OSDN Git Service

Merge "Cast hidl_pointer<T> to void*." am: 6033952ff1 am: fbedd83ffe am: b5a4e86c5f
authorMartijn Coenen <maco@google.com>
Fri, 18 Nov 2016 08:17:22 +0000 (08:17 +0000)
committerandroid-build-merger <android-build-merger@google.com>
Fri, 18 Nov 2016 08:17:22 +0000 (08:17 +0000)
am: fdbc9d7d52

Change-Id: I3e96ec07eb26e4df7ca610127c4952b97d057153

350 files changed:
audio/2.0/Android.bp [new file with mode: 0644]
audio/2.0/Android.mk [new file with mode: 0644]
audio/2.0/IDevice.hal [new file with mode: 0644]
audio/2.0/IDevicesFactory.hal [new file with mode: 0644]
audio/2.0/IPrimaryDevice.hal [new file with mode: 0644]
audio/2.0/IStream.hal [new file with mode: 0644]
audio/2.0/IStreamIn.hal [new file with mode: 0644]
audio/2.0/IStreamOut.hal [new file with mode: 0644]
audio/2.0/IStreamOutCallback.hal [new file with mode: 0644]
audio/2.0/default/Android.mk [new file with mode: 0644]
audio/2.0/default/Conversions.cpp [new file with mode: 0644]
audio/2.0/default/Conversions.h [new file with mode: 0644]
audio/2.0/default/Device.cpp [new file with mode: 0644]
audio/2.0/default/Device.h [new file with mode: 0644]
audio/2.0/default/DevicesFactory.cpp [new file with mode: 0644]
audio/2.0/default/DevicesFactory.h [new file with mode: 0644]
audio/2.0/default/ParametersUtil.cpp [new file with mode: 0644]
audio/2.0/default/ParametersUtil.h [new file with mode: 0644]
audio/2.0/default/PrimaryDevice.cpp [new file with mode: 0644]
audio/2.0/default/PrimaryDevice.h [new file with mode: 0644]
audio/2.0/default/Stream.cpp [new file with mode: 0644]
audio/2.0/default/Stream.h [new file with mode: 0644]
audio/2.0/default/StreamIn.cpp [new file with mode: 0644]
audio/2.0/default/StreamIn.h [new file with mode: 0644]
audio/2.0/default/StreamOut.cpp [new file with mode: 0644]
audio/2.0/default/StreamOut.h [new file with mode: 0644]
audio/2.0/default/android.hardware.audio@2.0-service.rc [new file with mode: 0644]
audio/2.0/default/service.cpp [new file with mode: 0644]
audio/2.0/types.hal [new file with mode: 0644]
audio/Android.bp [new file with mode: 0644]
audio/common/2.0/Android.bp [new file with mode: 0644]
audio/common/2.0/Android.mk [new file with mode: 0644]
audio/common/2.0/default/Android.mk [new file with mode: 0644]
audio/common/2.0/default/EffectMap.cpp [new file with mode: 0644]
audio/common/2.0/default/EffectMap.h [new file with mode: 0644]
audio/common/2.0/types.hal [new file with mode: 0644]
audio/common/2.0/vts/types.vts [new file with mode: 0644]
audio/effect/2.0/Android.bp [new file with mode: 0644]
audio/effect/2.0/Android.mk [new file with mode: 0644]
audio/effect/2.0/IAcousticEchoCancelerEffect.hal [new file with mode: 0644]
audio/effect/2.0/IAutomaticGainControlEffect.hal [new file with mode: 0644]
audio/effect/2.0/IBassBoostEffect.hal [new file with mode: 0644]
audio/effect/2.0/IDownmixEffect.hal [new file with mode: 0644]
audio/effect/2.0/IEffect.hal [new file with mode: 0644]
audio/effect/2.0/IEffectBufferProviderCallback.hal [new file with mode: 0644]
audio/effect/2.0/IEffectsFactory.hal [new file with mode: 0644]
audio/effect/2.0/IEnvironmentalReverbEffect.hal [new file with mode: 0644]
audio/effect/2.0/IEqualizerEffect.hal [new file with mode: 0644]
audio/effect/2.0/ILoudnessEnhancerEffect.hal [new file with mode: 0644]
audio/effect/2.0/INoiseSuppressionEffect.hal [new file with mode: 0644]
audio/effect/2.0/IPresetReverbEffect.hal [new file with mode: 0644]
audio/effect/2.0/IVirtualizerEffect.hal [new file with mode: 0644]
audio/effect/2.0/IVisualizerEffect.hal [new file with mode: 0644]
audio/effect/2.0/default/AcousticEchoCancelerEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/AcousticEchoCancelerEffect.h [new file with mode: 0644]
audio/effect/2.0/default/Android.mk [new file with mode: 0644]
audio/effect/2.0/default/AutomaticGainControlEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/AutomaticGainControlEffect.h [new file with mode: 0644]
audio/effect/2.0/default/BassBoostEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/BassBoostEffect.h [new file with mode: 0644]
audio/effect/2.0/default/Conversions.cpp [new file with mode: 0644]
audio/effect/2.0/default/Conversions.h [new file with mode: 0644]
audio/effect/2.0/default/DownmixEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/DownmixEffect.h [new file with mode: 0644]
audio/effect/2.0/default/Effect.cpp [new file with mode: 0644]
audio/effect/2.0/default/Effect.h [new file with mode: 0644]
audio/effect/2.0/default/EffectsFactory.cpp [new file with mode: 0644]
audio/effect/2.0/default/EffectsFactory.h [new file with mode: 0644]
audio/effect/2.0/default/EnvironmentalReverbEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/EnvironmentalReverbEffect.h [new file with mode: 0644]
audio/effect/2.0/default/EqualizerEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/EqualizerEffect.h [new file with mode: 0644]
audio/effect/2.0/default/LoudnessEnhancerEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/LoudnessEnhancerEffect.h [new file with mode: 0644]
audio/effect/2.0/default/NoiseSuppressionEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/NoiseSuppressionEffect.h [new file with mode: 0644]
audio/effect/2.0/default/PresetReverbEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/PresetReverbEffect.h [new file with mode: 0644]
audio/effect/2.0/default/VirtualizerEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/VirtualizerEffect.h [new file with mode: 0644]
audio/effect/2.0/default/VisualizerEffect.cpp [new file with mode: 0644]
audio/effect/2.0/default/VisualizerEffect.h [new file with mode: 0644]
audio/effect/2.0/types.hal [new file with mode: 0644]
audio/effect/2.0/vts/functional/Android.bp [new file with mode: 0644]
audio/effect/2.0/vts/functional/audio_effect_hidl_hal_test.cpp [new file with mode: 0644]
biometrics/Android.bp [new file with mode: 0644]
biometrics/fingerprint/2.1/Android.bp [new file with mode: 0644]
biometrics/fingerprint/2.1/IBiometricsFingerprint.hal [new file with mode: 0644]
biometrics/fingerprint/2.1/IBiometricsFingerprintClientCallback.hal [new file with mode: 0644]
biometrics/fingerprint/2.1/default/Android.mk [new file with mode: 0644]
biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp [new file with mode: 0644]
biometrics/fingerprint/2.1/default/BiometricsFingerprint.h [new file with mode: 0644]
biometrics/fingerprint/2.1/default/android.hardware.biometrics.fingerprint@2.1-service.rc [new file with mode: 0644]
biometrics/fingerprint/2.1/default/service.cpp [new file with mode: 0644]
biometrics/fingerprint/2.1/types.hal [new file with mode: 0644]
boot/1.0/vts/Android.mk [new file with mode: 0644]
boot/1.0/vts/BootControl.vts [new file with mode: 0644]
boot/1.0/vts/types.vts [new file with mode: 0644]
broadcastradio/1.0/Android.bp [new file with mode: 0644]
broadcastradio/1.0/IBroadcastRadio.hal [new file with mode: 0644]
broadcastradio/1.0/IBroadcastRadioFactory.hal [new file with mode: 0644]
broadcastradio/1.0/ITuner.hal [new file with mode: 0644]
broadcastradio/1.0/ITunerCallback.hal [new file with mode: 0644]
broadcastradio/1.0/types.hal [new file with mode: 0644]
broadcastradio/Android.bp [new file with mode: 0644]
contexthub/1.0/Android.bp [new file with mode: 0644]
contexthub/1.0/Android.mk [new file with mode: 0644]
contexthub/1.0/IContexthub.hal [new file with mode: 0644]
contexthub/1.0/IContexthubCallback.hal [new file with mode: 0644]
contexthub/1.0/types.hal [new file with mode: 0644]
contexthub/Android.bp [new file with mode: 0644]
example/Android.bp [new file with mode: 0644]
example/extension/light/2.0/Android.bp [new file with mode: 0644]
example/extension/light/2.0/Android.mk [new file with mode: 0644]
example/extension/light/2.0/IExtLight.hal [new file with mode: 0644]
example/extension/light/2.0/default/Android.mk [new file with mode: 0644]
example/extension/light/2.0/default/Light.cpp [new file with mode: 0644]
example/extension/light/2.0/default/Light.h [new file with mode: 0644]
example/extension/light/2.0/default/android.hardware.example.extension.light@2.0-service.rc [new file with mode: 0644]
example/extension/light/2.0/default/service.cpp [new file with mode: 0644]
example/extension/light/2.0/types.hal [new file with mode: 0644]
gnss/1.0/Android.bp [new file with mode: 0644]
gnss/1.0/IAGnss.hal [new file with mode: 0644]
gnss/1.0/IAGnssCallback.hal [new file with mode: 0644]
gnss/1.0/IAGnssRil.hal [new file with mode: 0644]
gnss/1.0/IAGnssRilCallback.hal [new file with mode: 0644]
gnss/1.0/IGnss.hal [new file with mode: 0644]
gnss/1.0/IGnssCallback.hal [new file with mode: 0644]
gnss/1.0/IGnssDebug.hal [new file with mode: 0644]
gnss/1.0/IGnssGeofenceCallback.hal [new file with mode: 0644]
gnss/1.0/IGnssGeofencing.hal [new file with mode: 0644]
gnss/1.0/IGnssMeasurement.hal [new file with mode: 0644]
gnss/1.0/IGnssMeasurementCallback.hal [new file with mode: 0644]
gnss/1.0/IGnssNavigationMessage.hal [new file with mode: 0644]
gnss/1.0/IGnssNavigationMessageCallback.hal [new file with mode: 0644]
gnss/1.0/IGnssNi.hal [new file with mode: 0644]
gnss/1.0/IGnssNiCallback.hal [new file with mode: 0644]
gnss/1.0/IGnssXtra.hal [new file with mode: 0644]
gnss/1.0/IGnssXtraCallback.hal [new file with mode: 0644]
gnss/1.0/types.hal [new file with mode: 0644]
gnss/Android.bp [new file with mode: 0644]
graphics/Android.bp [new file with mode: 0644]
graphics/allocator/2.0/Android.bp [new file with mode: 0644]
graphics/allocator/2.0/Android.mk [new file with mode: 0644]
graphics/allocator/2.0/IAllocator.hal [new file with mode: 0644]
graphics/allocator/2.0/default/Android.bp [new file with mode: 0644]
graphics/allocator/2.0/default/Gralloc.cpp [new file with mode: 0644]
graphics/allocator/2.0/default/Gralloc.h [new file with mode: 0644]
graphics/allocator/2.0/default/android.hardware.graphics.allocator@2.0-service.rc [new file with mode: 0644]
graphics/allocator/2.0/default/gralloc1-adapter.c [new file with mode: 0644]
graphics/allocator/2.0/default/gralloc1-adapter.h [new file with mode: 0644]
graphics/allocator/2.0/default/service.cpp [new file with mode: 0644]
graphics/allocator/2.0/types.hal [new file with mode: 0644]
graphics/common/1.0/Android.bp [new file with mode: 0644]
graphics/common/1.0/Android.mk [new file with mode: 0644]
graphics/common/1.0/types.hal [new file with mode: 0644]
graphics/composer/2.1/Android.bp [new file with mode: 0644]
graphics/composer/2.1/IComposer.hal [new file with mode: 0644]
graphics/composer/2.1/IComposerCallback.hal [new file with mode: 0644]
graphics/composer/2.1/default/Android.bp [new file with mode: 0644]
graphics/composer/2.1/default/Hwc.cpp [new file with mode: 0644]
graphics/composer/2.1/default/Hwc.h [new file with mode: 0644]
graphics/composer/2.1/default/android.hardware.graphics.composer@2.1-service.rc [new file with mode: 0644]
graphics/composer/2.1/default/service.cpp [new file with mode: 0644]
graphics/composer/2.1/types.hal [new file with mode: 0644]
graphics/mapper/2.0/Android.bp [new file with mode: 0644]
graphics/mapper/2.0/default/Android.bp [new file with mode: 0644]
graphics/mapper/2.0/default/GrallocMapper.cpp [new file with mode: 0644]
graphics/mapper/2.0/include/android/hardware/graphics/mapper/2.0/IMapper.h [new file with mode: 0644]
graphics/mapper/2.0/include/android/hardware/graphics/mapper/2.0/types.h [new file with mode: 0644]
health/1.0/Android.bp [new file with mode: 0644]
health/1.0/Android.mk [new file with mode: 0644]
health/1.0/IHealth.hal [new file with mode: 0644]
health/1.0/default/Android.mk [new file with mode: 0644]
health/1.0/default/Health.cpp [new file with mode: 0644]
health/1.0/default/Health.h [new file with mode: 0644]
health/1.0/default/HealthService.cpp [new file with mode: 0644]
health/1.0/default/android.hardware.health@1.0-service.rc [new file with mode: 0644]
health/1.0/default/convert.cpp [new file with mode: 0644]
health/1.0/default/include/hal_conversion.h [new file with mode: 0644]
health/1.0/default/libhealthd/Android.mk [new file with mode: 0644]
health/1.0/default/libhealthd/healthd_board_default.cpp [new file with mode: 0644]
health/1.0/types.hal [new file with mode: 0644]
health/Android.bp [new file with mode: 0644]
light/2.0/Android.bp [new file with mode: 0644]
light/2.0/Android.mk [new file with mode: 0644]
light/2.0/ILight.hal [new file with mode: 0644]
light/2.0/default/Android.mk [new file with mode: 0644]
light/2.0/default/Light.cpp [new file with mode: 0644]
light/2.0/default/Light.h [new file with mode: 0644]
light/2.0/default/android.hardware.light@2.0-service.rc [new file with mode: 0644]
light/2.0/default/service.cpp [new file with mode: 0644]
light/2.0/types.hal [new file with mode: 0644]
light/2.0/vts/Android.mk [new file with mode: 0644]
light/2.0/vts/Light.vts [new file with mode: 0644]
light/2.0/vts/types.vts [new file with mode: 0644]
light/Android.bp [new file with mode: 0644]
media/1.0/Android.bp [new file with mode: 0644]
media/1.0/types.hal [new file with mode: 0644]
media/Android.bp [new file with mode: 0644]
media/omx/1.0/Android.bp [new file with mode: 0644]
media/omx/1.0/IGraphicBufferSource.hal [new file with mode: 0644]
media/omx/1.0/IOmx.hal [new file with mode: 0644]
media/omx/1.0/IOmxBufferSource.hal [new file with mode: 0644]
media/omx/1.0/IOmxNode.hal [new file with mode: 0644]
media/omx/1.0/IOmxObserver.hal [new file with mode: 0644]
media/omx/1.0/types.hal [new file with mode: 0644]
memtrack/1.0/Android.bp [new file with mode: 0644]
memtrack/1.0/Android.mk [new file with mode: 0644]
memtrack/1.0/IMemtrack.hal [new file with mode: 0644]
memtrack/1.0/default/Android.bp [new file with mode: 0644]
memtrack/1.0/default/Memtrack.cpp [new file with mode: 0644]
memtrack/1.0/default/Memtrack.h [new file with mode: 0644]
memtrack/1.0/default/android.hardware.memtrack@1.0-service.rc [new file with mode: 0644]
memtrack/1.0/default/service.cpp [new file with mode: 0644]
memtrack/1.0/types.hal [new file with mode: 0644]
memtrack/1.0/vts/Android.mk [new file with mode: 0644]
memtrack/1.0/vts/Memtrack.vts [new file with mode: 0644]
memtrack/1.0/vts/types.vts [new file with mode: 0644]
memtrack/Android.bp [new file with mode: 0644]
nfc/1.0/vts/Android.mk [new file with mode: 0644]
nfc/1.0/vts/Nfc.vts [new file with mode: 0644]
nfc/1.0/vts/NfcClientCallback.vts [new file with mode: 0644]
nfc/1.0/vts/functional/Android.bp [new file with mode: 0644]
nfc/1.0/vts/functional/nfc_hidl_hal_test.cpp [new file with mode: 0644]
nfc/1.0/vts/types.vts [new file with mode: 0644]
nfc/Android.bp
power/1.0/Android.bp [new file with mode: 0644]
power/1.0/Android.mk [new file with mode: 0644]
power/1.0/IPower.hal [new file with mode: 0644]
power/1.0/default/Android.bp [new file with mode: 0644]
power/1.0/default/Power.cpp [new file with mode: 0644]
power/1.0/default/Power.h [new file with mode: 0644]
power/1.0/default/android.hardware.power@1.0-service.rc [new file with mode: 0644]
power/1.0/default/service.cpp [new file with mode: 0644]
power/1.0/types.hal [new file with mode: 0644]
power/1.0/vts/Android.mk [new file with mode: 0644]
power/1.0/vts/Power.vts [new file with mode: 0644]
power/1.0/vts/types.vts [new file with mode: 0644]
power/Android.bp [new file with mode: 0644]
sensors/1.0/Android.bp [new file with mode: 0644]
sensors/1.0/Android.mk [new file with mode: 0644]
sensors/1.0/ISensors.hal [new file with mode: 0644]
sensors/1.0/default/Android.bp [new file with mode: 0644]
sensors/1.0/default/Android.mk [new file with mode: 0644]
sensors/1.0/default/Sensors.cpp [new file with mode: 0644]
sensors/1.0/default/Sensors.h [new file with mode: 0644]
sensors/1.0/default/android.hardware.sensors@1.0-service.rc [new file with mode: 0644]
sensors/1.0/default/convert.cpp [new file with mode: 0644]
sensors/1.0/default/include/sensors/convert.h [new file with mode: 0644]
sensors/1.0/default/service.cpp [new file with mode: 0644]
sensors/1.0/types.hal [new file with mode: 0644]
sensors/Android.bp [new file with mode: 0644]
soundtrigger/2.0/Android.bp [new file with mode: 0644]
soundtrigger/2.0/ISoundTriggerHw.hal [new file with mode: 0644]
soundtrigger/2.0/ISoundTriggerHwCallback.hal [new file with mode: 0644]
soundtrigger/2.0/default/Android.mk [new file with mode: 0644]
soundtrigger/2.0/default/SoundTriggerHalImpl.cpp [new file with mode: 0644]
soundtrigger/2.0/default/SoundTriggerHalImpl.h [new file with mode: 0644]
soundtrigger/2.0/types.hal [new file with mode: 0644]
soundtrigger/Android.bp [new file with mode: 0644]
thermal/1.0/Android.bp [new file with mode: 0644]
thermal/1.0/Android.mk [new file with mode: 0644]
thermal/1.0/IThermal.hal [new file with mode: 0644]
thermal/1.0/default/Android.bp [new file with mode: 0644]
thermal/1.0/default/Android.mk [new file with mode: 0644]
thermal/1.0/default/Thermal.cpp [new file with mode: 0644]
thermal/1.0/default/Thermal.h [new file with mode: 0644]
thermal/1.0/default/android.hardware.thermal@1.0-service.rc [new file with mode: 0644]
thermal/1.0/default/service.cpp [new file with mode: 0644]
thermal/1.0/types.hal [new file with mode: 0644]
thermal/1.0/vts/Android.mk [new file with mode: 0644]
thermal/1.0/vts/Thermal.vts [new file with mode: 0644]
thermal/1.0/vts/functional/Android.bp [new file with mode: 0644]
thermal/1.0/vts/functional/thermal_hidl_hal_test.cpp [new file with mode: 0644]
thermal/1.0/vts/types.vts [new file with mode: 0644]
thermal/Android.bp [new file with mode: 0644]
tv/Android.bp [new file with mode: 0644]
tv/cec/1.0/Android.bp [new file with mode: 0644]
tv/cec/1.0/Android.mk [new file with mode: 0644]
tv/cec/1.0/IHdmiCec.hal [new file with mode: 0644]
tv/cec/1.0/IHdmiCecCallback.hal [new file with mode: 0644]
tv/cec/1.0/default/Android.mk [new file with mode: 0644]
tv/cec/1.0/default/HdmiCec.cpp [new file with mode: 0644]
tv/cec/1.0/default/HdmiCec.h [new file with mode: 0644]
tv/cec/1.0/default/android.hardware.tv.cec@1.0-service.rc [new file with mode: 0644]
tv/cec/1.0/default/service.cpp [new file with mode: 0644]
tv/cec/1.0/types.hal [new file with mode: 0644]
tv/input/1.0/Android.bp [new file with mode: 0644]
tv/input/1.0/ITvInput.hal [new file with mode: 0644]
tv/input/1.0/ITvInputCallback.hal [new file with mode: 0644]
tv/input/1.0/default/Android.mk [new file with mode: 0644]
tv/input/1.0/default/TvInput.cpp [new file with mode: 0644]
tv/input/1.0/default/TvInput.h [new file with mode: 0644]
tv/input/1.0/default/android.hardware.tv.input@1.0-service.rc [new file with mode: 0644]
tv/input/1.0/default/service.cpp [new file with mode: 0644]
tv/input/1.0/types.hal [new file with mode: 0644]
vehicle/2.0/Android.bp [new file with mode: 0644]
vehicle/2.0/Android.mk [new file with mode: 0644]
vehicle/2.0/IVehicle.hal [new file with mode: 0644]
vehicle/2.0/IVehicleCallback.hal [new file with mode: 0644]
vehicle/2.0/default/Android.mk [new file with mode: 0644]
vehicle/2.0/default/VehicleHal.h [new file with mode: 0644]
vehicle/2.0/default/VehicleService.cpp [new file with mode: 0644]
vehicle/2.0/default/android.hardware.vehicle@2.0-service.rc [new file with mode: 0644]
vehicle/2.0/default/impl/DefaultConfig.h [new file with mode: 0644]
vehicle/2.0/default/impl/DefaultVehicleHal.cpp [new file with mode: 0644]
vehicle/2.0/default/impl/DefaultVehicleHal.h [new file with mode: 0644]
vehicle/2.0/default/tests/SubscriptionManager_test.cpp [new file with mode: 0644]
vehicle/2.0/default/tests/VehicleHalManager_test.cpp [new file with mode: 0644]
vehicle/2.0/default/tests/VehicleHalTestUtils.h [new file with mode: 0644]
vehicle/2.0/default/tests/VehicleObjectPool_test.cpp [new file with mode: 0644]
vehicle/2.0/default/tests/VehiclePropConfigIndex_test.cpp [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/ConcurrentQueue.h [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/SubscriptionManager.cpp [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/SubscriptionManager.h [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/VehicleHalManager.cpp [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/VehicleHalManager.h [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/VehicleObjectPool.h [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/VehiclePropConfigIndex.h [new file with mode: 0644]
vehicle/2.0/default/vehicle_hal_manager/VehicleUtils.h [new file with mode: 0644]
vehicle/2.0/types.hal [new file with mode: 0644]
vehicle/Android.bp [new file with mode: 0644]
vibrator/1.0/Android.bp [new file with mode: 0644]
vibrator/1.0/Android.mk [new file with mode: 0644]
vibrator/1.0/IVibrator.hal [new file with mode: 0644]
vibrator/1.0/default/Android.bp [new file with mode: 0644]
vibrator/1.0/default/Android.mk [new file with mode: 0644]
vibrator/1.0/default/Vibrator.cpp [new file with mode: 0644]
vibrator/1.0/default/Vibrator.h [new file with mode: 0644]
vibrator/1.0/default/android.hardware.vibrator@1.0-service.rc [new file with mode: 0644]
vibrator/1.0/default/service.cpp [new file with mode: 0644]
vibrator/1.0/types.hal [new file with mode: 0644]
vibrator/1.0/vts/Android.mk [new file with mode: 0644]
vibrator/1.0/vts/Vibrator.vts [new file with mode: 0644]
vibrator/1.0/vts/functional/Android.bp [new file with mode: 0644]
vibrator/1.0/vts/functional/vibrator_hidl_hal_test.cpp [new file with mode: 0644]
vibrator/1.0/vts/types.vts [new file with mode: 0644]
vibrator/Android.bp [new file with mode: 0644]
vr/1.0/Android.bp [new file with mode: 0644]
vr/1.0/Android.mk [new file with mode: 0644]
vr/1.0/IVr.hal [new file with mode: 0644]
vr/1.0/default/Android.bp [new file with mode: 0644]
vr/1.0/default/Vr.cpp [new file with mode: 0644]
vr/1.0/default/Vr.h [new file with mode: 0644]
vr/1.0/default/android.hardware.vr@1.0-service.rc [new file with mode: 0644]
vr/1.0/default/service.cpp [new file with mode: 0644]
vr/1.0/vts/Android.mk [new file with mode: 0644]
vr/1.0/vts/Vr.vts [new file with mode: 0644]
vr/Android.bp [new file with mode: 0644]

diff --git a/audio/2.0/Android.bp b/audio/2.0/Android.bp
new file mode 100644 (file)
index 0000000..2ded34b
--- /dev/null
@@ -0,0 +1,103 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.audio@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.audio@2.0",
+    srcs: [
+        "types.hal",
+        "IDevice.hal",
+        "IDevicesFactory.hal",
+        "IPrimaryDevice.hal",
+        "IStream.hal",
+        "IStreamIn.hal",
+        "IStreamOut.hal",
+        "IStreamOutCallback.hal",
+    ],
+    out: [
+        "android/hardware/audio/2.0/types.cpp",
+        "android/hardware/audio/2.0/DeviceAll.cpp",
+        "android/hardware/audio/2.0/DevicesFactoryAll.cpp",
+        "android/hardware/audio/2.0/PrimaryDeviceAll.cpp",
+        "android/hardware/audio/2.0/StreamAll.cpp",
+        "android/hardware/audio/2.0/StreamInAll.cpp",
+        "android/hardware/audio/2.0/StreamOutAll.cpp",
+        "android/hardware/audio/2.0/StreamOutCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.audio@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.audio@2.0",
+    srcs: [
+        "types.hal",
+        "IDevice.hal",
+        "IDevicesFactory.hal",
+        "IPrimaryDevice.hal",
+        "IStream.hal",
+        "IStreamIn.hal",
+        "IStreamOut.hal",
+        "IStreamOutCallback.hal",
+    ],
+    out: [
+        "android/hardware/audio/2.0/types.h",
+        "android/hardware/audio/2.0/IDevice.h",
+        "android/hardware/audio/2.0/IHwDevice.h",
+        "android/hardware/audio/2.0/BnDevice.h",
+        "android/hardware/audio/2.0/BpDevice.h",
+        "android/hardware/audio/2.0/BsDevice.h",
+        "android/hardware/audio/2.0/IDevicesFactory.h",
+        "android/hardware/audio/2.0/IHwDevicesFactory.h",
+        "android/hardware/audio/2.0/BnDevicesFactory.h",
+        "android/hardware/audio/2.0/BpDevicesFactory.h",
+        "android/hardware/audio/2.0/BsDevicesFactory.h",
+        "android/hardware/audio/2.0/IPrimaryDevice.h",
+        "android/hardware/audio/2.0/IHwPrimaryDevice.h",
+        "android/hardware/audio/2.0/BnPrimaryDevice.h",
+        "android/hardware/audio/2.0/BpPrimaryDevice.h",
+        "android/hardware/audio/2.0/BsPrimaryDevice.h",
+        "android/hardware/audio/2.0/IStream.h",
+        "android/hardware/audio/2.0/IHwStream.h",
+        "android/hardware/audio/2.0/BnStream.h",
+        "android/hardware/audio/2.0/BpStream.h",
+        "android/hardware/audio/2.0/BsStream.h",
+        "android/hardware/audio/2.0/IStreamIn.h",
+        "android/hardware/audio/2.0/IHwStreamIn.h",
+        "android/hardware/audio/2.0/BnStreamIn.h",
+        "android/hardware/audio/2.0/BpStreamIn.h",
+        "android/hardware/audio/2.0/BsStreamIn.h",
+        "android/hardware/audio/2.0/IStreamOut.h",
+        "android/hardware/audio/2.0/IHwStreamOut.h",
+        "android/hardware/audio/2.0/BnStreamOut.h",
+        "android/hardware/audio/2.0/BpStreamOut.h",
+        "android/hardware/audio/2.0/BsStreamOut.h",
+        "android/hardware/audio/2.0/IStreamOutCallback.h",
+        "android/hardware/audio/2.0/IHwStreamOutCallback.h",
+        "android/hardware/audio/2.0/BnStreamOutCallback.h",
+        "android/hardware/audio/2.0/BpStreamOutCallback.h",
+        "android/hardware/audio/2.0/BsStreamOutCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.audio@2.0",
+    generated_sources: ["android.hardware.audio@2.0_genc++"],
+    generated_headers: ["android.hardware.audio@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.audio@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.audio.common@2.0",
+        "android.hardware.audio.effect@2.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.audio.common@2.0",
+        "android.hardware.audio.effect@2.0",
+    ],
+}
diff --git a/audio/2.0/Android.mk b/audio/2.0/Android.mk
new file mode 100644 (file)
index 0000000..8557ea2
--- /dev/null
@@ -0,0 +1,44 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.audio@2.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/audio/2.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/IDevice.hal
+$(GEN): $(LOCAL_PATH)/IDevicesFactory.hal
+$(GEN): $(LOCAL_PATH)/IPrimaryDevice.hal
+$(GEN): $(LOCAL_PATH)/IStream.hal
+$(GEN): $(LOCAL_PATH)/IStreamIn.hal
+$(GEN): $(LOCAL_PATH)/IStreamOut.hal
+$(GEN): $(LOCAL_PATH)/IStreamOutCallback.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.audio@2.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/audio/2.0/IDevice.hal b/audio/2.0/IDevice.hal
new file mode 100644 (file)
index 0000000..38bfe21
--- /dev/null
@@ -0,0 +1,227 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+import android.hardware.audio.common@2.0;
+import IStreamIn;
+import IStreamOut;
+
+interface IDevice {
+    typedef android.hardware.audio@2.0::Result Result;
+
+    /*
+     * Returns whether the audio hardware interface has been initialized.
+     *
+     * @return retval OK on success, NOT_INITIALIZED on failure.
+     */
+    initCheck() generates (Result retval);
+
+    /*
+     * Sets the audio volume for all audio activities other than voice call. If
+     * NOT_SUPPORTED is returned, the software mixer will emulate this
+     * capability.
+     *
+     * @param volume 1.0f means unity, 0.0f is zero.
+     * @return retval operation completion status.
+     */
+    setMasterVolume(float volume) generates (Result retval);
+
+    /*
+     * Get the current master volume value for the HAL, if the HAL supports
+     * master volume control. For example, AudioFlinger will query this value
+     * from the primary audio HAL when the service starts and use the value for
+     * setting the initial master volume across all HALs. HALs which do not
+     * support this method must return NOT_SUPPORTED in 'retval'.
+     *
+     * @return retval operation completion status.
+     * @return volume 1.0f means unity, 0.0f is zero.
+     */
+    getMasterVolume() generates (Result retval, float volume);
+
+    /*
+     * Sets microphone muting state.
+     *
+     * @param mute whether microphone is muted.
+     * @return retval operation completion status.
+     */
+    setMicMute(bool mute) generates (Result retval);
+
+    /*
+     * Gets whether microphone is muted.
+     *
+     * @return retval operation completion status.
+     * @return mute whether microphone is muted.
+     */
+    getMicMute() generates (Result retval, bool mute);
+
+    /*
+     * Set the audio mute status for all audio activities. If the return value
+     * is NOT_SUPPORTED, the software mixer will emulate this capability.
+     *
+     * @param mute whether audio is muted.
+     * @return retval operation completion status.
+     */
+    setMasterMute(bool mute) generates (Result retval);
+
+    /**
+     * Get the current master mute status for the HAL, if the HAL supports
+     * master mute control. AudioFlinger will query this value from the primary
+     * audio HAL when the service starts and use the value for setting the
+     * initial master mute across all HALs. HAL must indicate that the feature
+     * is not supported by returning NOT_SUPPORTED status.
+     *
+     * @return retval operation completion status.
+     * @return mute whether audio is muted.
+     */
+    getMasterMute() generates (Result retval, bool mute);
+
+    /*
+     * Returns audio input buffer size according to parameters passed or
+     * INVALID_ARGUMENTS if one of the parameters is not supported.
+     *
+     * @param config audio configuration.
+     * @return retval operation completion status.
+     * @return bufferSize input buffer size in bytes.
+     */
+    getInputBufferSize(AudioConfig config)
+            generates (Result retval, uint64_t bufferSize);
+
+    /*
+     * This method creates and opens the audio hardware output stream.
+     *
+     * @param ioHandle handle assigned by AudioFlinger.
+     * @param device device type and (if needed) address.
+     * @param config stream configuration.
+     * @param flags additional flags.
+     * @return retval operation completion status.
+     * @return outStream created output stream.
+     */
+    openOutputStream(
+            AudioIoHandle ioHandle,
+            DeviceAddress device,
+            AudioConfig config,
+            AudioOutputFlag flags) generates (Result retval, IStreamOut outStream);
+
+    /*
+     * This method creates and opens the audio hardware input stream.
+     *
+     * @param ioHandle handle assigned by AudioFlinger.
+     * @param device device type and (if needed) address.
+     * @param config stream configuration.
+     * @param flags additional flags.
+     * @param source source specification.
+     * @return retval operation completion status.
+     * @return inStream created input stream.
+     */
+    openInputStream(
+            AudioIoHandle ioHandle,
+            DeviceAddress device,
+            AudioConfig config,
+            AudioInputFlag flags,
+            AudioSource source) generates (Result retval, IStreamIn inStream);
+
+    /*
+     * Creates an audio patch between several source and sink ports.  The handle
+     * is allocated by the HAL and must be unique for this audio HAL module.
+     *
+     * @param sources patch sources.
+     * @param sinks patch sinks.
+     * @return retval operation completion status.
+     * @return patch created patch handle.
+     */
+    createAudioPatch(vec<AudioPortConfig> sources, vec<AudioPortConfig> sinks)
+            generates (Result retval, AudioPatchHandle patch);
+
+    /*
+     * Release an audio patch.
+     *
+     * @param patch patch handle.
+     * @return retval operation completion status.
+     */
+    releaseAudioPatch(AudioPatchHandle patch) generates (Result retval);
+
+    /*
+     * Returns the list of supported attributes for a given audio port.
+     *
+     * As input, 'port' contains the information (type, role, address etc...)
+     * needed by the HAL to identify the port.
+     *
+     * As output, 'port' contains possible attributes (sampling rates, formats,
+     * channel masks, gain controllers...) for this port.
+     *
+     * @param port port identifier.
+     * @return retval operation completion status.
+     * @return port port descriptor with all parameters filled up.
+     */
+    getAudioPort(AudioPort port)
+            generates (Result retval, AudioPort port);
+
+    /*
+     * Set audio port configuration.
+     *
+     * @param config audio port configuration.
+     * @return retval operation completion status.
+     */
+    setAudioPortConfig(AudioPortConfig config) generates (Result retval);
+
+    /*
+     * Gets the HW synchronization source of the device. Calling this method is
+     * equivalent to getting AUDIO_PARAMETER_HW_AV_SYNC on the legacy HAL.
+     *
+     * @return hwAvSync HW synchronization source
+     */
+    getHwAvSync() generates (AudioHwSync hwAvSync);
+
+    /*
+     * Sets whether the screen is on. Calling this method is equivalent to
+     * setting AUDIO_PARAMETER_KEY_SCREEN_STATE on the legacy HAL.
+     *
+     * @param turnedOn whether the screen is turned on.
+     * @return retval operation completion status.
+     */
+    setScreenState(bool turnedOn) generates (Result retval);
+
+    /*
+     * Generic method for retrieving vendor-specific parameter values.
+     * The framework does not interpret the parameters, they are passed
+     * in an opaque manner between a vendor application and HAL.
+     *
+     * @param keys parameter keys.
+     * @return retval operation completion status.
+     * @return parameters parameter key value pairs.
+     */
+    getParameters(vec<string> keys)
+            generates (Result retval, vec<ParameterValue> parameters);
+
+    /*
+     * Generic method for setting vendor-specific parameter values.
+     * The framework does not interpret the parameters, they are passed
+     * in an opaque manner between a vendor application and HAL.
+     *
+     * @param parameters parameter key value pairs.
+     * @return retval operation completion status.
+     */
+    setParameters(vec<ParameterValue> parameters) generates (Result retval);
+
+    /*
+     * Dumps information about the stream into the provided file descriptor.
+     * This is used for the dumpsys facility.
+     *
+     * @param fd dump file descriptor.
+     */
+    debugDump(handle fd);
+};
diff --git a/audio/2.0/IDevicesFactory.hal b/audio/2.0/IDevicesFactory.hal
new file mode 100644 (file)
index 0000000..a4e6956
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+import android.hardware.audio.common@2.0;
+import IDevice;
+
+interface IDevicesFactory {
+    typedef android.hardware.audio@2.0::Result Result;
+
+    enum Device {
+        PRIMARY,
+        A2DP,
+        USB,
+        R_SUBMIX
+    };
+
+    /*
+     * Opens an audio device. To close the device, it is necessary to release
+     * references to the returned device object.
+     *
+     * @param device device type.
+     * @return retval operation completion status. Returns INVALID_ARGUMENTS
+     *         if there is no corresponding hardware module found,
+     *         NOT_INITIALIZED if an error occured while opening the hardware
+     *         module.
+     * @return result the interface for the created device.
+     */
+    openDevice(Device device) generates (Result retval, IDevice result);
+};
diff --git a/audio/2.0/IPrimaryDevice.hal b/audio/2.0/IPrimaryDevice.hal
new file mode 100644 (file)
index 0000000..6beddfe
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+import android.hardware.audio.common@2.0;
+import IDevice;
+
+interface IPrimaryDevice extends IDevice {
+    typedef android.hardware.audio@2.0::Result Result;
+
+    /*
+     * Sets the audio volume of a voice call.
+     *
+     * @param volume 1.0f means unity, 0.0f is zero.
+     * @return retval operation completion status.
+     */
+    setVoiceVolume(float volume) generates (Result retval);
+
+    /*
+     * This method is used to notify the HAL about audio mode changes.
+     *
+     * @param mode new mode.
+     * @return retval operation completion status.
+     */
+    setMode(AudioMode mode) generates (Result retval);
+
+    /*
+     * Gets whether BT SCO Noise Reduction and Echo Cancellation are enabled.
+     * Calling this method is equivalent to getting AUDIO_PARAMETER_KEY_BT_NREC
+     * on the legacy HAL.
+     *
+     * @return retval operation completion status.
+     * @return enabled whether BT SCO NR + EC are enabled.
+     */
+    getBtScoNrecEnabled() generates (Result retval, bool enabled);
+
+    /*
+     * Sets whether BT SCO Noise Reduction and Echo Cancellation are enabled.
+     * Calling this method is equivalent to setting AUDIO_PARAMETER_KEY_BT_NREC
+     * on the legacy HAL.
+     *
+     * @param enabled whether BT SCO NR + EC are enabled.
+     * @return retval operation completion status.
+     */
+    setBtScoNrecEnabled(bool enabled) generates (Result retval);
+
+    /*
+     * Gets whether BT SCO Wideband mode is enabled. Calling this method is
+     * equivalent to getting AUDIO_PARAMETER_KEY_BT_SCO_WB on the legacy HAL.
+     *
+     * @return retval operation completion status.
+     * @return enabled whether BT Wideband is enabled.
+     */
+    getBtScoWidebandEnabled() generates (Result retval, bool enabled);
+
+    /*
+     * Sets whether BT SCO Wideband mode is enabled. Calling this method is
+     * equivalent to setting AUDIO_PARAMETER_KEY_BT_SCO_WB on the legacy HAL.
+     *
+     * @param enabled whether BT Wideband is enabled.
+     * @return retval operation completion status.
+     */
+    setBtScoWidebandEnabled(bool enabled) generates (Result retval);
+
+    enum TtyMode {
+        OFF,
+        VCO,
+        HCO,
+        FULL
+    };
+
+    /*
+     * Gets current TTY mode selection. Calling this method is equivalent to
+     * getting AUDIO_PARAMETER_KEY_TTY_MODE on the legacy HAL.
+     *
+     * @return retval operation completion status.
+     * @return mode TTY mode.
+     */
+    getTtyMode() generates (Result retval, TtyMode mode);
+
+    /*
+     * Sets current TTY mode. Calling this method is equivalent to setting
+     * AUDIO_PARAMETER_KEY_TTY_MODE on the legacy HAL.
+     *
+     * @param mode TTY mode.
+     * @return retval operation completion status.
+     */
+    setTtyMode(TtyMode mode) generates (Result retval);
+
+    /*
+     * Gets whether Hearing Aid Compatibility - Telecoil (HAC-T) mode is
+     * enabled. Calling this method is equivalent to getting
+     * AUDIO_PARAMETER_KEY_HAC on the legacy HAL.
+     *
+     * @return retval operation completion status.
+     * @return enabled whether HAC mode is enabled.
+     */
+    getHacEnabled() generates (Result retval, bool enabled);
+
+    /*
+     * Sets whether Hearing Aid Compatibility - Telecoil (HAC-T) mode is
+     * enabled. Calling this method is equivalent to setting
+     * AUDIO_PARAMETER_KEY_HAC on the legacy HAL.
+     *
+     * @param enabled whether HAC mode is enabled.
+     * @return retval operation completion status.
+     */
+    setHacEnabled(bool enabled) generates (Result retval);
+};
diff --git a/audio/2.0/IStream.hal b/audio/2.0/IStream.hal
new file mode 100644 (file)
index 0000000..dc43346
--- /dev/null
@@ -0,0 +1,230 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+import android.hardware.audio.common@2.0;
+import android.hardware.audio.effect@2.0::IEffect;
+
+interface IStream {
+    typedef android.hardware.audio@2.0::Result Result;
+
+    /*
+     * Return the frame size (number of bytes per sample).
+     *
+     * @return frameSize frame size in bytes.
+     */
+    getFrameSize() generates (uint64_t frameSize);
+
+    /*
+     * Return the frame count of the buffer. Calling this method is equivalent
+     * to getting AUDIO_PARAMETER_STREAM_FRAME_COUNT on the legacy HAL.
+     *
+     * @return count frame count.
+     */
+    getFrameCount() generates (uint64_t count);
+
+    /*
+     * Return the size of input/output buffer in bytes for this stream.
+     * It must be a multiple of the frame size.
+     *
+     * @return buffer buffer size in bytes.
+     */
+    getBufferSize() generates (uint64_t bufferSize);
+
+    /*
+     * Return the sampling rate in Hz.
+     *
+     * @return sampleRateHz sample rate in Hz.
+     */
+    getSampleRate() generates (uint32_t sampleRateHz);
+
+    /*
+     * Return supported sampling rates of the stream. Calling this method is
+     * equivalent to getting AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES on the
+     * legacy HAL.
+     *
+     * @return sampleRateHz supported sample rates.
+     */
+    getSupportedSampleRates() generates (vec<uint32_t> sampleRates);
+
+    /*
+     * Sets the sampling rate of the stream. Calling this method is equivalent
+     * to setting AUDIO_PARAMETER_STREAM_SAMPLING_RATE on the legacy HAL.
+     *
+     * @param sampleRateHz sample rate in Hz.
+     * @return retval operation completion status.
+     */
+    setSampleRate(uint32_t sampleRateHz) generates (Result retval);
+
+    /*
+     * Return the channel mask of the stream.
+     *
+     * @return mask channel mask.
+     */
+    getChannelMask() generates (AudioChannelMask mask);
+
+    /*
+     * Return supported channel masks of the stream. Calling this method is
+     * equivalent to getting AUDIO_PARAMETER_STREAM_SUP_CHANNELS on the legacy
+     * HAL.
+     *
+     * @return masks supported audio masks.
+     */
+    getSupportedChannelMasks() generates (vec<AudioChannelMask> masks);
+
+    /*
+     * Sets the channel mask of the stream. Calling this method is equivalent to
+     * setting AUDIO_PARAMETER_STREAM_CHANNELS on the legacy HAL.
+     *
+     * @param format audio format.
+     * @return retval operation completion status.
+     */
+    setChannelMask(AudioChannelMask mask) generates (Result retval);
+
+    /*
+     * Return the audio format of the stream.
+     *
+     * @return format audio format.
+     */
+    getFormat() generates (AudioFormat format);
+
+    /*
+     * Return supported audio formats of the stream. Calling this method is
+     * equivalent to getting AUDIO_PARAMETER_STREAM_SUP_FORMATS on the legacy
+     * HAL.
+     *
+     * @return formats supported audio formats.
+     */
+    getSupportedFormats() generates (vec<AudioFormat> formats);
+
+    /*
+     * Sets the audio format of the stream. Calling this method is equivalent to
+     * setting AUDIO_PARAMETER_STREAM_FORMAT on the legacy HAL.
+     *
+     * @param format audio format.
+     * @return retval operation completion status.
+     */
+    setFormat(AudioFormat format) generates (Result retval);
+
+    /*
+     * Convenience method for retrieving several stream parameters in
+     * one transaction.
+     *
+     * @return sampleRateHz sample rate in Hz.
+     * @return mask channel mask.
+     * @return format audio format.
+     */
+    getAudioProperties() generates (
+            uint32_t sampleRateHz, AudioChannelMask mask, AudioFormat format);
+
+    /*
+     * Applies audio effect to the stream.
+     *
+     * @param effectId effect ID (obtained from IEffectsFactory.createEffect) of
+     *                 the effect to apply.
+     * @return retval operation completion status.
+     */
+    addEffect(uint64_t effectId) generates (Result retval);
+
+    /*
+     * Stops application of the effect to the stream.
+     *
+     * @param effectId effect ID (obtained from IEffectsFactory.createEffect) of
+     *                 the effect to remove.
+     * @return retval operation completion status.
+     */
+    removeEffect(uint64_t effectId) generates (Result retval);
+
+    /*
+     * Put the audio hardware input/output into standby mode.
+     * Driver must exit from standby mode at the next I/O operation.
+     *
+     * @return retval operation completion status.
+     */
+    standby() generates (Result retval);
+
+    /*
+     * Return the set of device(s) which this stream is connected to.
+     *
+     * @return device set of device(s) which this stream is connected to.
+     */
+    getDevice() generates (AudioDevice device);
+
+    /*
+     * Connects the stream to the device.
+     *
+     * This method must only be used for HALs that do not support
+     * 'IDevice.createAudioPatch' method. Calling this method is
+     * equivalent to setting AUDIO_PARAMETER_STREAM_ROUTING in the legacy HAL
+     * interface.
+     *
+     * @param address device to connect the stream to.
+     * @return retval operation completion status.
+     */
+    setDevice(DeviceAddress address) generates (Result retval);
+
+    /*
+     * Notifies the stream about device connection state. Calling this method is
+     * equivalent to setting AUDIO_PARAMETER_DEVICE_[DIS]CONNECT on the legacy
+     * HAL.
+     *
+     * @param address audio device specification.
+     * @param connected whether the device is connected.
+     * @return retval operation completion status.
+     */
+    setConnectedState(DeviceAddress address, bool connected)
+            generates (Result retval);
+
+    /*
+     * Sets the HW synchronization source. Calling this method is equivalent to
+     * setting AUDIO_PARAMETER_STREAM_HW_AV_SYNC on the legacy HAL.
+     *
+     * @param hwAvSync HW synchronization source
+     * @return retval operation completion status.
+     */
+    setHwAvSync(AudioHwSync hwAvSync) generates (Result retval);
+
+    /*
+     * Generic method for retrieving vendor-specific parameter values.
+     * The framework does not interpret the parameters, they are passed
+     * in an opaque manner between a vendor application and HAL.
+     *
+     * @param keys parameter keys.
+     * @return retval operation completion status.
+     * @return parameters parameter key value pairs.
+     */
+    getParameters(vec<string> keys)
+            generates (Result retval, vec<ParameterValue> parameters);
+
+    /*
+     * Generic method for setting vendor-specific parameter values.
+     * The framework does not interpret the parameters, they are passed
+     * in an opaque manner between a vendor application and HAL.
+     *
+     * @param parameters parameter key value pairs.
+     * @return retval operation completion status.
+     */
+    setParameters(vec<ParameterValue> parameters) generates (Result retval);
+
+    /*
+     * Dumps information about the stream into the provided file descriptor.
+     * This is used for the dumpsys facility.
+     *
+     * @param fd dump file descriptor.
+     */
+    debugDump(handle fd);
+};
diff --git a/audio/2.0/IStreamIn.hal b/audio/2.0/IStreamIn.hal
new file mode 100644 (file)
index 0000000..6cf7425
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+import android.hardware.audio.common@2.0;
+import IStream;
+
+interface IStreamIn extends IStream {
+    typedef android.hardware.audio@2.0::Result Result;
+
+    /*
+     * Returns the source descriptor of the input stream. Calling this method is
+     * equivalent to getting AUDIO_PARAMETER_STREAM_INPUT_SOURCE on the legacy
+     * HAL.
+     *
+     * @return retval operation completion status.
+     * @return source audio source.
+     */
+    getAudioSource() generates (Result retval, AudioSource source);
+
+    /*
+     * Set the input gain for the audio driver.
+     *
+     * @param gain 1.0f is unity, 0.0f is zero.
+     * @result retval operation completion status.
+     */
+    setGain(float gain) generates (Result retval);
+
+    /*
+     * Read audio buffer in from driver. If at least one frame was read prior to
+     * the error, 'read' must return that byte count and then return an error
+     * in the subsequent call.
+     *
+     * @param size maximum amount of bytes to read.
+     * @return retval operation completion status.
+     * @return data audio data.
+     */
+    // TODO(mnaganov): Replace with FMQ version.
+    read(uint64_t size) generates (Result retval, vec<uint8_t> data);
+
+    /*
+     * Return the amount of input frames lost in the audio driver since the last
+     * call of this function.
+     *
+     * Audio driver is expected to reset the value to 0 and restart counting
+     * upon returning the current value by this function call. Such loss
+     * typically occurs when the user space process is blocked longer than the
+     * capacity of audio driver buffers.
+     *
+     * @return framesLost the number of input audio frames lost.
+     */
+    getInputFramesLost() generates (uint32_t framesLost);
+
+    /**
+     * Return a recent count of the number of audio frames received and the
+     * clock time associated with that frame count.
+     *
+     * @return retval INVALID_STATE if the device is not ready/available,
+     *                NOT_SUPPORTED if the command is not supported,
+     *                OK otherwise.
+     * @return frames the total frame count received. This must be as early in
+     *                the capture pipeline as possible. In general, frames
+     *                must be non-negative and must not go "backwards".
+     * @return time is the clock monotonic time when frames was measured. In
+     *              general, time must be a positive quantity and must not
+     *              go "backwards".
+     */
+    getCapturePosition()
+            generates (Result retval, uint64_t frames, uint64_t time);
+};
diff --git a/audio/2.0/IStreamOut.hal b/audio/2.0/IStreamOut.hal
new file mode 100644 (file)
index 0000000..55a852d
--- /dev/null
@@ -0,0 +1,191 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+import android.hardware.audio.common@2.0;
+import IStream;
+import IStreamOutCallback;
+
+interface IStreamOut extends IStream {
+    typedef android.hardware.audio@2.0::Result Result;
+
+    /*
+     * Return the audio hardware driver estimated latency in milliseconds.
+     *
+     * @return latencyMs latency in milliseconds.
+     */
+    getLatency() generates (uint32_t latencyMs);
+
+    /*
+     * This method is used in situations where audio mixing is done in the
+     * hardware. This method serves as a direct interface with hardware,
+     * allowing to directly set the volume as apposed to via the framework.
+     * This method might produce multiple PCM outputs or hardware accelerated
+     * codecs, such as MP3 or AAC.
+     *
+     * @param left left channel attenuation, 1.0f is unity, 0.0f is zero.
+     * @param right right channel attenuation, 1.0f is unity, 0.0f is zero.
+     * @return retval operation completion status.
+     */
+    setVolume(float left, float right) generates (Result retval);
+
+    /*
+     * Write audio buffer to driver. On success, sets 'retval' to 'OK', and
+     * returns number of bytes written. If at least one frame was written
+     * successfully prior to the error, it is suggested that the driver return
+     * that successful (short) byte count and then return an error in the
+     * subsequent call.
+     *
+     * If 'setCallback' has previously been called to enable non-blocking mode
+     * then 'write' is not allowed to block. It must write only the number of
+     * bytes that currently fit in the driver/hardware buffer and then return
+     * this byte count. If this is less than the requested write size the
+     * callback function must be called when more space is available in the
+     * driver/hardware buffer.
+     *
+     * @param data audio data.
+     * @return retval operation completion status.
+     * @return written number of bytes written.
+     */
+    // TODO(mnaganov): Replace with FMQ version.
+    write(vec<uint8_t> data) generates (Result retval, uint64_t written);
+
+    /*
+     * Return the number of audio frames written by the audio DSP to DAC since
+     * the output has exited standby.
+     *
+     * @return retval operation completion status.
+     * @return dspFrames number of audio frames written.
+     */
+    getRenderPosition() generates (Result retval, uint32_t dspFrames);
+
+    /*
+     * Get the local time at which the next write to the audio driver will be
+     * presented. The units are microseconds, where the epoch is decided by the
+     * local audio HAL.
+     *
+     * @return retval operation completion status.
+     * @return timestampUs time of the next write.
+     */
+    getNextWriteTimestamp() generates (Result retval, int64_t timestampUs);
+
+    /*
+     * Set the callback interface for notifying completion of non-blocking
+     * write and drain.
+     *
+     * Calling this function implies that all future 'write' and 'drain'
+     * must be non-blocking and use the callback to signal completion.
+     *
+     * @return retval operation completion status.
+     */
+    setCallback(IStreamOutCallback callback) generates (Result retval);
+
+    /*
+     * Returns whether HAL supports pausing and resuming of streams.
+     *
+     * @return supportsPause true if pausing is supported.
+     * @return supportsResume true if resume is supported.
+     */
+    supportsPauseAndResume()
+            generates (bool supportsPause, bool supportsResume);
+
+    /**
+     * Notifies to the audio driver to stop playback however the queued buffers
+     * are retained by the hardware. Useful for implementing pause/resume. Empty
+     * implementation if not supported however must be implemented for hardware
+     * with non-trivial latency. In the pause state, some audio hardware may
+     * still be using power. Client code may consider calling 'suspend' after a
+     * timeout to prevent that excess power usage.
+     *
+     * Implementation of this function is mandatory for offloaded playback.
+     *
+     * @return retval operation completion status.
+     */
+    pause() generates (Result retval);
+
+    /*
+     * Notifies to the audio driver to resume playback following a pause.
+     * Returns error INVALID_STATE if called without matching pause.
+     *
+     * Implementation of this function is mandatory for offloaded playback.
+     *
+     * @return retval operation completion status.
+     */
+    resume() generates (Result retval);
+
+    /*
+     * Returns whether HAL supports draining of streams.
+     *
+     * @return supports true if draining is supported.
+     */
+    supportsDrain() generates (bool supports);
+
+    /**
+     * Requests notification when data buffered by the driver/hardware has been
+     * played. If 'setCallback' has previously been called to enable
+     * non-blocking mode, then 'drain' must not block, instead it must return
+     * quickly and completion of the drain is notified through the callback. If
+     * 'setCallback' has not been called, then 'drain' must block until
+     * completion.
+     *
+     * If 'type' is 'ALL', the drain completes when all previously written data
+     * has been played.
+     *
+     * If 'type' is 'EARLY_NOTIFY', the drain completes shortly before all data
+     * for the current track has played to allow time for the framework to
+     * perform a gapless track switch.
+     *
+     * Drain must return immediately on 'stop' and 'flush' calls.
+     *
+     * Implementation of this function is mandatory for offloaded playback.
+     *
+     * @param type type of drain.
+     * @return retval operation completion status.
+     */
+    drain(AudioDrain type) generates (Result retval);
+
+    /*
+     * Notifies to the audio driver to flush the queued data. Stream must
+     * already be paused before calling 'flush'.
+     *
+     * Implementation of this function is mandatory for offloaded playback.
+     *
+     * @return retval operation completion status.
+     */
+    flush() generates (Result retval);
+
+    /*
+     * Return a recent count of the number of audio frames presented to an
+     * external observer. This excludes frames which have been written but are
+     * still in the pipeline. The count is not reset to zero when output enters
+     * standby. Also returns the value of CLOCK_MONOTONIC as of this
+     * presentation count. The returned count is expected to be 'recent', but
+     * does not need to be the most recent possible value. However, the
+     * associated time must correspond to whatever count is returned.
+     *
+     * Example: assume that N+M frames have been presented, where M is a 'small'
+     * number. Then it is permissible to return N instead of N+M, and the
+     * timestamp must correspond to N rather than N+M. The terms 'recent' and
+     * 'small' are not defined. They reflect the quality of the implementation.
+     *
+     * @return retval operation completion status.
+     * @return frames count of presented audio frames.
+     * @return timeStamp associated clock time.
+     */
+    getPresentationPosition()
+            generates (Result retval, uint64_t frames, TimeSpec timeStamp);
+};
diff --git a/audio/2.0/IStreamOutCallback.hal b/audio/2.0/IStreamOutCallback.hal
new file mode 100644 (file)
index 0000000..267c46d
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+/*
+ * Asynchronous write callback interface.
+ */
+interface IStreamOutCallback {
+    /*
+     * Non blocking write completed.
+     */
+    onWriteReady();
+
+    /*
+     * Drain completed.
+     */
+    onDrainReady();
+
+    /*
+     * Stream hit an error.
+     */
+    onError();
+};
diff --git a/audio/2.0/default/Android.mk b/audio/2.0/default/Android.mk
new file mode 100644 (file)
index 0000000..a5c0383
--- /dev/null
@@ -0,0 +1,74 @@
+#
+# 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.
+
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.audio@2.0-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    Conversions.cpp \
+    Device.cpp \
+    DevicesFactory.cpp \
+    ParametersUtil.cpp \
+    PrimaryDevice.cpp \
+    Stream.cpp \
+    StreamIn.cpp \
+    StreamOut.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    libhidl \
+    libhwbinder \
+    libutils \
+    libhardware \
+    liblog \
+    android.hardware.audio@2.0 \
+    android.hardware.audio.common@2.0 \
+    android.hardware.audio.common@2.0-util \
+
+LOCAL_WHOLE_STATIC_LIBRARIES := libmedia_helper
+
+include $(BUILD_SHARED_LIBRARY)
+
+#
+# Service
+#
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.audio@2.0-service
+LOCAL_INIT_RC := android.hardware.audio@2.0-service.rc
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    service.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+    libhidl \
+    liblog \
+    libhwbinder \
+    libutils \
+    libhardware \
+    android.hardware.audio@2.0 \
+    android.hardware.audio.common@2.0 \
+    android.hardware.audio.effect@2.0 \
+    android.hardware.soundtrigger@2.0 \
+
+ifeq ($(strip $(AUDIOSERVER_MULTILIB)),)
+LOCAL_MULTILIB := 32
+else
+LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
+endif
+
+include $(BUILD_EXECUTABLE)
diff --git a/audio/2.0/default/Conversions.cpp b/audio/2.0/default/Conversions.cpp
new file mode 100644 (file)
index 0000000..1ba16e1
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+#include <stdio.h>
+
+#include "Conversions.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+std::string deviceAddressToHal(const DeviceAddress& address) {
+    // HAL assumes that the address is NUL-terminated.
+    char halAddress[AUDIO_DEVICE_MAX_ADDRESS_LEN];
+    memset(halAddress, 0, sizeof(halAddress));
+    uint32_t halDevice = static_cast<uint32_t>(address.device);
+    if ((halDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0
+            || (halDevice & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) != 0) {
+        snprintf(halAddress, sizeof(halAddress),
+                "%02X:%02X:%02X:%02X:%02X:%02X",
+                address.address.mac[0], address.address.mac[1], address.address.mac[2],
+                address.address.mac[3], address.address.mac[4], address.address.mac[5]);
+    } else if ((halDevice & AUDIO_DEVICE_OUT_IP) != 0 || (halDevice & AUDIO_DEVICE_IN_IP) != 0) {
+        snprintf(halAddress, sizeof(halAddress),
+                "%d.%d.%d.%d",
+                address.address.ipv4[0], address.address.ipv4[1],
+                address.address.ipv4[2], address.address.ipv4[3]);
+    } else if ((halDevice & AUDIO_DEVICE_OUT_ALL_USB) != 0
+            || (halDevice & AUDIO_DEVICE_IN_ALL_USB) != 0) {
+        snprintf(halAddress, sizeof(halAddress),
+                "card=%d;device=%d",
+                address.address.alsa.card, address.address.alsa.device);
+    } else if ((halDevice & AUDIO_DEVICE_OUT_BUS) != 0 || (halDevice & AUDIO_DEVICE_IN_BUS) != 0) {
+        snprintf(halAddress, sizeof(halAddress),
+                "%s", address.busAddress.c_str());
+    } else if ((halDevice & AUDIO_DEVICE_OUT_REMOTE_SUBMIX) != 0
+            || (halDevice & AUDIO_DEVICE_IN_REMOTE_SUBMIX) != 0) {
+        snprintf(halAddress, sizeof(halAddress),
+                "%s", address.rSubmixAddress.c_str());
+    }
+    return halAddress;
+}
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/Conversions.h b/audio/2.0/default/Conversions.h
new file mode 100644 (file)
index 0000000..ebda5c5
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_audio_V2_0_Conversions_H_
+#define android_hardware_audio_V2_0_Conversions_H_
+
+#include <string>
+
+#include <android/hardware/audio/2.0/types.h>
+#include <system/audio.h>
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::V2_0::DeviceAddress;
+
+std::string deviceAddressToHal(const DeviceAddress& address);
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // android_hardware_audio_V2_0_Conversions_H_
diff --git a/audio/2.0/default/Device.cpp b/audio/2.0/default/Device.cpp
new file mode 100644 (file)
index 0000000..05824c7
--- /dev/null
@@ -0,0 +1,534 @@
+ /*
+ * 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.
+ */
+
+#define LOG_TAG "DeviceHAL"
+
+#include <algorithm>
+#include <memory.h>
+#include <string.h>
+
+#include <utils/Log.h>
+
+#include "Conversions.h"
+#include "Device.h"
+#include "StreamIn.h"
+#include "StreamOut.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+Device::Device(audio_hw_device_t* device)
+        : mDevice(device) {
+}
+
+Device::~Device() {
+    int status = audio_hw_device_close(mDevice);
+    ALOGW_IF(status, "Error closing audio hw device %p: %s", mDevice, strerror(-status));
+    mDevice = nullptr;
+}
+
+// static
+void Device::audioConfigToHal(const AudioConfig& config, audio_config_t* halConfig) {
+    memset(halConfig, 0, sizeof(audio_config_t));
+    halConfig->sample_rate = config.sampleRateHz;
+    halConfig->channel_mask = static_cast<audio_channel_mask_t>(config.channelMask);
+    halConfig->format = static_cast<audio_format_t>(config.format);
+    audioOffloadInfoToHal(config.offloadInfo, &halConfig->offload_info);
+    halConfig->frame_count = config.frameCount;
+}
+
+// static
+void Device::audioGainConfigFromHal(
+        const struct audio_gain_config& halConfig, AudioGainConfig* config) {
+    config->index = halConfig.index;
+    config->mode = AudioGainMode(halConfig.mode);
+    config->channelMask = AudioChannelMask(halConfig.channel_mask);
+    for (size_t i = 0; i < sizeof(audio_channel_mask_t) * 8; ++i) {
+        config->values[i] = halConfig.values[i];
+    }
+    config->rampDurationMs = halConfig.ramp_duration_ms;
+}
+
+// static
+void Device::audioGainConfigToHal(
+        const AudioGainConfig& config, struct audio_gain_config* halConfig) {
+    halConfig->index = config.index;
+    halConfig->mode = static_cast<audio_gain_mode_t>(config.mode);
+    halConfig->channel_mask = static_cast<audio_channel_mask_t>(config.channelMask);
+    memset(halConfig->values, 0, sizeof(halConfig->values));
+    for (size_t i = 0; i < sizeof(audio_channel_mask_t) * 8; ++i) {
+        halConfig->values[i] = config.values[i];
+    }
+    halConfig->ramp_duration_ms = config.rampDurationMs;
+}
+
+// static
+void Device::audioGainFromHal(const struct audio_gain& halGain, AudioGain* gain) {
+    gain->mode = AudioGainMode(halGain.mode);
+    gain->channelMask = AudioChannelMask(halGain.channel_mask);
+    gain->minValue = halGain.min_value;
+    gain->maxValue = halGain.max_value;
+    gain->defaultValue = halGain.default_value;
+    gain->stepValue = halGain.step_value;
+    gain->minRampMs = halGain.min_ramp_ms;
+    gain->maxRampMs = halGain.max_ramp_ms;
+}
+
+// static
+void Device::audioGainToHal(const AudioGain& gain, struct audio_gain* halGain) {
+    halGain->mode = static_cast<audio_gain_mode_t>(gain.mode);
+    halGain->channel_mask = static_cast<audio_channel_mask_t>(gain.channelMask);
+    halGain->min_value = gain.minValue;
+    halGain->max_value = gain.maxValue;
+    halGain->default_value = gain.defaultValue;
+    halGain->step_value = gain.stepValue;
+    halGain->min_ramp_ms = gain.minRampMs;
+    halGain->max_ramp_ms = gain.maxRampMs;
+}
+
+// static
+void Device::audioOffloadInfoToHal(
+        const AudioOffloadInfo& offload, audio_offload_info_t* halOffload) {
+    *halOffload = AUDIO_INFO_INITIALIZER;
+    halOffload->sample_rate = offload.sampleRateHz;
+    halOffload->channel_mask = static_cast<audio_channel_mask_t>(offload.channelMask);
+    halOffload->stream_type = static_cast<audio_stream_type_t>(offload.streamType);
+    halOffload->bit_rate = offload.bitRatePerSecond;
+    halOffload->duration_us = offload.durationMicroseconds;
+    halOffload->has_video = offload.hasVideo;
+    halOffload->is_streaming = offload.isStreaming;
+}
+
+// static
+void Device::audioPortConfigFromHal(
+        const struct audio_port_config& halConfig, AudioPortConfig* config) {
+    config->id = halConfig.id;
+    config->role = AudioPortRole(halConfig.role);
+    config->type = AudioPortType(halConfig.type);
+    config->configMask = AudioPortConfigMask(halConfig.config_mask);
+    config->sampleRateHz = halConfig.sample_rate;
+    config->channelMask = AudioChannelMask(halConfig.channel_mask);
+    config->format = AudioFormat(halConfig.format);
+    audioGainConfigFromHal(halConfig.gain, &config->gain);
+    switch (halConfig.type) {
+        case AUDIO_PORT_TYPE_NONE: break;
+        case AUDIO_PORT_TYPE_DEVICE: {
+            config->ext.device.hwModule = halConfig.ext.device.hw_module;
+            config->ext.device.type = AudioDevice(halConfig.ext.device.type);
+            memcpy(config->ext.device.address.data(),
+                    halConfig.ext.device.address,
+                    AUDIO_DEVICE_MAX_ADDRESS_LEN);
+            break;
+        }
+        case AUDIO_PORT_TYPE_MIX: {
+            config->ext.mix.hwModule = halConfig.ext.mix.hw_module;
+            config->ext.mix.ioHandle = halConfig.ext.mix.handle;
+            if (halConfig.role == AUDIO_PORT_ROLE_SOURCE) {
+                config->ext.mix.useCase.source = AudioSource(halConfig.ext.mix.usecase.source);
+            } else if (halConfig.role == AUDIO_PORT_ROLE_SINK) {
+                config->ext.mix.useCase.stream = AudioStreamType(halConfig.ext.mix.usecase.stream);
+            }
+            break;
+        }
+        case AUDIO_PORT_TYPE_SESSION: {
+            config->ext.session.session = halConfig.ext.session.session;
+            break;
+        }
+    }
+}
+
+// static
+void Device::audioPortConfigToHal(
+        const AudioPortConfig& config, struct audio_port_config* halConfig) {
+    memset(halConfig, 0, sizeof(audio_port_config));
+    halConfig->id = config.id;
+    halConfig->role = static_cast<audio_port_role_t>(config.role);
+    halConfig->type = static_cast<audio_port_type_t>(config.type);
+    halConfig->config_mask = static_cast<unsigned int>(config.configMask);
+    halConfig->sample_rate = config.sampleRateHz;
+    halConfig->channel_mask = static_cast<audio_channel_mask_t>(config.channelMask);
+    halConfig->format = static_cast<audio_format_t>(config.format);
+    audioGainConfigToHal(config.gain, &halConfig->gain);
+    switch (config.type) {
+        case AudioPortType::NONE: break;
+        case AudioPortType::DEVICE: {
+            halConfig->ext.device.hw_module = config.ext.device.hwModule;
+            halConfig->ext.device.type = static_cast<audio_devices_t>(config.ext.device.type);
+            memcpy(halConfig->ext.device.address,
+                    config.ext.device.address.data(),
+                    AUDIO_DEVICE_MAX_ADDRESS_LEN);
+            break;
+        }
+        case AudioPortType::MIX: {
+            halConfig->ext.mix.hw_module = config.ext.mix.hwModule;
+            halConfig->ext.mix.handle = config.ext.mix.ioHandle;
+            if (config.role == AudioPortRole::SOURCE) {
+                halConfig->ext.mix.usecase.source =
+                        static_cast<audio_source_t>(config.ext.mix.useCase.source);
+            } else if (config.role == AudioPortRole::SINK) {
+                halConfig->ext.mix.usecase.stream =
+                        static_cast<audio_stream_type_t>(config.ext.mix.useCase.stream);
+            }
+            break;
+        }
+        case AudioPortType::SESSION: {
+            halConfig->ext.session.session =
+                    static_cast<audio_session_t>(config.ext.session.session);
+            break;
+        }
+    }
+}
+
+// static
+std::unique_ptr<audio_port_config[]> Device::audioPortConfigsToHal(
+        const hidl_vec<AudioPortConfig>& configs) {
+    std::unique_ptr<audio_port_config[]> halConfigs(new audio_port_config[configs.size()]);
+    for (size_t i = 0; i < configs.size(); ++i) {
+        audioPortConfigToHal(configs[i], &halConfigs[i]);
+    }
+    return halConfigs;
+}
+
+// static
+void Device::audioPortFromHal(const struct audio_port& halPort, AudioPort* port) {
+    port->id = halPort.id;
+    port->role = AudioPortRole(halPort.role);
+    port->type = AudioPortType(halPort.type);
+    port->name.setToExternal(halPort.name, strlen(halPort.name));
+    port->sampleRates.resize(halPort.num_sample_rates);
+    for (size_t i = 0; i < halPort.num_sample_rates; ++i) {
+        port->sampleRates[i] = halPort.sample_rates[i];
+    }
+    port->channelMasks.resize(halPort.num_channel_masks);
+    for (size_t i = 0; i < halPort.num_channel_masks; ++i) {
+        port->channelMasks[i] = AudioChannelMask(halPort.channel_masks[i]);
+    }
+    port->formats.resize(halPort.num_formats);
+    for (size_t i = 0; i < halPort.num_formats; ++i) {
+        port->formats[i] = AudioFormat(halPort.formats[i]);
+    }
+    port->gains.resize(halPort.num_gains);
+    for (size_t i = 0; i < halPort.num_gains; ++i) {
+        audioGainFromHal(halPort.gains[i], &port->gains[i]);
+    }
+    audioPortConfigFromHal(halPort.active_config, &port->activeConfig);
+    switch (halPort.type) {
+        case AUDIO_PORT_TYPE_NONE: break;
+        case AUDIO_PORT_TYPE_DEVICE: {
+            port->ext.device.hwModule = halPort.ext.device.hw_module;
+            port->ext.device.type = AudioDevice(halPort.ext.device.type);
+            memcpy(port->ext.device.address.data(),
+                    halPort.ext.device.address,
+                    AUDIO_DEVICE_MAX_ADDRESS_LEN);
+            break;
+        }
+        case AUDIO_PORT_TYPE_MIX: {
+            port->ext.mix.hwModule = halPort.ext.mix.hw_module;
+            port->ext.mix.ioHandle = halPort.ext.mix.handle;
+            port->ext.mix.latencyClass = AudioMixLatencyClass(halPort.ext.mix.latency_class);
+            break;
+        }
+        case AUDIO_PORT_TYPE_SESSION: {
+            port->ext.session.session = halPort.ext.session.session;
+            break;
+        }
+    }
+}
+
+// static
+void Device::audioPortToHal(const AudioPort& port, struct audio_port* halPort) {
+    memset(halPort, 0, sizeof(audio_port));
+    halPort->id = port.id;
+    halPort->role = static_cast<audio_port_role_t>(port.role);
+    halPort->type = static_cast<audio_port_type_t>(port.type);
+    memcpy(halPort->name,
+            port.name.c_str(),
+            std::min(port.name.size(), static_cast<size_t>(AUDIO_PORT_MAX_NAME_LEN)));
+    halPort->num_sample_rates =
+            std::min(port.sampleRates.size(), static_cast<size_t>(AUDIO_PORT_MAX_SAMPLING_RATES));
+    for (size_t i = 0; i < halPort->num_sample_rates; ++i) {
+        halPort->sample_rates[i] = port.sampleRates[i];
+    }
+    halPort->num_channel_masks =
+            std::min(port.channelMasks.size(), static_cast<size_t>(AUDIO_PORT_MAX_CHANNEL_MASKS));
+    for (size_t i = 0; i < halPort->num_channel_masks; ++i) {
+        halPort->channel_masks[i] = static_cast<audio_channel_mask_t>(port.channelMasks[i]);
+    }
+    halPort->num_formats =
+            std::min(port.formats.size(), static_cast<size_t>(AUDIO_PORT_MAX_FORMATS));
+    for (size_t i = 0; i < halPort->num_formats; ++i) {
+        halPort->formats[i] = static_cast<audio_format_t>(port.formats[i]);
+    }
+    halPort->num_gains = std::min(port.gains.size(), static_cast<size_t>(AUDIO_PORT_MAX_GAINS));
+    for (size_t i = 0; i < halPort->num_gains; ++i) {
+        audioGainToHal(port.gains[i], &halPort->gains[i]);
+    }
+    audioPortConfigToHal(port.activeConfig, &halPort->active_config);
+    switch (port.type) {
+        case AudioPortType::NONE: break;
+        case AudioPortType::DEVICE: {
+            halPort->ext.device.hw_module = port.ext.device.hwModule;
+            halPort->ext.device.type = static_cast<audio_devices_t>(port.ext.device.type);
+            memcpy(halPort->ext.device.address,
+                    port.ext.device.address.data(),
+                    AUDIO_DEVICE_MAX_ADDRESS_LEN);
+            break;
+        }
+        case AudioPortType::MIX: {
+            halPort->ext.mix.hw_module = port.ext.mix.hwModule;
+            halPort->ext.mix.handle = port.ext.mix.ioHandle;
+            halPort->ext.mix.latency_class =
+                    static_cast<audio_mix_latency_class_t>(port.ext.mix.latencyClass);
+            break;
+        }
+        case AudioPortType::SESSION: {
+            halPort->ext.session.session = static_cast<audio_session_t>(port.ext.session.session);
+            break;
+        }
+    }
+}
+
+Result Device::analyzeStatus(const char* funcName, int status) {
+    if (status != 0) {
+        ALOGW("Device %p %s: %s", mDevice, funcName, strerror(-status));
+    }
+    switch (status) {
+        case 0: return Result::OK;
+        case -EINVAL: return Result::INVALID_ARGUMENTS;
+        case -ENODATA: return Result::INVALID_STATE;
+        case -ENODEV: return Result::NOT_INITIALIZED;
+        case -ENOSYS: return Result::NOT_SUPPORTED;
+        default: return Result::INVALID_STATE;
+    }
+}
+
+char* Device::halGetParameters(const char* keys) {
+    return mDevice->get_parameters(mDevice, keys);
+}
+
+int Device::halSetParameters(const char* keysAndValues) {
+    return mDevice->set_parameters(mDevice, keysAndValues);
+}
+
+// Methods from ::android::hardware::audio::V2_0::IDevice follow.
+Return<Result> Device::initCheck()  {
+    return analyzeStatus("init_check", mDevice->init_check(mDevice));
+}
+
+Return<Result> Device::setMasterVolume(float volume)  {
+    Result retval(Result::NOT_SUPPORTED);
+    if (mDevice->set_master_volume != NULL) {
+        retval = analyzeStatus("set_master_volume", mDevice->set_master_volume(mDevice, volume));
+    }
+    return retval;
+}
+
+Return<void> Device::getMasterVolume(getMasterVolume_cb _hidl_cb)  {
+    Result retval(Result::NOT_SUPPORTED);
+    float volume = 0;
+    if (mDevice->get_master_volume != NULL) {
+        retval = analyzeStatus("get_master_volume", mDevice->get_master_volume(mDevice, &volume));
+    }
+    _hidl_cb(retval, volume);
+    return Void();
+}
+
+Return<Result> Device::setMicMute(bool mute)  {
+    return analyzeStatus("set_mic_mute", mDevice->set_mic_mute(mDevice, mute));
+}
+
+Return<void> Device::getMicMute(getMicMute_cb _hidl_cb)  {
+    bool mute = false;
+    Result retval = analyzeStatus("get_mic_mute", mDevice->get_mic_mute(mDevice, &mute));
+    _hidl_cb(retval, mute);
+    return Void();
+}
+
+Return<Result> Device::setMasterMute(bool mute)  {
+    Result retval(Result::NOT_SUPPORTED);
+    if (mDevice->set_master_mute != NULL) {
+        retval = analyzeStatus("set_master_mute", mDevice->set_master_mute(mDevice, mute));
+    }
+    return retval;
+}
+
+Return<void> Device::getMasterMute(getMasterMute_cb _hidl_cb)  {
+    Result retval(Result::NOT_SUPPORTED);
+    bool mute = false;
+    if (mDevice->get_master_mute != NULL) {
+        retval = analyzeStatus("get_master_mute", mDevice->get_master_mute(mDevice, &mute));
+    }
+    _hidl_cb(retval, mute);
+    return Void();
+}
+
+Return<void> Device::getInputBufferSize(
+        const AudioConfig& config, getInputBufferSize_cb _hidl_cb)  {
+    audio_config_t halConfig;
+    audioConfigToHal(config, &halConfig);
+    size_t halBufferSize = mDevice->get_input_buffer_size(mDevice, &halConfig);
+    Result retval(Result::INVALID_ARGUMENTS);
+    uint64_t bufferSize = 0;
+    if (halBufferSize != 0) {
+        retval = Result::OK;
+        bufferSize = halBufferSize;
+    }
+    _hidl_cb(retval, bufferSize);
+    return Void();
+}
+
+Return<void> Device::openOutputStream(
+        int32_t ioHandle,
+        const DeviceAddress& device,
+        const AudioConfig& config,
+        AudioOutputFlag flags,
+        openOutputStream_cb _hidl_cb)  {
+    audio_config_t halConfig;
+    audioConfigToHal(config, &halConfig);
+    audio_stream_out_t *halStream;
+    int status = mDevice->open_output_stream(
+            mDevice,
+            ioHandle,
+            static_cast<audio_devices_t>(device.device),
+            static_cast<audio_output_flags_t>(flags),
+            &halConfig,
+            &halStream,
+            deviceAddressToHal(device).c_str());
+    sp<IStreamOut> streamOut;
+    if (status == OK) {
+        streamOut = new StreamOut(mDevice, halStream);
+    }
+    _hidl_cb(analyzeStatus("open_output_stream", status), streamOut);
+    return Void();
+}
+
+Return<void> Device::openInputStream(
+        int32_t ioHandle,
+        const DeviceAddress& device,
+        const AudioConfig& config,
+        AudioInputFlag flags,
+        AudioSource source,
+        openInputStream_cb _hidl_cb)  {
+    audio_config_t halConfig;
+    audioConfigToHal(config, &halConfig);
+    audio_stream_in_t *halStream;
+    int status = mDevice->open_input_stream(
+            mDevice,
+            ioHandle,
+            static_cast<audio_devices_t>(device.device),
+            &halConfig,
+            &halStream,
+            static_cast<audio_input_flags_t>(flags),
+            deviceAddressToHal(device).c_str(),
+            static_cast<audio_source_t>(source));
+    sp<IStreamIn> streamIn;
+    if (status == OK) {
+        streamIn = new StreamIn(mDevice, halStream);
+    }
+    _hidl_cb(analyzeStatus("open_input_stream", status), streamIn);
+    return Void();
+}
+
+Return<void> Device::createAudioPatch(
+        const hidl_vec<AudioPortConfig>& sources,
+        const hidl_vec<AudioPortConfig>& sinks,
+        createAudioPatch_cb _hidl_cb)  {
+    Result retval(Result::NOT_SUPPORTED);
+    AudioPatchHandle patch = 0;
+    if (version() >= AUDIO_DEVICE_API_VERSION_3_0) {
+        std::unique_ptr<audio_port_config[]> halSources(audioPortConfigsToHal(sources));
+        std::unique_ptr<audio_port_config[]> halSinks(audioPortConfigsToHal(sinks));
+        audio_patch_handle_t halPatch;
+        retval = analyzeStatus(
+                "create_audio_patch",
+                mDevice->create_audio_patch(
+                        mDevice,
+                        sources.size(), &halSources[0],
+                        sinks.size(), &halSinks[0],
+                        &halPatch));
+        if (retval == Result::OK) {
+            patch = static_cast<AudioPatchHandle>(halPatch);
+        }
+    }
+    _hidl_cb(retval, patch);
+    return Void();
+}
+
+Return<Result> Device::releaseAudioPatch(int32_t patch)  {
+    if (version() >= AUDIO_DEVICE_API_VERSION_3_0) {
+        return analyzeStatus(
+                "release_audio_patch",
+                mDevice->release_audio_patch(mDevice, static_cast<audio_patch_handle_t>(patch)));
+    }
+    return Result::NOT_SUPPORTED;
+}
+
+Return<void> Device::getAudioPort(const AudioPort& port, getAudioPort_cb _hidl_cb)  {
+    audio_port halPort;
+    audioPortToHal(port, &halPort);
+    Result retval = analyzeStatus("get_audio_port", mDevice->get_audio_port(mDevice, &halPort));
+    AudioPort resultPort = port;
+    if (retval == Result::OK) {
+        audioPortFromHal(halPort, &resultPort);
+    }
+    _hidl_cb(retval, resultPort);
+    return Void();
+}
+
+Return<Result> Device::setAudioPortConfig(const AudioPortConfig& config)  {
+    if (version() >= AUDIO_DEVICE_API_VERSION_3_0) {
+        struct audio_port_config halPortConfig;
+        audioPortConfigToHal(config, &halPortConfig);
+        return analyzeStatus(
+                "set_audio_port_config", mDevice->set_audio_port_config(mDevice, &halPortConfig));
+    }
+    return Result::NOT_SUPPORTED;
+}
+
+Return<AudioHwSync> Device::getHwAvSync()  {
+    int halHwAvSync;
+    Result retval = getParam(AudioParameter::keyHwAvSync, &halHwAvSync);
+    return retval == Result::OK ? halHwAvSync : AUDIO_HW_SYNC_INVALID;
+}
+
+Return<Result> Device::setScreenState(bool turnedOn)  {
+    return setParam(AudioParameter::keyScreenState, turnedOn);
+}
+
+Return<void> Device::getParameters(const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  {
+    getParametersImpl(keys, _hidl_cb);
+    return Void();
+}
+
+Return<Result> Device::setParameters(const hidl_vec<ParameterValue>& parameters)  {
+    return setParametersImpl(parameters);
+}
+
+Return<void> Device::debugDump(const native_handle_t* fd)  {
+    if (fd->numFds == 1) {
+        analyzeStatus("dump", mDevice->dump(mDevice, fd->data[0]));
+    }
+    return Void();
+}
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/Device.h b/audio/2.0/default/Device.h
new file mode 100644 (file)
index 0000000..d7b3128
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_V2_0_Device_H_
+#define HIDL_GENERATED_android_hardware_audio_V2_0_Device_H_
+
+#include <memory>
+
+#include <media/AudioParameter.h>
+#include <hardware/audio.h>
+
+#include <android/hardware/audio/2.0/IDevice.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "ParametersUtil.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioConfig;
+using ::android::hardware::audio::common::V2_0::AudioGain;
+using ::android::hardware::audio::common::V2_0::AudioGainConfig;
+using ::android::hardware::audio::common::V2_0::AudioGainMode;
+using ::android::hardware::audio::common::V2_0::AudioHwSync;
+using ::android::hardware::audio::common::V2_0::AudioInputFlag;
+using ::android::hardware::audio::common::V2_0::AudioMixLatencyClass;
+using ::android::hardware::audio::common::V2_0::AudioOffloadInfo;
+using ::android::hardware::audio::common::V2_0::AudioOutputFlag;
+using ::android::hardware::audio::common::V2_0::AudioPatchHandle;
+using ::android::hardware::audio::common::V2_0::AudioPort;
+using ::android::hardware::audio::common::V2_0::AudioPortConfig;
+using ::android::hardware::audio::common::V2_0::AudioPortConfigMask;
+using ::android::hardware::audio::common::V2_0::AudioPortRole;
+using ::android::hardware::audio::common::V2_0::AudioPortType;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::common::V2_0::AudioStreamType;
+using ::android::hardware::audio::V2_0::DeviceAddress;
+using ::android::hardware::audio::V2_0::IDevice;
+using ::android::hardware::audio::V2_0::IStreamIn;
+using ::android::hardware::audio::V2_0::IStreamOut;
+using ::android::hardware::audio::V2_0::ParameterValue;
+using ::android::hardware::audio::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Device : public IDevice, public ParametersUtil {
+    explicit Device(audio_hw_device_t* device);
+
+    // Methods from ::android::hardware::audio::V2_0::IDevice follow.
+    Return<Result> initCheck()  override;
+    Return<Result> setMasterVolume(float volume)  override;
+    Return<void> getMasterVolume(getMasterVolume_cb _hidl_cb)  override;
+    Return<Result> setMicMute(bool mute)  override;
+    Return<void> getMicMute(getMicMute_cb _hidl_cb)  override;
+    Return<Result> setMasterMute(bool mute)  override;
+    Return<void> getMasterMute(getMasterMute_cb _hidl_cb)  override;
+    Return<void> getInputBufferSize(
+            const AudioConfig& config, getInputBufferSize_cb _hidl_cb)  override;
+    Return<void> openOutputStream(
+            int32_t ioHandle,
+            const DeviceAddress& device,
+            const AudioConfig& config,
+            AudioOutputFlag flags,
+            openOutputStream_cb _hidl_cb)  override;
+    Return<void> openInputStream(
+            int32_t ioHandle,
+            const DeviceAddress& device,
+            const AudioConfig& config,
+            AudioInputFlag flags,
+            AudioSource source,
+            openInputStream_cb _hidl_cb)  override;
+    Return<void> createAudioPatch(
+            const hidl_vec<AudioPortConfig>& sources,
+            const hidl_vec<AudioPortConfig>& sinks,
+            createAudioPatch_cb _hidl_cb)  override;
+    Return<Result> releaseAudioPatch(int32_t patch)  override;
+    Return<void> getAudioPort(const AudioPort& port, getAudioPort_cb _hidl_cb)  override;
+    Return<Result> setAudioPortConfig(const AudioPortConfig& config)  override;
+    Return<AudioHwSync> getHwAvSync()  override;
+    Return<Result> setScreenState(bool turnedOn)  override;
+    Return<void> getParameters(
+            const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  override;
+    Return<Result> setParameters(const hidl_vec<ParameterValue>& parameters)  override;
+    Return<void> debugDump(const native_handle_t* fd)  override;
+
+    // Utility methods for extending interfaces.
+    Result analyzeStatus(const char* funcName, int status);
+    audio_hw_device_t* device() const { return mDevice; }
+
+  private:
+    audio_hw_device_t *mDevice;
+
+    static void audioConfigToHal(const AudioConfig& config, audio_config_t* halConfig);
+    static void audioGainConfigFromHal(
+            const struct audio_gain_config& halConfig, AudioGainConfig* config);
+    static void audioGainConfigToHal(
+            const AudioGainConfig& config, struct audio_gain_config* halConfig);
+    static void audioGainFromHal(const struct audio_gain& halGain, AudioGain* gain);
+    static void audioGainToHal(const AudioGain& gain, struct audio_gain* halGain);
+    static void audioOffloadInfoToHal(
+            const AudioOffloadInfo& offload, audio_offload_info_t* halOffload);
+    static void audioPortConfigFromHal(
+            const struct audio_port_config& halConfig, AudioPortConfig* config);
+    static void audioPortConfigToHal(
+            const AudioPortConfig& config, struct audio_port_config* halConfig);
+    static std::unique_ptr<audio_port_config[]> audioPortConfigsToHal(
+            const hidl_vec<AudioPortConfig>& configs);
+    static void audioPortFromHal(const struct audio_port& halPort, AudioPort* port);
+    static void audioPortToHal(const AudioPort& port, struct audio_port* halPort);
+
+    virtual ~Device();
+
+    // Methods from ParametersUtil.
+    char* halGetParameters(const char* keys) override;
+    int halSetParameters(const char* keysAndValues) override;
+
+    uint32_t version() const { return mDevice->common.version; }
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_V2_0_Device_H_
diff --git a/audio/2.0/default/DevicesFactory.cpp b/audio/2.0/default/DevicesFactory.cpp
new file mode 100644 (file)
index 0000000..1e087f2
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "DevicesFactoryHAL"
+
+#include <string.h>
+
+#include <utils/Log.h>
+
+#include "Device.h"
+#include "DevicesFactory.h"
+#include "PrimaryDevice.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+// static
+const char* DevicesFactory::deviceToString(IDevicesFactory::Device device) {
+    switch (device) {
+        case IDevicesFactory::Device::PRIMARY: return AUDIO_HARDWARE_MODULE_ID_PRIMARY;
+        case IDevicesFactory::Device::A2DP: return AUDIO_HARDWARE_MODULE_ID_A2DP;
+        case IDevicesFactory::Device::USB: return AUDIO_HARDWARE_MODULE_ID_USB;
+        case IDevicesFactory::Device::R_SUBMIX: return AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX;
+    }
+}
+
+// static
+int DevicesFactory::loadAudioInterface(const char *if_name, audio_hw_device_t **dev)
+{
+    const hw_module_t *mod;
+    int rc;
+
+    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
+    if (rc) {
+        ALOGE("%s couldn't load audio hw module %s.%s (%s)", __func__,
+                AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
+        goto out;
+    }
+    rc = audio_hw_device_open(mod, dev);
+    if (rc) {
+        ALOGE("%s couldn't open audio hw device in %s.%s (%s)", __func__,
+                AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
+        goto out;
+    }
+    if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
+        ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
+        rc = -EINVAL;
+        audio_hw_device_close(*dev);
+        goto out;
+    }
+    return OK;
+
+out:
+    *dev = NULL;
+    return rc;
+}
+
+// Methods from ::android::hardware::audio::V2_0::IDevicesFactory follow.
+Return<void> DevicesFactory::openDevice(IDevicesFactory::Device device, openDevice_cb _hidl_cb)  {
+    audio_hw_device_t *halDevice;
+    int halStatus = loadAudioInterface(deviceToString(device), &halDevice);
+    Result retval(Result::OK);
+    sp<IDevice> result;
+    if (halStatus == OK) {
+        if (device == IDevicesFactory::Device::PRIMARY) {
+            result = new PrimaryDevice(halDevice);
+        } else {
+            result = new ::android::hardware::audio::V2_0::implementation::Device(halDevice);
+        }
+    } else if (halStatus == -EINVAL) {
+        retval = Result::NOT_INITIALIZED;
+    } else {
+        retval = Result::INVALID_ARGUMENTS;
+    }
+    _hidl_cb(retval, result);
+    return Void();
+}
+
+IDevicesFactory* HIDL_FETCH_IDevicesFactory(const char* /* name */) {
+    return new DevicesFactory();
+}
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/DevicesFactory.h b/audio/2.0/default/DevicesFactory.h
new file mode 100644 (file)
index 0000000..0ea9859
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_V2_0_DevicesFactory_H_
+#define HIDL_GENERATED_android_hardware_audio_V2_0_DevicesFactory_H_
+
+#include <hardware/audio.h>
+
+#include <android/hardware/audio/2.0/IDevicesFactory.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::V2_0::IDevice;
+using ::android::hardware::audio::V2_0::IDevicesFactory;
+using ::android::hardware::audio::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct DevicesFactory : public IDevicesFactory {
+    // Methods from ::android::hardware::audio::V2_0::IDevicesFactory follow.
+    Return<void> openDevice(IDevicesFactory::Device device, openDevice_cb _hidl_cb)  override;
+
+  private:
+    static const char* deviceToString(IDevicesFactory::Device device);
+    static int loadAudioInterface(const char *if_name, audio_hw_device_t **dev);
+
+};
+
+extern "C" IDevicesFactory* HIDL_FETCH_IDevicesFactory(const char* name);
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_V2_0_DevicesFactory_H_
diff --git a/audio/2.0/default/ParametersUtil.cpp b/audio/2.0/default/ParametersUtil.cpp
new file mode 100644 (file)
index 0000000..75a60b9
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+#include "ParametersUtil.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+Result ParametersUtil::getParam(const char* name, bool* value) {
+    String8 halValue;
+    Result retval = getParam(name, &halValue);
+    *value = false;
+    if (retval == Result::OK) {
+        *value = !(halValue == AudioParameter::valueOff);
+    }
+    return retval;
+}
+
+Result ParametersUtil::getParam(const char* name, int* value) {
+    const String8 halName(name);
+    AudioParameter keys;
+    keys.addKey(halName);
+    std::unique_ptr<AudioParameter> params = getParams(keys);
+    status_t halStatus = params->getInt(halName, *value);
+    return halStatus == OK ? Result::OK : Result::INVALID_ARGUMENTS;
+}
+
+Result ParametersUtil::getParam(const char* name, String8* value) {
+    const String8 halName(name);
+    AudioParameter keys;
+    keys.addKey(halName);
+    std::unique_ptr<AudioParameter> params = getParams(keys);
+    status_t halStatus = params->get(halName, *value);
+    return halStatus == OK ? Result::OK : Result::INVALID_ARGUMENTS;
+}
+
+void ParametersUtil::getParametersImpl(
+        const hidl_vec<hidl_string>& keys,
+        std::function<void(Result retval, const hidl_vec<ParameterValue>& parameters)> cb)  {
+    AudioParameter halKeys;
+    for (size_t i = 0; i < keys.size(); ++i) {
+        halKeys.addKey(String8(keys[i].c_str()));
+    }
+    std::unique_ptr<AudioParameter> halValues = getParams(halKeys);
+    Result retval(Result::INVALID_ARGUMENTS);
+    hidl_vec<ParameterValue> result;
+    if (halValues->size() > 0) {
+        result.resize(halValues->size());
+        String8 halKey, halValue;
+        for (size_t i = 0; i < halValues->size(); ++i) {
+            status_t status = halValues->getAt(i, halKey, halValue);
+            if (status != OK) {
+                result.resize(0);
+                break;
+            }
+            result[i].key = halKey.string();
+            result[i].value = halValue.string();
+        }
+        if (result.size() != 0) {
+            retval = Result::OK;
+        }
+    }
+    cb(retval, result);
+}
+
+std::unique_ptr<AudioParameter> ParametersUtil::getParams(const AudioParameter& keys) {
+    String8 paramsAndValues;
+    char *halValues = halGetParameters(keys.keysToString().string());
+    if (halValues != NULL) {
+        paramsAndValues.setTo(halValues);
+        free(halValues);
+    } else {
+        paramsAndValues.clear();
+    }
+    return std::unique_ptr<AudioParameter>(new AudioParameter(paramsAndValues));
+}
+
+Result ParametersUtil::setParam(const char* name, bool value) {
+    AudioParameter param;
+    param.add(String8(name), String8(value ? AudioParameter::valueOn : AudioParameter::valueOff));
+    return setParams(param);
+}
+
+Result ParametersUtil::setParam(const char* name, int value) {
+    AudioParameter param;
+    param.addInt(String8(name), value);
+    return setParams(param);
+}
+
+Result ParametersUtil::setParam(const char* name, const char* value) {
+    AudioParameter param;
+    param.add(String8(name), String8(value));
+    return setParams(param);
+}
+
+Result ParametersUtil::setParametersImpl(const hidl_vec<ParameterValue>& parameters)  {
+    AudioParameter params;
+    for (size_t i = 0; i < parameters.size(); ++i) {
+        params.add(String8(parameters[i].key.c_str()), String8(parameters[i].value.c_str()));
+    }
+    return setParams(params);
+}
+
+Result ParametersUtil::setParams(const AudioParameter& param) {
+    int halStatus = halSetParameters(param.toString().string());
+    if (halStatus == OK)
+        return Result::OK;
+    else if (halStatus == -ENOSYS)
+        return Result::INVALID_STATE;
+    else
+        return Result::INVALID_ARGUMENTS;
+}
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/ParametersUtil.h b/audio/2.0/default/ParametersUtil.h
new file mode 100644 (file)
index 0000000..49036dc
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_audio_V2_0_ParametersUtil_H_
+#define android_hardware_audio_V2_0_ParametersUtil_H_
+
+#include <functional>
+#include <memory>
+
+#include <android/hardware/audio/2.0/types.h>
+#include <hidl/HidlSupport.h>
+#include <media/AudioParameter.h>
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::V2_0::ParameterValue;
+using ::android::hardware::audio::V2_0::Result;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+
+class ParametersUtil {
+  public:
+    Result getParam(const char* name, bool* value);
+    Result getParam(const char* name, int* value);
+    Result getParam(const char* name, String8* value);
+    void getParametersImpl(
+            const hidl_vec<hidl_string>& keys,
+            std::function<void(Result retval, const hidl_vec<ParameterValue>& parameters)> cb);
+    std::unique_ptr<AudioParameter> getParams(const AudioParameter& keys);
+    Result setParam(const char* name, bool value);
+    Result setParam(const char* name, int value);
+    Result setParam(const char* name, const char* value);
+    Result setParametersImpl(const hidl_vec<ParameterValue>& parameters);
+    Result setParams(const AudioParameter& param);
+
+  protected:
+    virtual ~ParametersUtil() {}
+
+    virtual char* halGetParameters(const char* keys) = 0;
+    virtual int halSetParameters(const char* keysAndValues) = 0;
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // android_hardware_audio_V2_0_ParametersUtil_H_
diff --git a/audio/2.0/default/PrimaryDevice.cpp b/audio/2.0/default/PrimaryDevice.cpp
new file mode 100644 (file)
index 0000000..9f5180c
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "PrimaryDeviceHAL"
+
+#include "PrimaryDevice.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+PrimaryDevice::PrimaryDevice(audio_hw_device_t* device)
+        : mDevice(new Device(device)) {
+}
+
+PrimaryDevice::~PrimaryDevice() {}
+
+// Methods from ::android::hardware::audio::V2_0::IDevice follow.
+Return<Result> PrimaryDevice::initCheck()  {
+    return mDevice->initCheck();
+}
+
+Return<Result> PrimaryDevice::setMasterVolume(float volume)  {
+    return mDevice->setMasterVolume(volume);
+}
+
+Return<void> PrimaryDevice::getMasterVolume(getMasterVolume_cb _hidl_cb)  {
+    return mDevice->getMasterVolume(_hidl_cb);
+}
+
+Return<Result> PrimaryDevice::setMicMute(bool mute)  {
+    return mDevice->setMicMute(mute);
+}
+
+Return<void> PrimaryDevice::getMicMute(getMicMute_cb _hidl_cb)  {
+    return mDevice->getMicMute(_hidl_cb);
+}
+
+Return<Result> PrimaryDevice::setMasterMute(bool mute)  {
+    return mDevice->setMasterMute(mute);
+}
+
+Return<void> PrimaryDevice::getMasterMute(getMasterMute_cb _hidl_cb)  {
+    return mDevice->getMasterMute(_hidl_cb);
+}
+
+Return<void> PrimaryDevice::getInputBufferSize(
+        const AudioConfig& config, getInputBufferSize_cb _hidl_cb)  {
+    return mDevice->getInputBufferSize(config, _hidl_cb);
+}
+
+Return<void> PrimaryDevice::openOutputStream(
+        int32_t ioHandle,
+        const DeviceAddress& device,
+        const AudioConfig& config,
+        AudioOutputFlag flags,
+        openOutputStream_cb _hidl_cb)  {
+    return mDevice->openOutputStream(ioHandle, device, config, flags, _hidl_cb);
+}
+
+Return<void> PrimaryDevice::openInputStream(
+        int32_t ioHandle,
+        const DeviceAddress& device,
+        const AudioConfig& config,
+        AudioInputFlag flags,
+        AudioSource source,
+        openInputStream_cb _hidl_cb)  {
+    return mDevice->openInputStream(ioHandle, device, config, flags, source, _hidl_cb);
+}
+
+Return<void> PrimaryDevice::createAudioPatch(
+        const hidl_vec<AudioPortConfig>& sources,
+        const hidl_vec<AudioPortConfig>& sinks,
+        createAudioPatch_cb _hidl_cb)  {
+    return mDevice->createAudioPatch(sources, sinks, _hidl_cb);
+}
+
+Return<Result> PrimaryDevice::releaseAudioPatch(int32_t patch)  {
+    return mDevice->releaseAudioPatch(patch);
+}
+
+Return<void> PrimaryDevice::getAudioPort(const AudioPort& port, getAudioPort_cb _hidl_cb)  {
+    return mDevice->getAudioPort(port, _hidl_cb);
+}
+
+Return<Result> PrimaryDevice::setAudioPortConfig(const AudioPortConfig& config)  {
+    return mDevice->setAudioPortConfig(config);
+}
+
+Return<AudioHwSync> PrimaryDevice::getHwAvSync()  {
+    return mDevice->getHwAvSync();
+}
+
+Return<Result> PrimaryDevice::setScreenState(bool turnedOn)  {
+    return mDevice->setScreenState(turnedOn);
+}
+
+Return<void> PrimaryDevice::getParameters(
+        const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  {
+    return mDevice->getParameters(keys, _hidl_cb);
+}
+
+Return<Result> PrimaryDevice::setParameters(const hidl_vec<ParameterValue>& parameters)  {
+    return mDevice->setParameters(parameters);
+}
+
+Return<void> PrimaryDevice::debugDump(const native_handle_t* fd)  {
+    return mDevice->debugDump(fd);
+}
+
+
+// Methods from ::android::hardware::audio::V2_0::IPrimaryDevice follow.
+Return<Result> PrimaryDevice::setVoiceVolume(float volume)  {
+    return mDevice->analyzeStatus(
+            "set_voice_volume",
+            mDevice->device()->set_voice_volume(mDevice->device(), volume));
+}
+
+Return<Result> PrimaryDevice::setMode(AudioMode mode)  {
+    return mDevice->analyzeStatus(
+            "set_mode",
+            mDevice->device()->set_mode(mDevice->device(), static_cast<audio_mode_t>(mode)));
+}
+
+Return<void> PrimaryDevice::getBtScoNrecEnabled(getBtScoNrecEnabled_cb _hidl_cb)  {
+    bool enabled;
+    Result retval = mDevice->getParam(AudioParameter::keyBtNrec, &enabled);
+    _hidl_cb(retval, enabled);
+    return Void();
+}
+
+Return<Result> PrimaryDevice::setBtScoNrecEnabled(bool enabled)  {
+    return mDevice->setParam(AudioParameter::keyBtNrec, enabled);
+}
+
+Return<void> PrimaryDevice::getBtScoWidebandEnabled(getBtScoWidebandEnabled_cb _hidl_cb)  {
+    bool enabled;
+    Result retval = mDevice->getParam(AUDIO_PARAMETER_KEY_BT_SCO_WB, &enabled);
+    _hidl_cb(retval, enabled);
+    return Void();
+}
+
+Return<Result> PrimaryDevice::setBtScoWidebandEnabled(bool enabled)  {
+    return mDevice->setParam(AUDIO_PARAMETER_KEY_BT_SCO_WB, enabled);
+}
+
+Return<void> PrimaryDevice::getTtyMode(getTtyMode_cb _hidl_cb)  {
+    int halMode;
+    Result retval = mDevice->getParam(AUDIO_PARAMETER_KEY_TTY_MODE, &halMode);
+    TtyMode mode = retval == Result::OK ? TtyMode(halMode) : TtyMode::OFF;
+    _hidl_cb(retval, mode);
+    return Void();
+}
+
+Return<Result> PrimaryDevice::setTtyMode(IPrimaryDevice::TtyMode mode)  {
+    return mDevice->setParam(AUDIO_PARAMETER_KEY_TTY_MODE, static_cast<int>(mode));
+}
+
+Return<void> PrimaryDevice::getHacEnabled(getHacEnabled_cb _hidl_cb)  {
+    bool enabled;
+    Result retval = mDevice->getParam(AUDIO_PARAMETER_KEY_HAC, &enabled);
+    _hidl_cb(retval, enabled);
+    return Void();
+}
+
+Return<Result> PrimaryDevice::setHacEnabled(bool enabled)  {
+    return mDevice->setParam(AUDIO_PARAMETER_KEY_HAC, enabled);
+}
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/PrimaryDevice.h b/audio/2.0/default/PrimaryDevice.h
new file mode 100644 (file)
index 0000000..4c5b590
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_V2_0_PrimaryDevice_H_
+#define HIDL_GENERATED_android_hardware_audio_V2_0_PrimaryDevice_H_
+
+#include <android/hardware/audio/2.0/IPrimaryDevice.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Device.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioConfig;
+using ::android::hardware::audio::common::V2_0::AudioInputFlag;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioOutputFlag;
+using ::android::hardware::audio::common::V2_0::AudioPort;
+using ::android::hardware::audio::common::V2_0::AudioPortConfig;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::V2_0::DeviceAddress;
+using ::android::hardware::audio::V2_0::IDevice;
+using ::android::hardware::audio::V2_0::IPrimaryDevice;
+using ::android::hardware::audio::V2_0::IStreamIn;
+using ::android::hardware::audio::V2_0::IStreamOut;
+using ::android::hardware::audio::V2_0::ParameterValue;
+using ::android::hardware::audio::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct PrimaryDevice : public IPrimaryDevice {
+    explicit PrimaryDevice(audio_hw_device_t* device);
+
+    // Methods from ::android::hardware::audio::V2_0::IDevice follow.
+    Return<Result> initCheck()  override;
+    Return<Result> setMasterVolume(float volume)  override;
+    Return<void> getMasterVolume(getMasterVolume_cb _hidl_cb)  override;
+    Return<Result> setMicMute(bool mute)  override;
+    Return<void> getMicMute(getMicMute_cb _hidl_cb)  override;
+    Return<Result> setMasterMute(bool mute)  override;
+    Return<void> getMasterMute(getMasterMute_cb _hidl_cb)  override;
+    Return<void> getInputBufferSize(
+            const AudioConfig& config, getInputBufferSize_cb _hidl_cb)  override;
+    Return<void> openOutputStream(
+            int32_t ioHandle,
+            const DeviceAddress& device,
+            const AudioConfig& config,
+            AudioOutputFlag flags,
+            openOutputStream_cb _hidl_cb)  override;
+    Return<void> openInputStream(
+            int32_t ioHandle,
+            const DeviceAddress& device,
+            const AudioConfig& config,
+            AudioInputFlag flags,
+            AudioSource source,
+            openInputStream_cb _hidl_cb)  override;
+    Return<void> createAudioPatch(
+            const hidl_vec<AudioPortConfig>& sources,
+            const hidl_vec<AudioPortConfig>& sinks,
+            createAudioPatch_cb _hidl_cb)  override;
+    Return<Result> releaseAudioPatch(int32_t patch)  override;
+    Return<void> getAudioPort(const AudioPort& port, getAudioPort_cb _hidl_cb)  override;
+    Return<Result> setAudioPortConfig(const AudioPortConfig& config)  override;
+    Return<AudioHwSync> getHwAvSync()  override;
+    Return<Result> setScreenState(bool turnedOn)  override;
+    Return<void> getParameters(
+            const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  override;
+    Return<Result> setParameters(const hidl_vec<ParameterValue>& parameters)  override;
+    Return<void> debugDump(const native_handle_t* fd)  override;
+
+    // Methods from ::android::hardware::audio::V2_0::IPrimaryDevice follow.
+    Return<Result> setVoiceVolume(float volume)  override;
+    Return<Result> setMode(AudioMode mode)  override;
+    Return<void> getBtScoNrecEnabled(getBtScoNrecEnabled_cb _hidl_cb)  override;
+    Return<Result> setBtScoNrecEnabled(bool enabled)  override;
+    Return<void> getBtScoWidebandEnabled(getBtScoWidebandEnabled_cb _hidl_cb)  override;
+    Return<Result> setBtScoWidebandEnabled(bool enabled)  override;
+    Return<void> getTtyMode(getTtyMode_cb _hidl_cb)  override;
+    Return<Result> setTtyMode(IPrimaryDevice::TtyMode mode)  override;
+    Return<void> getHacEnabled(getHacEnabled_cb _hidl_cb)  override;
+    Return<Result> setHacEnabled(bool enabled)  override;
+
+  private:
+    sp<Device> mDevice;
+
+    virtual ~PrimaryDevice();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_V2_0_PrimaryDevice_H_
diff --git a/audio/2.0/default/Stream.cpp b/audio/2.0/default/Stream.cpp
new file mode 100644 (file)
index 0000000..7616bec
--- /dev/null
@@ -0,0 +1,236 @@
+/*
+ * 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.
+ */
+
+#include <inttypes.h>
+
+#define LOG_TAG "StreamHAL"
+
+#include <hardware/audio.h>
+#include <hardware/audio_effect.h>
+#include <media/TypeConverter.h>
+#include <utils/Log.h>
+#include <utils/SortedVector.h>
+#include <utils/Vector.h>
+
+#include "Conversions.h"
+#include "EffectMap.h"
+#include "Stream.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+Stream::Stream(audio_stream_t* stream)
+        : mStream(stream) {
+}
+
+Stream::~Stream() {
+    mStream = nullptr;
+}
+
+Result Stream::analyzeStatus(const char* funcName, int status) {
+    if (status != 0) {
+        ALOGW("Stream %p %s: %s", mStream, funcName, strerror(-status));
+    }
+    switch (status) {
+        case 0: return Result::OK;
+        case -EINVAL: return Result::INVALID_ARGUMENTS;
+        case -ENODATA: return Result::INVALID_STATE;
+        case -ENODEV: return Result::NOT_INITIALIZED;
+        case -ENOSYS: return Result::NOT_SUPPORTED;
+        default: return Result::INVALID_STATE;
+    }
+}
+
+char* Stream::halGetParameters(const char* keys) {
+    return mStream->get_parameters(mStream, keys);
+}
+
+int Stream::halSetParameters(const char* keysAndValues) {
+    return mStream->set_parameters(mStream, keysAndValues);
+}
+
+// Methods from ::android::hardware::audio::V2_0::IStream follow.
+Return<uint64_t> Stream::getFrameSize()  {
+    // Needs to be implemented by interface subclasses. But can't be declared as pure virtual,
+    // since interface subclasses implementation do not inherit from this class.
+    LOG_ALWAYS_FATAL("Stream::getFrameSize is pure abstract");
+    return uint64_t {};
+}
+
+Return<uint64_t> Stream::getFrameCount()  {
+    int halFrameCount;
+    Result retval = getParam(AudioParameter::keyFrameCount, &halFrameCount);
+    return retval == Result::OK ? halFrameCount : 0;
+}
+
+Return<uint64_t> Stream::getBufferSize()  {
+    return mStream->get_buffer_size(mStream);
+}
+
+Return<uint32_t> Stream::getSampleRate()  {
+    return mStream->get_sample_rate(mStream);
+}
+
+Return<void> Stream::getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb)  {
+    String8 halListValue;
+    Result result = getParam(AudioParameter::keyStreamSupportedSamplingRates, &halListValue);
+    hidl_vec<uint32_t> sampleRates;
+    SortedVector<uint32_t> halSampleRates;
+    if (result == Result::OK) {
+        halSampleRates = samplingRatesFromString(
+                halListValue.string(), AudioParameter::valueListSeparator);
+        sampleRates.setToExternal(halSampleRates.editArray(), halSampleRates.size());
+    }
+    _hidl_cb(sampleRates);
+    return Void();
+}
+
+Return<Result> Stream::setSampleRate(uint32_t sampleRateHz)  {
+    return setParam(AudioParameter::keySamplingRate, static_cast<int>(sampleRateHz));
+}
+
+Return<AudioChannelMask> Stream::getChannelMask()  {
+    return AudioChannelMask(mStream->get_channels(mStream));
+}
+
+Return<void> Stream::getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb)  {
+    String8 halListValue;
+    Result result = getParam(AudioParameter::keyStreamSupportedChannels, &halListValue);
+    hidl_vec<AudioChannelMask> channelMasks;
+    SortedVector<audio_channel_mask_t> halChannelMasks;
+    if (result == Result::OK) {
+        halChannelMasks = channelMasksFromString(
+                halListValue.string(), AudioParameter::valueListSeparator);
+        channelMasks.resize(halChannelMasks.size());
+        for (size_t i = 0; i < halChannelMasks.size(); ++i) {
+            channelMasks[i] = AudioChannelMask(halChannelMasks[i]);
+        }
+    }
+     _hidl_cb(channelMasks);
+    return Void();
+}
+
+Return<Result> Stream::setChannelMask(AudioChannelMask mask)  {
+    return setParam(AudioParameter::keyChannels, static_cast<int>(mask));
+}
+
+Return<AudioFormat> Stream::getFormat()  {
+    return AudioFormat(mStream->get_format(mStream));
+}
+
+Return<void> Stream::getSupportedFormats(getSupportedFormats_cb _hidl_cb)  {
+    String8 halListValue;
+    Result result = getParam(AudioParameter::keyStreamSupportedFormats, &halListValue);
+    hidl_vec<AudioFormat> formats;
+    Vector<audio_format_t> halFormats;
+    if (result == Result::OK) {
+        halFormats = formatsFromString(halListValue.string(), AudioParameter::valueListSeparator);
+        formats.resize(halFormats.size());
+        for (size_t i = 0; i < halFormats.size(); ++i) {
+            formats[i] = AudioFormat(halFormats[i]);
+        }
+    }
+     _hidl_cb(formats);
+    return Void();
+}
+
+Return<Result> Stream::setFormat(AudioFormat format)  {
+    return setParam(AudioParameter::keyFormat, static_cast<int>(format));
+}
+
+Return<void> Stream::getAudioProperties(getAudioProperties_cb _hidl_cb)  {
+    uint32_t halSampleRate = mStream->get_sample_rate(mStream);
+    audio_channel_mask_t halMask = mStream->get_channels(mStream);
+    audio_format_t halFormat = mStream->get_format(mStream);
+    _hidl_cb(halSampleRate, AudioChannelMask(halMask), AudioFormat(halFormat));
+    return Void();
+}
+
+Return<Result> Stream::addEffect(uint64_t effectId)  {
+    effect_handle_t halEffect = EffectMap::getInstance().get(effectId);
+    if (halEffect != NULL) {
+        return analyzeStatus("add_audio_effect", mStream->add_audio_effect(mStream, halEffect));
+    } else {
+        ALOGW("Invalid effect ID passed from client: %" PRIu64, effectId);
+        return Result::INVALID_ARGUMENTS;
+    }
+}
+
+Return<Result> Stream::removeEffect(uint64_t effectId)  {
+    effect_handle_t halEffect = EffectMap::getInstance().get(effectId);
+    if (halEffect != NULL) {
+        return analyzeStatus(
+                "remove_audio_effect", mStream->remove_audio_effect(mStream, halEffect));
+    } else {
+        ALOGW("Invalid effect ID passed from client: %" PRIu64, effectId);
+        return Result::INVALID_ARGUMENTS;
+    }
+}
+
+Return<Result> Stream::standby()  {
+    return analyzeStatus("standby", mStream->standby(mStream));
+}
+
+Return<AudioDevice> Stream::getDevice()  {
+    return AudioDevice(mStream->get_device(mStream));
+}
+
+Return<Result> Stream::setDevice(const DeviceAddress& address)  {
+    char* halDeviceAddress =
+            audio_device_address_to_parameter(
+                    static_cast<audio_devices_t>(address.device),
+                    deviceAddressToHal(address).c_str());
+    AudioParameter params((String8(halDeviceAddress)));
+    free(halDeviceAddress);
+    params.addInt(
+            String8(AudioParameter::keyRouting), static_cast<audio_devices_t>(address.device));
+    return setParams(params);
+}
+
+Return<Result> Stream::setConnectedState(const DeviceAddress& address, bool connected)  {
+    return setParam(
+            connected ? AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect,
+            deviceAddressToHal(address).c_str());
+}
+
+Return<Result> Stream::setHwAvSync(uint32_t hwAvSync)  {
+    return setParam(AudioParameter::keyStreamHwAvSync, static_cast<int>(hwAvSync));
+}
+
+Return<void> Stream::getParameters(const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  {
+    getParametersImpl(keys, _hidl_cb);
+    return Void();
+}
+
+Return<Result> Stream::setParameters(const hidl_vec<ParameterValue>& parameters)  {
+    return setParametersImpl(parameters);
+}
+
+Return<void> Stream::debugDump(const native_handle_t* fd)  {
+    if (fd->numFds == 1) {
+        analyzeStatus("dump", mStream->dump(mStream, fd->data[0]));
+    }
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/Stream.h b/audio/2.0/default/Stream.h
new file mode 100644 (file)
index 0000000..f28fbff
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_V2_0_Stream_H_
+#define HIDL_GENERATED_android_hardware_audio_V2_0_Stream_H_
+
+#include <android/hardware/audio/2.0/IStream.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "ParametersUtil.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioChannelMask;
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioFormat;
+using ::android::hardware::audio::V2_0::DeviceAddress;
+using ::android::hardware::audio::V2_0::IStream;
+using ::android::hardware::audio::V2_0::ParameterValue;
+using ::android::hardware::audio::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Stream : public IStream, public ParametersUtil {
+    explicit Stream(audio_stream_t* stream);
+
+    // Methods from ::android::hardware::audio::V2_0::IStream follow.
+    Return<uint64_t> getFrameSize()  override;
+    Return<uint64_t> getFrameCount()  override;
+    Return<uint64_t> getBufferSize()  override;
+    Return<uint32_t> getSampleRate()  override;
+    Return<void> getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb)  override;
+    Return<Result> setSampleRate(uint32_t sampleRateHz)  override;
+    Return<AudioChannelMask> getChannelMask()  override;
+    Return<void> getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb)  override;
+    Return<Result> setChannelMask(AudioChannelMask mask)  override;
+    Return<AudioFormat> getFormat()  override;
+    Return<void> getSupportedFormats(getSupportedFormats_cb _hidl_cb)  override;
+    Return<Result> setFormat(AudioFormat format)  override;
+    Return<void> getAudioProperties(getAudioProperties_cb _hidl_cb)  override;
+    Return<Result> addEffect(uint64_t effectId)  override;
+    Return<Result> removeEffect(uint64_t effectId)  override;
+    Return<Result> standby()  override;
+    Return<AudioDevice> getDevice()  override;
+    Return<Result> setDevice(const DeviceAddress& address)  override;
+    Return<Result> setConnectedState(const DeviceAddress& address, bool connected)  override;
+    Return<Result> setHwAvSync(uint32_t hwAvSync)  override;
+    Return<void> getParameters(
+            const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  override;
+    Return<Result> setParameters(const hidl_vec<ParameterValue>& parameters)  override;
+    Return<void> debugDump(const native_handle_t* fd)  override;
+
+    // Utility methods for extending interfaces.
+    Result analyzeStatus(const char* funcName, int status);
+
+  private:
+    audio_stream_t *mStream;
+
+    virtual ~Stream();
+
+    // Methods from ParametersUtil.
+    char* halGetParameters(const char* keys) override;
+    int halSetParameters(const char* keysAndValues) override;
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_V2_0_Stream_H_
diff --git a/audio/2.0/default/StreamIn.cpp b/audio/2.0/default/StreamIn.cpp
new file mode 100644 (file)
index 0000000..b590d1a
--- /dev/null
@@ -0,0 +1,191 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "StreamInHAL"
+
+#include <hardware/audio.h>
+#include <utils/Log.h>
+
+#include "StreamIn.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+StreamIn::StreamIn(audio_hw_device_t* device, audio_stream_in_t* stream)
+        : mDevice(device), mStream(stream), mStreamCommon(new Stream(&stream->common)) {
+}
+
+StreamIn::~StreamIn() {
+    mDevice->close_input_stream(mDevice, mStream);
+    mStream = nullptr;
+    mDevice = nullptr;
+}
+
+// Methods from ::android::hardware::audio::V2_0::IStream follow.
+Return<uint64_t> StreamIn::getFrameSize()  {
+    return audio_stream_in_frame_size(mStream);
+}
+
+Return<uint64_t> StreamIn::getFrameCount()  {
+    return mStreamCommon->getFrameCount();
+}
+
+Return<uint64_t> StreamIn::getBufferSize()  {
+    return mStreamCommon->getBufferSize();
+}
+
+Return<uint32_t> StreamIn::getSampleRate()  {
+    return mStreamCommon->getSampleRate();
+}
+
+Return<void> StreamIn::getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb)  {
+    return mStreamCommon->getSupportedSampleRates(_hidl_cb);
+}
+
+Return<Result> StreamIn::setSampleRate(uint32_t sampleRateHz)  {
+    return mStreamCommon->setSampleRate(sampleRateHz);
+}
+
+Return<AudioChannelMask> StreamIn::getChannelMask()  {
+    return mStreamCommon->getChannelMask();
+}
+
+Return<void> StreamIn::getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb)  {
+    return mStreamCommon->getSupportedChannelMasks(_hidl_cb);
+}
+
+Return<Result> StreamIn::setChannelMask(AudioChannelMask mask)  {
+    return mStreamCommon->setChannelMask(mask);
+}
+
+Return<AudioFormat> StreamIn::getFormat()  {
+    return mStreamCommon->getFormat();
+}
+
+Return<void> StreamIn::getSupportedFormats(getSupportedFormats_cb _hidl_cb)  {
+    return mStreamCommon->getSupportedFormats(_hidl_cb);
+}
+
+Return<Result> StreamIn::setFormat(AudioFormat format)  {
+    return mStreamCommon->setFormat(format);
+}
+
+Return<void> StreamIn::getAudioProperties(getAudioProperties_cb _hidl_cb)  {
+    return mStreamCommon->getAudioProperties(_hidl_cb);
+}
+
+Return<Result> StreamIn::addEffect(uint64_t effectId)  {
+    return mStreamCommon->addEffect(effectId);
+}
+
+Return<Result> StreamIn::removeEffect(uint64_t effectId)  {
+    return mStreamCommon->removeEffect(effectId);
+}
+
+Return<Result> StreamIn::standby()  {
+    return mStreamCommon->standby();
+}
+
+Return<AudioDevice> StreamIn::getDevice()  {
+    return mStreamCommon->getDevice();
+}
+
+Return<Result> StreamIn::setDevice(const DeviceAddress& address)  {
+    return mStreamCommon->setDevice(address);
+}
+
+Return<Result> StreamIn::setConnectedState(const DeviceAddress& address, bool connected)  {
+    return mStreamCommon->setConnectedState(address, connected);
+}
+
+Return<Result> StreamIn::setHwAvSync(uint32_t hwAvSync)  {
+    return mStreamCommon->setHwAvSync(hwAvSync);
+}
+
+Return<void> StreamIn::getParameters(const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb) {
+    return mStreamCommon->getParameters(keys, _hidl_cb);
+}
+
+Return<Result> StreamIn::setParameters(const hidl_vec<ParameterValue>& parameters)  {
+    return mStreamCommon->setParameters(parameters);
+}
+
+Return<void> StreamIn::debugDump(const native_handle_t* fd)  {
+    return mStreamCommon->debugDump(fd);
+}
+
+
+// Methods from ::android::hardware::audio::V2_0::IStreamIn follow.
+Return<void> StreamIn::getAudioSource(getAudioSource_cb _hidl_cb)  {
+    int halSource;
+    Result retval = mStreamCommon->getParam(AudioParameter::keyInputSource, &halSource);
+    AudioSource source(AudioSource::DEFAULT);
+    if (retval == Result::OK) {
+        source = AudioSource(halSource);
+    }
+    _hidl_cb(retval, source);
+    return Void();
+}
+
+Return<Result> StreamIn::setGain(float gain)  {
+    return mStreamCommon->analyzeStatus("set_gain", mStream->set_gain(mStream, gain));
+}
+
+Return<void> StreamIn::read(uint64_t size, read_cb _hidl_cb)  {
+    // TODO(mnaganov): Replace with FMQ version.
+    hidl_vec<uint8_t> data;
+    data.resize(size);
+    Result retval(Result::OK);
+    ssize_t readResult = mStream->read(mStream, &data[0], data.size());
+    if (readResult >= 0 && static_cast<size_t>(readResult) != data.size()) {
+        data.resize(readResult);
+    } else if (readResult < 0) {
+        data.resize(0);
+        retval = mStreamCommon->analyzeStatus("read", readResult);
+    }
+    _hidl_cb(retval, data);
+    return Void();
+}
+
+Return<uint32_t> StreamIn::getInputFramesLost()  {
+    return mStream->get_input_frames_lost(mStream);
+}
+
+Return<void> StreamIn::getCapturePosition(getCapturePosition_cb _hidl_cb)  {
+    Result retval(Result::NOT_SUPPORTED);
+    uint64_t frames = 0, time = 0;
+    if (mStream->get_capture_position != NULL) {
+        int64_t halFrames, halTime;
+        retval = mStreamCommon->analyzeStatus(
+                "get_capture_position",
+                mStream->get_capture_position(mStream, &halFrames, &halTime));
+        if (retval == Result::OK) {
+            frames = halFrames;
+            time = halTime;
+        }
+    }
+    _hidl_cb(retval, frames, time);
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/StreamIn.h b/audio/2.0/default/StreamIn.h
new file mode 100644 (file)
index 0000000..83f620c
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_V2_0_StreamIn_H_
+#define HIDL_GENERATED_android_hardware_audio_V2_0_StreamIn_H_
+
+#include <android/hardware/audio/2.0/IStreamIn.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Stream.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioChannelMask;
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioFormat;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::V2_0::DeviceAddress;
+using ::android::hardware::audio::V2_0::IStream;
+using ::android::hardware::audio::V2_0::IStreamIn;
+using ::android::hardware::audio::V2_0::ParameterValue;
+using ::android::hardware::audio::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct StreamIn : public IStreamIn {
+    StreamIn(audio_hw_device_t* device, audio_stream_in_t* stream);
+
+    // Methods from ::android::hardware::audio::V2_0::IStream follow.
+    Return<uint64_t> getFrameSize()  override;
+    Return<uint64_t> getFrameCount()  override;
+    Return<uint64_t> getBufferSize()  override;
+    Return<uint32_t> getSampleRate()  override;
+    Return<void> getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb)  override;
+    Return<Result> setSampleRate(uint32_t sampleRateHz)  override;
+    Return<AudioChannelMask> getChannelMask()  override;
+    Return<void> getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb)  override;
+    Return<Result> setChannelMask(AudioChannelMask mask)  override;
+    Return<AudioFormat> getFormat()  override;
+    Return<void> getSupportedFormats(getSupportedFormats_cb _hidl_cb)  override;
+    Return<Result> setFormat(AudioFormat format)  override;
+    Return<void> getAudioProperties(getAudioProperties_cb _hidl_cb)  override;
+    Return<Result> addEffect(uint64_t effectId)  override;
+    Return<Result> removeEffect(uint64_t effectId)  override;
+    Return<Result> standby()  override;
+    Return<AudioDevice> getDevice()  override;
+    Return<Result> setDevice(const DeviceAddress& address)  override;
+    Return<Result> setConnectedState(const DeviceAddress& address, bool connected)  override;
+    Return<Result> setHwAvSync(uint32_t hwAvSync)  override;
+    Return<void> getParameters(
+            const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  override;
+    Return<Result> setParameters(const hidl_vec<ParameterValue>& parameters)  override;
+    Return<void> debugDump(const native_handle_t* fd)  override;
+
+    // Methods from ::android::hardware::audio::V2_0::IStreamIn follow.
+    Return<void> getAudioSource(getAudioSource_cb _hidl_cb)  override;
+    Return<Result> setGain(float gain)  override;
+    Return<void> read(uint64_t size, read_cb _hidl_cb)  override;
+    Return<uint32_t> getInputFramesLost()  override;
+    Return<void> getCapturePosition(getCapturePosition_cb _hidl_cb)  override;
+
+  private:
+    audio_hw_device_t *mDevice;
+    audio_stream_in_t *mStream;
+    sp<Stream> mStreamCommon;
+
+    virtual ~StreamIn();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_V2_0_StreamIn_H_
diff --git a/audio/2.0/default/StreamOut.cpp b/audio/2.0/default/StreamOut.cpp
new file mode 100644 (file)
index 0000000..34bae29
--- /dev/null
@@ -0,0 +1,275 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "StreamOutHAL"
+
+#include <hardware/audio.h>
+#include <utils/Log.h>
+
+#include "StreamOut.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+StreamOut::StreamOut(audio_hw_device_t* device, audio_stream_out_t* stream)
+        : mDevice(device), mStream(stream), mStreamCommon(new Stream(&stream->common)) {
+}
+
+StreamOut::~StreamOut() {
+    mCallback.clear();
+    mDevice->close_output_stream(mDevice, mStream);
+    mStream = nullptr;
+    mDevice = nullptr;
+}
+
+// Methods from ::android::hardware::audio::V2_0::IStream follow.
+Return<uint64_t> StreamOut::getFrameSize()  {
+    return audio_stream_out_frame_size(mStream);
+}
+
+Return<uint64_t> StreamOut::getFrameCount()  {
+    return mStreamCommon->getFrameCount();
+}
+
+Return<uint64_t> StreamOut::getBufferSize()  {
+    return mStreamCommon->getBufferSize();
+}
+
+Return<uint32_t> StreamOut::getSampleRate()  {
+    return mStreamCommon->getSampleRate();
+}
+
+Return<void> StreamOut::getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb)  {
+    return mStreamCommon->getSupportedSampleRates(_hidl_cb);
+}
+
+Return<Result> StreamOut::setSampleRate(uint32_t sampleRateHz)  {
+    return mStreamCommon->setSampleRate(sampleRateHz);
+}
+
+Return<AudioChannelMask> StreamOut::getChannelMask()  {
+    return mStreamCommon->getChannelMask();
+}
+
+Return<void> StreamOut::getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb)  {
+    return mStreamCommon->getSupportedChannelMasks(_hidl_cb);
+}
+
+Return<Result> StreamOut::setChannelMask(AudioChannelMask mask)  {
+    return mStreamCommon->setChannelMask(mask);
+}
+
+Return<AudioFormat> StreamOut::getFormat()  {
+    return mStreamCommon->getFormat();
+}
+
+Return<void> StreamOut::getSupportedFormats(getSupportedFormats_cb _hidl_cb)  {
+    return mStreamCommon->getSupportedFormats(_hidl_cb);
+}
+
+Return<Result> StreamOut::setFormat(AudioFormat format)  {
+    return mStreamCommon->setFormat(format);
+}
+
+Return<void> StreamOut::getAudioProperties(getAudioProperties_cb _hidl_cb)  {
+    return mStreamCommon->getAudioProperties(_hidl_cb);
+}
+
+Return<Result> StreamOut::addEffect(uint64_t effectId)  {
+    return mStreamCommon->addEffect(effectId);
+}
+
+Return<Result> StreamOut::removeEffect(uint64_t effectId)  {
+    return mStreamCommon->removeEffect(effectId);
+}
+
+Return<Result> StreamOut::standby()  {
+    return mStreamCommon->standby();
+}
+
+Return<AudioDevice> StreamOut::getDevice()  {
+    return mStreamCommon->getDevice();
+}
+
+Return<Result> StreamOut::setDevice(const DeviceAddress& address)  {
+    return mStreamCommon->setDevice(address);
+}
+
+Return<Result> StreamOut::setConnectedState(const DeviceAddress& address, bool connected)  {
+    return mStreamCommon->setConnectedState(address, connected);
+}
+
+Return<Result> StreamOut::setHwAvSync(uint32_t hwAvSync)  {
+    return mStreamCommon->setHwAvSync(hwAvSync);
+}
+
+Return<void> StreamOut::getParameters(
+        const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  {
+    return mStreamCommon->getParameters(keys, _hidl_cb);
+}
+
+Return<Result> StreamOut::setParameters(const hidl_vec<ParameterValue>& parameters)  {
+    return mStreamCommon->setParameters(parameters);
+}
+
+Return<void> StreamOut::debugDump(const native_handle_t* fd)  {
+    return mStreamCommon->debugDump(fd);
+}
+
+
+// Methods from ::android::hardware::audio::V2_0::IStreamOut follow.
+Return<uint32_t> StreamOut::getLatency()  {
+    return mStream->get_latency(mStream);
+}
+
+Return<Result> StreamOut::setVolume(float left, float right)  {
+    Result retval(Result::NOT_SUPPORTED);
+    if (mStream->set_volume != NULL) {
+        retval = mStreamCommon->analyzeStatus(
+                "set_volume", mStream->set_volume(mStream, left, right));
+    }
+    return retval;
+}
+
+Return<void> StreamOut::write(const hidl_vec<uint8_t>& data, write_cb _hidl_cb)  {
+    // TODO(mnaganov): Replace with FMQ version.
+    Result retval(Result::OK);
+    uint64_t written = 0;
+    ssize_t writeResult = mStream->write(mStream, &data[0], data.size());
+    if (writeResult >= 0) {
+        written = writeResult;
+    } else {
+        retval = mStreamCommon->analyzeStatus("write", writeResult);
+        written = 0;
+    }
+    _hidl_cb(retval, written);
+    return Void();
+}
+
+Return<void> StreamOut::getRenderPosition(getRenderPosition_cb _hidl_cb)  {
+    uint32_t halDspFrames;
+    Result retval = mStreamCommon->analyzeStatus(
+            "get_render_position", mStream->get_render_position(mStream, &halDspFrames));
+    _hidl_cb(retval, halDspFrames);
+    return Void();
+}
+
+Return<void> StreamOut::getNextWriteTimestamp(getNextWriteTimestamp_cb _hidl_cb)  {
+    Result retval(Result::NOT_SUPPORTED);
+    int64_t timestampUs = 0;
+    if (mStream->get_next_write_timestamp != NULL) {
+        retval = mStreamCommon->analyzeStatus(
+                "get_next_write_timestamp",
+                mStream->get_next_write_timestamp(mStream, &timestampUs));
+    }
+    _hidl_cb(retval, timestampUs);
+    return Void();
+}
+
+Return<Result> StreamOut::setCallback(const sp<IStreamOutCallback>& callback)  {
+    if (mStream->set_callback == NULL) return Result::NOT_SUPPORTED;
+    int result = mStream->set_callback(mStream, StreamOut::asyncCallback, this);
+    if (result == 0) {
+        mCallback = callback;
+    }
+    return mStreamCommon->analyzeStatus("set_callback", result);
+}
+
+// static
+int StreamOut::asyncCallback(stream_callback_event_t event, void*, void *cookie) {
+    wp<StreamOut> weakSelf(reinterpret_cast<StreamOut*>(cookie));
+    sp<StreamOut> self = weakSelf.promote();
+    if (self == 0) return 0;
+    sp<IStreamOutCallback> callback = self->mCallback.promote();
+    if (callback == 0) return 0;
+    ALOGV("asyncCallback() event %d", event);
+    switch (event) {
+        case STREAM_CBK_EVENT_WRITE_READY:
+            callback->onWriteReady();
+            break;
+        case STREAM_CBK_EVENT_DRAIN_READY:
+            callback->onDrainReady();
+            break;
+        case STREAM_CBK_EVENT_ERROR:
+            callback->onError();
+            break;
+        default:
+            ALOGW("asyncCallback() unknown event %d", event);
+            break;
+    }
+    return 0;
+}
+
+Return<void> StreamOut::supportsPauseAndResume(supportsPauseAndResume_cb _hidl_cb)  {
+    _hidl_cb(mStream->pause != NULL, mStream->resume != NULL);
+    return Void();
+}
+
+Return<Result> StreamOut::pause()  {
+    return mStream->pause != NULL ?
+            mStreamCommon->analyzeStatus("pause", mStream->pause(mStream)) :
+            Result::NOT_SUPPORTED;
+}
+
+Return<Result> StreamOut::resume()  {
+    return mStream->resume != NULL ?
+            mStreamCommon->analyzeStatus("resume", mStream->resume(mStream)) :
+            Result::NOT_SUPPORTED;
+}
+
+Return<bool> StreamOut::supportsDrain()  {
+    return mStream->drain != NULL;
+}
+
+Return<Result> StreamOut::drain(AudioDrain type)  {
+    return mStream->drain != NULL ?
+            mStreamCommon->analyzeStatus(
+                    "drain", mStream->drain(mStream, static_cast<audio_drain_type_t>(type))) :
+            Result::NOT_SUPPORTED;
+}
+
+Return<Result> StreamOut::flush()  {
+    return mStream->flush != NULL ?
+            mStreamCommon->analyzeStatus("flush", mStream->flush(mStream)) :
+            Result::NOT_SUPPORTED;
+}
+
+Return<void> StreamOut::getPresentationPosition(getPresentationPosition_cb _hidl_cb)  {
+    Result retval(Result::NOT_SUPPORTED);
+    uint64_t frames = 0;
+    TimeSpec timeStamp = { 0, 0 };
+    if (mStream->get_presentation_position != NULL) {
+        struct timespec halTimeStamp;
+        retval = mStreamCommon->analyzeStatus(
+                "get_presentation_position",
+                mStream->get_presentation_position(mStream, &frames, &halTimeStamp));
+        if (retval == Result::OK) {
+            timeStamp.tvSec = halTimeStamp.tv_sec;
+            timeStamp.tvNSec = halTimeStamp.tv_nsec;
+        }
+    }
+    _hidl_cb(retval, frames, timeStamp);
+    return Void();
+}
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/2.0/default/StreamOut.h b/audio/2.0/default/StreamOut.h
new file mode 100644 (file)
index 0000000..51b7df8
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_V2_0_StreamOut_H_
+#define HIDL_GENERATED_android_hardware_audio_V2_0_StreamOut_H_
+
+#include <android/hardware/audio/2.0/IStreamOut.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Stream.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioChannelMask;
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioFormat;
+using ::android::hardware::audio::V2_0::AudioDrain;
+using ::android::hardware::audio::V2_0::DeviceAddress;
+using ::android::hardware::audio::V2_0::IStream;
+using ::android::hardware::audio::V2_0::IStreamOut;
+using ::android::hardware::audio::V2_0::IStreamOutCallback;
+using ::android::hardware::audio::V2_0::ParameterValue;
+using ::android::hardware::audio::V2_0::Result;
+using ::android::hardware::audio::V2_0::TimeSpec;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct StreamOut : public IStreamOut {
+    StreamOut(audio_hw_device_t* device, audio_stream_out_t* stream);
+
+    // Methods from ::android::hardware::audio::V2_0::IStream follow.
+    Return<uint64_t> getFrameSize()  override;
+    Return<uint64_t> getFrameCount()  override;
+    Return<uint64_t> getBufferSize()  override;
+    Return<uint32_t> getSampleRate()  override;
+    Return<void> getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb)  override;
+    Return<Result> setSampleRate(uint32_t sampleRateHz)  override;
+    Return<AudioChannelMask> getChannelMask()  override;
+    Return<void> getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb)  override;
+    Return<Result> setChannelMask(AudioChannelMask mask)  override;
+    Return<AudioFormat> getFormat()  override;
+    Return<void> getSupportedFormats(getSupportedFormats_cb _hidl_cb)  override;
+    Return<Result> setFormat(AudioFormat format)  override;
+    Return<void> getAudioProperties(getAudioProperties_cb _hidl_cb)  override;
+    Return<Result> addEffect(uint64_t effectId)  override;
+    Return<Result> removeEffect(uint64_t effectId)  override;
+    Return<Result> standby()  override;
+    Return<AudioDevice> getDevice()  override;
+    Return<Result> setDevice(const DeviceAddress& address)  override;
+    Return<Result> setConnectedState(const DeviceAddress& address, bool connected)  override;
+    Return<Result> setHwAvSync(uint32_t hwAvSync)  override;
+    Return<void> getParameters(
+            const hidl_vec<hidl_string>& keys, getParameters_cb _hidl_cb)  override;
+    Return<Result> setParameters(const hidl_vec<ParameterValue>& parameters)  override;
+    Return<void> debugDump(const native_handle_t* fd)  override;
+
+    // Methods from ::android::hardware::audio::V2_0::IStreamOut follow.
+    Return<uint32_t> getLatency()  override;
+    Return<Result> setVolume(float left, float right)  override;
+    Return<void> write(const hidl_vec<uint8_t>& data, write_cb _hidl_cb)  override;
+    Return<void> getRenderPosition(getRenderPosition_cb _hidl_cb)  override;
+    Return<void> getNextWriteTimestamp(getNextWriteTimestamp_cb _hidl_cb)  override;
+    Return<Result> setCallback(const sp<IStreamOutCallback>& callback)  override;
+    Return<void> supportsPauseAndResume(supportsPauseAndResume_cb _hidl_cb)  override;
+    Return<Result> pause()  override;
+    Return<Result> resume()  override;
+    Return<bool> supportsDrain()  override;
+    Return<Result> drain(AudioDrain type)  override;
+    Return<Result> flush()  override;
+    Return<void> getPresentationPosition(getPresentationPosition_cb _hidl_cb)  override;
+
+  private:
+    audio_hw_device_t *mDevice;
+    audio_stream_out_t *mStream;
+    sp<Stream> mStreamCommon;
+    // Do not store sp<> to avoid creating a reference loop if the entity that holds
+    // onto the output stream owns or implements the callback.
+    wp<IStreamOutCallback> mCallback;
+
+    virtual ~StreamOut();
+
+    static int asyncCallback(stream_callback_event_t event, void *param, void *cookie);
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_V2_0_StreamOut_H_
diff --git a/audio/2.0/default/android.hardware.audio@2.0-service.rc b/audio/2.0/default/android.hardware.audio@2.0-service.rc
new file mode 100644 (file)
index 0000000..f9fecdb
--- /dev/null
@@ -0,0 +1,7 @@
+service audio-hal-2-0 /system/bin/hw/android.hardware.audio@2.0-service
+    class hal
+    user audioserver
+    # media gid needed for /dev/fm (radio) and for /data/misc/media (tee)
+    group audio camera drmrpc inet media mediadrm net_bt net_bt_admin net_bw_acct
+    ioprio rt 4
+    writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks
diff --git a/audio/2.0/default/service.cpp b/audio/2.0/default/service.cpp
new file mode 100644 (file)
index 0000000..147f7b9
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "audiohalservice"
+
+#include <hidl/LegacySupport.h>
+#include <android/hardware/audio/2.0/IDevicesFactory.h>
+#include <android/hardware/audio/effect/2.0/IEffectsFactory.h>
+#include <android/hardware/soundtrigger/2.0/ISoundTriggerHw.h>
+
+using android::hardware::IPCThreadState;
+using android::hardware::ProcessState;
+using android::hardware::audio::effect::V2_0::IEffectsFactory;
+using android::hardware::audio::V2_0::IDevicesFactory;
+using android::hardware::soundtrigger::V2_0::ISoundTriggerHw;
+using android::hardware::registerPassthroughServiceImplementation;
+
+int main(int /* argc */, char* /* argv */ []) {
+    registerPassthroughServiceImplementation<IDevicesFactory>("audio_devices_factory");
+    registerPassthroughServiceImplementation<IEffectsFactory>("audio_effects_factory");
+    registerPassthroughServiceImplementation<ISoundTriggerHw>("sound_trigger.primary");
+    return android::hardware::launchRpcServer(16);
+}
diff --git a/audio/2.0/types.hal b/audio/2.0/types.hal
new file mode 100644 (file)
index 0000000..9a5e4f1
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * 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 android.hardware.audio@2.0;
+
+import android.hardware.audio.common@2.0;
+
+enum Result {
+    OK,
+    NOT_INITIALIZED,
+    INVALID_ARGUMENTS,
+    INVALID_STATE,
+    NOT_SUPPORTED
+};
+
+@export(name="audio_drain_type_t", value_prefix="AUDIO_DRAIN_")
+enum AudioDrain {
+    /* drain() returns when all data has been played. */
+    ALL,
+    /* drain() returns a short time before all data from the current track has
+       been played to give time for gapless track switch. */
+    EARLY_NOTIFY
+};
+
+/*
+ * A substitute for POSIX timespec.
+ */
+struct TimeSpec {
+    uint64_t tvSec;   // seconds
+    uint64_t tvNSec;  // nanoseconds
+};
+
+/*
+ * IEEE 802 MAC address.
+ */
+typedef uint8_t[6] MacAddress;
+
+struct ParameterValue {
+    string key;
+    string value;
+};
+
+/*
+ * Specifies a device in case when several devices of the same type
+ * can be connected (e.g. BT A2DP, USB).
+ */
+struct DeviceAddress {
+    AudioDevice device;  // discriminator
+    union Address {
+        MacAddress mac;     // used for BLUETOOTH_A2DP_*
+        uint8_t[4] ipv4;    // used for IP
+        struct Alsa {
+            int32_t card;
+            int32_t device;
+        } alsa;             // used for USB_*
+    } address;
+    string busAddress;      // used for BUS
+    string rSubmixAddress;  // used for REMOTE_SUBMIX
+};
diff --git a/audio/Android.bp b/audio/Android.bp
new file mode 100644 (file)
index 0000000..3121a36
--- /dev/null
@@ -0,0 +1,7 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "2.0",
+    "common/2.0",
+    "effect/2.0",
+    "effect/2.0/vts/functional",
+]
diff --git a/audio/common/2.0/Android.bp b/audio/common/2.0/Android.bp
new file mode 100644 (file)
index 0000000..89ce3b6
--- /dev/null
@@ -0,0 +1,43 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.audio.common@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.audio.common@2.0",
+    srcs: [
+        "types.hal",
+    ],
+    out: [
+        "android/hardware/audio/common/2.0/types.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.audio.common@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.audio.common@2.0",
+    srcs: [
+        "types.hal",
+    ],
+    out: [
+        "android/hardware/audio/common/2.0/types.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.audio.common@2.0",
+    generated_sources: ["android.hardware.audio.common@2.0_genc++"],
+    generated_headers: ["android.hardware.audio.common@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.audio.common@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/audio/common/2.0/Android.mk b/audio/common/2.0/Android.mk
new file mode 100644 (file)
index 0000000..f8346b1
--- /dev/null
@@ -0,0 +1,37 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.audio.common@2.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/audio/common/2.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.audio.common@2.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/audio/common/2.0/default/Android.mk b/audio/common/2.0/default/Android.mk
new file mode 100644 (file)
index 0000000..aa60eb2
--- /dev/null
@@ -0,0 +1,29 @@
+#
+# 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.
+
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.audio.common@2.0-util
+LOCAL_SRC_FILES := \
+    EffectMap.cpp \
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
+
+LOCAL_SHARED_LIBRARIES := \
+    libutils \
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/audio/common/2.0/default/EffectMap.cpp b/audio/common/2.0/default/EffectMap.cpp
new file mode 100644 (file)
index 0000000..703b91c
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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.
+ */
+
+#include <atomic>
+
+#include "EffectMap.h"
+
+namespace android {
+
+ANDROID_SINGLETON_STATIC_INSTANCE(EffectMap);
+
+// static
+const uint64_t EffectMap::INVALID_ID = 0;
+
+// static
+uint64_t EffectMap::makeUniqueId() {
+    static std::atomic<uint64_t> counter{INVALID_ID + 1};
+    return counter++;
+}
+
+uint64_t EffectMap::add(effect_handle_t handle) {
+    uint64_t newId = makeUniqueId();
+    std::lock_guard<std::mutex> lock(mLock);
+    mEffects.add(newId, handle);
+    return newId;
+}
+
+effect_handle_t EffectMap::get(const uint64_t& id) {
+    std::lock_guard<std::mutex> lock(mLock);
+    ssize_t idx = mEffects.indexOfKey(id);
+    return idx >= 0 ? mEffects[idx] : NULL;
+}
+
+void EffectMap::remove(effect_handle_t handle) {
+    std::lock_guard<std::mutex> lock(mLock);
+    for (size_t i = 0; i < mEffects.size(); ++i) {
+        if (mEffects[i] == handle) {
+            mEffects.removeItemsAt(i);
+            break;
+        }
+    }
+}
+
+}  // namespace android
diff --git a/audio/common/2.0/default/EffectMap.h b/audio/common/2.0/default/EffectMap.h
new file mode 100644 (file)
index 0000000..82bbb1f
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_audio_V2_0_EffectMap_H_
+#define android_hardware_audio_V2_0_EffectMap_H_
+
+#include <mutex>
+
+#include <hardware/audio_effect.h>
+#include <utils/KeyedVector.h>
+#include <utils/Singleton.h>
+
+namespace android {
+
+// This class needs to be in 'android' ns because Singleton macros require that.
+class EffectMap : public Singleton<EffectMap> {
+  public:
+    static const uint64_t INVALID_ID;
+
+    uint64_t add(effect_handle_t handle);
+    effect_handle_t get(const uint64_t& id);
+    void remove(effect_handle_t handle);
+
+  private:
+    static uint64_t makeUniqueId();
+
+    std::mutex mLock;
+    KeyedVector<uint64_t, effect_handle_t> mEffects;
+};
+
+}  // namespace android
+
+#endif  // android_hardware_audio_V2_0_EffectMap_H_
diff --git a/audio/common/2.0/types.hal b/audio/common/2.0/types.hal
new file mode 100644 (file)
index 0000000..75fdb52
--- /dev/null
@@ -0,0 +1,852 @@
+/*
+ * 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 android.hardware.audio.common@2.0;
+
+/*
+ *
+ *  IDs and Handles
+ *
+ */
+
+/*
+ * Handle type for identifying audio sources and sinks.
+ */
+typedef int32_t AudioIoHandle;
+
+/*
+ * Audio hw module handle functions or structures referencing a module.
+ */
+typedef int32_t AudioModuleHandle;
+
+/*
+ * Each port has a unique ID or handle allocated by policy manager.
+ */
+typedef int32_t AudioPortHandle;
+
+/*
+ * Each patch is identified by a handle at the interface used to create that
+ * patch. For instance, when a patch is created by the audio HAL, the HAL
+ * allocates and returns a handle.  This handle is unique to a given audio HAL
+ * hardware module.  But the same patch receives another system wide unique
+ * handle allocated by the framework.  This unique handle is used for all
+ * transactions inside the framework.
+ */
+typedef int32_t AudioPatchHandle;
+
+/*
+ * A HW synchronization source returned by the audio HAL.
+ */
+typedef uint32_t AudioHwSync;
+
+/*
+ * Each port has a unique ID or handle allocated by policy manager.
+ */
+@export(name="")
+enum AudioHandleConsts {
+    AUDIO_IO_HANDLE_NONE = 0,
+    AUDIO_MODULE_HANDLE_NONE = 0,
+    AUDIO_PORT_HANDLE_NONE = 0,
+    AUDIO_PATCH_HANDLE_NONE = 0,
+};
+
+/*
+ * Commonly used structure for passing unique identifieds (UUID).
+ * For the definition of UUID, refer to ITU-T X.667 spec.
+ */
+struct Uuid {
+    uint32_t timeLow;
+    uint16_t timeMid;
+    uint16_t versionAndTimeHigh;
+    uint16_t variantAndClockSeqHigh;
+    uint8_t[6] node;
+};
+
+
+/*
+ *
+ *  Audio streams
+ *
+ */
+
+/*
+ * Audio stream type describing the intented use case of a stream.
+ */
+@export(name="audio_stream_type_t", value_prefix="AUDIO_STREAM_")
+enum AudioStreamType : int32_t {
+    // These values must kept in sync with
+    //  frameworks/base/media/java/android/media/AudioSystem.java
+    // TODO: Synchronization should be done automatically by tools
+    DEFAULT          = -1,
+    MIN              = 0,
+    VOICE_CALL       = 0,
+    SYSTEM           = 1,
+    RING             = 2,
+    MUSIC            = 3,
+    ALARM            = 4,
+    NOTIFICATION     = 5,
+    BLUETOOTH_SCO    = 6,
+    ENFORCED_AUDIBLE = 7,  // Sounds that cannot be muted by user and must be
+                           // routed to speaker
+    DTMF             = 8,
+    TTS              = 9,  // Transmitted Through Speaker.  Plays over speaker
+                           // only, silent on other devices
+    ACCESSIBILITY    = 10, // For accessibility talk back prompts
+    REROUTING        = 11, // For dynamic policy output mixes
+    PATCH            = 12, // For internal audio flinger tracks.  Fixed volume
+    PUBLIC_CNT       = TTS + 1,
+    // Number of streams considered by audio policy for volume and routing
+    FOR_POLICY_CNT   = PATCH,
+    CNT              = PATCH + 1
+};
+
+@export(name="audio_source_t", value_prefix="AUDIO_SOURCE_")
+enum AudioSource {
+    // These values must kept in sync with
+    //  frameworks/base/media/java/android/media/MediaRecorder.java,
+    //  frameworks/av/services/audiopolicy/AudioPolicyService.cpp,
+    //  system/media/audio_effects/include/audio_effects/audio_effects_conf.h
+    DEFAULT             = 0,
+    MIC                 = 1,
+    VOICE_UPLINK        = 2,
+    VOICE_DOWNLINK      = 3,
+    VOICE_CALL          = 4,
+    CAMCORDER           = 5,
+    VOICE_RECOGNITION   = 6,
+    VOICE_COMMUNICATION = 7,
+    /*
+     * Source for the mix to be presented remotely. An example of remote
+     * presentation is Wifi Display where a dongle attached to a TV can be used
+     * to play the mix captured by this audio source.
+     */
+    REMOTE_SUBMIX       = 8,
+    /*
+     * Source for unprocessed sound. Usage examples include level measurement
+     * and raw signal analysis.
+     */
+    UNPROCESSED         = 9,
+
+    CNT,
+    MAX                 = CNT - 1,
+    FM_TUNER            = 1998,
+    /*
+     * A low-priority, preemptible audio source for for background software
+     * hotword detection. Same tuning as VOICE_RECOGNITION.  Used only
+     * internally by the framework.
+     */
+    HOTWORD             = 1999
+};
+
+typedef int32_t AudioSession;
+/*
+ * Special audio session values.
+ */
+@export(name="audio_session_t", value_prefix="AUDIO_SESSION_")
+enum AudioSessionConsts : int32_t {
+    /*
+     * Session for effects attached to a particular output stream
+     * (value must be less than 0)
+     */
+    OUTPUT_STAGE = -1,
+    /*
+     * Session for effects applied to output mix. These effects can
+     * be moved by audio policy manager to another output stream
+     * (value must be 0)
+     */
+    OUTPUT_MIX = 0,
+    /*
+     * Application does not specify an explicit session ID to be used, and
+     * requests a new session ID to be allocated TODO use unique values for
+     * AUDIO_SESSION_OUTPUT_MIX and AUDIO_SESSION_ALLOCATE, after all uses have
+     * been updated from 0 to the appropriate symbol, and have been tested.
+     * Corresponds to AudioManager.AUDIO_SESSION_ID_GENERATE and
+     * AudioSystem.AUDIO_SESSION_ALLOCATE.
+     */
+    ALLOCATE = 0,
+    /*
+     * For use with AudioRecord::start(), this indicates no trigger session.
+     * It is also used with output tracks and patch tracks, which never have a
+     * session.
+     */
+    NONE = 0
+};
+
+/*
+ * Audio format  is a 32-bit word that consists of:
+ *   main format field (upper 8 bits)
+ *   sub format field (lower 24 bits).
+ *
+ * The main format indicates the main codec type. The sub format field indicates
+ * options and parameters for each format. The sub format is mainly used for
+ * record to indicate for instance the requested bitrate or profile.  It can
+ * also be used for certain formats to give informations not present in the
+ * encoded audio stream (e.g. octet alignement for AMR).
+ */
+@export(name="audio_format_t", value_prefix="AUDIO_FORMAT_")
+enum AudioFormat : uint32_t {
+    INVALID             = 0xFFFFFFFFUL,
+    DEFAULT             = 0,
+    PCM                 = 0x00000000UL, /* DO NOT CHANGE */
+    MP3                 = 0x01000000UL,
+    AMR_NB              = 0x02000000UL,
+    AMR_WB              = 0x03000000UL,
+    AAC                 = 0x04000000UL,
+    HE_AAC_V1           = 0x05000000UL, /* Deprecated, Use AAC_HE_V1*/
+    HE_AAC_V2           = 0x06000000UL, /* Deprecated, Use AAC_HE_V2*/
+    VORBIS              = 0x07000000UL,
+    OPUS                = 0x08000000UL,
+    AC3                 = 0x09000000UL,
+    E_AC3               = 0x0A000000UL,
+    DTS                 = 0x0B000000UL,
+    DTS_HD              = 0x0C000000UL,
+    // IEC61937 is encoded audio wrapped in 16-bit PCM.
+    IEC61937            = 0x0D000000UL,
+    DOLBY_TRUEHD        = 0x0E000000UL,
+    MAIN_MASK           = 0xFF000000UL, /* Deprecated */
+    SUB_MASK            = 0x00FFFFFFUL,
+
+    /* Subformats */
+    PCM_SUB_16_BIT        = 0x1, // PCM signed 16 bits
+    PCM_SUB_8_BIT         = 0x2, // PCM unsigned 8 bits
+    PCM_SUB_32_BIT        = 0x3, // PCM signed .31 fixed point
+    PCM_SUB_8_24_BIT      = 0x4, // PCM signed 8.23 fixed point
+    PCM_SUB_FLOAT         = 0x5, // PCM single-precision float pt
+    PCM_SUB_24_BIT_PACKED = 0x6, // PCM signed .23 fix pt (3 bytes)
+
+    MP3_SUB_NONE          = 0x0,
+
+    AMR_SUB_NONE          = 0x0,
+
+    AAC_SUB_MAIN          = 0x1,
+    AAC_SUB_LC            = 0x2,
+    AAC_SUB_SSR           = 0x4,
+    AAC_SUB_LTP           = 0x8,
+    AAC_SUB_HE_V1         = 0x10,
+    AAC_SUB_SCALABLE      = 0x20,
+    AAC_SUB_ERLC          = 0x40,
+    AAC_SUB_LD            = 0x80,
+    AAC_SUB_HE_V2         = 0x100,
+    AAC_SUB_ELD           = 0x200,
+
+    VORBIS_SUB_NONE       = 0x0,
+
+    /* Aliases */
+    /* note != AudioFormat.ENCODING_PCM_16BIT */
+    PCM_16_BIT          = (PCM | PCM_SUB_16_BIT),
+    /* note != AudioFormat.ENCODING_PCM_8BIT */
+    PCM_8_BIT           = (PCM | PCM_SUB_8_BIT),
+    PCM_32_BIT          = (PCM | PCM_SUB_32_BIT),
+    PCM_8_24_BIT        = (PCM | PCM_SUB_8_24_BIT),
+    PCM_FLOAT           = (PCM | PCM_SUB_FLOAT),
+    PCM_24_BIT_PACKED   = (PCM | PCM_SUB_24_BIT_PACKED),
+    AAC_MAIN            = (AAC | AAC_SUB_MAIN),
+    AAC_LC              = (AAC | AAC_SUB_LC),
+    AAC_SSR             = (AAC | AAC_SUB_SSR),
+    AAC_LTP             = (AAC | AAC_SUB_LTP),
+    AAC_HE_V1           = (AAC | AAC_SUB_HE_V1),
+    AAC_SCALABLE        = (AAC | AAC_SUB_SCALABLE),
+    AAC_ERLC            = (AAC | AAC_SUB_ERLC),
+    AAC_LD              = (AAC | AAC_SUB_LD),
+    AAC_HE_V2           = (AAC | AAC_SUB_HE_V2),
+    AAC_ELD             = (AAC | AAC_SUB_ELD)
+};
+
+/*
+ * Usage of these values highlights places in the code that use 2- or 8- channel
+ * assumptions.
+ */
+@export(name="")
+enum FixedChannelCount {
+    FCC_2 = 2, // This is typically due to legacy implementation of stereo I/O
+    FCC_8 = 8  // This is typically due to audio mixer and resampler limitations
+};
+
+/*
+ * A channel mask per se only defines the presence or absence of a channel, not
+ * the order.  See AUDIO_INTERLEAVE_* for the platform convention of order.
+ *
+ * AudioChannelMask is an opaque type and its internal layout should not be
+ * assumed as it may change in the future.  Instead, always use functions
+ * to examine it.
+ *
+ * These are the current representations:
+ *
+ *   REPRESENTATION_POSITION
+ *     is a channel mask representation for position assignment.  Each low-order
+ *     bit corresponds to the spatial position of a transducer (output), or
+ *     interpretation of channel (input).  The user of a channel mask needs to
+ *     know the context of whether it is for output or input.  The constants
+ *     OUT_* or IN_* apply to the bits portion.  It is not permitted for no bits
+ *     to be set.
+ *
+ *   REPRESENTATION_INDEX
+ *     is a channel mask representation for index assignment.  Each low-order
+ *     bit corresponds to a selected channel.  There is no platform
+ *     interpretation of the various bits.  There is no concept of output or
+ *     input.  It is not permitted for no bits to be set.
+ *
+ * All other representations are reserved for future use.
+ *
+ * Warning: current representation distinguishes between input and output, but
+ * this will not the be case in future revisions of the platform. Wherever there
+ * is an ambiguity between input and output that is currently resolved by
+ * checking the channel mask, the implementer should look for ways to fix it
+ * with additional information outside of the mask.
+ */
+@export(name="", value_prefix="AUDIO_CHANNEL_")
+enum AudioChannelMask : uint32_t {
+    REPRESENTATION_POSITION = 0, /* must be 0 for compatibility */
+    /* 1 is reserved for future use */
+    REPRESENTATION_INDEX    = 2,
+    /* 3 is reserved for future use */
+
+    /* These can be a complete value of AudioChannelMask */
+    NONE                      = 0x0,
+    INVALID                   = 0xC0000000,
+
+   /*
+    * These can be the bits portion of an AudioChannelMask
+    * with representation REPRESENTATION_POSITION.
+    */
+
+    /* output channels */
+    OUT_FRONT_LEFT            = 0x1,
+    OUT_FRONT_RIGHT           = 0x2,
+    OUT_FRONT_CENTER          = 0x4,
+    OUT_LOW_FREQUENCY         = 0x8,
+    OUT_BACK_LEFT             = 0x10,
+    OUT_BACK_RIGHT            = 0x20,
+    OUT_FRONT_LEFT_OF_CENTER  = 0x40,
+    OUT_FRONT_RIGHT_OF_CENTER = 0x80,
+    OUT_BACK_CENTER           = 0x100,
+    OUT_SIDE_LEFT             = 0x200,
+    OUT_SIDE_RIGHT            = 0x400,
+    OUT_TOP_CENTER            = 0x800,
+    OUT_TOP_FRONT_LEFT        = 0x1000,
+    OUT_TOP_FRONT_CENTER      = 0x2000,
+    OUT_TOP_FRONT_RIGHT       = 0x4000,
+    OUT_TOP_BACK_LEFT         = 0x8000,
+    OUT_TOP_BACK_CENTER       = 0x10000,
+    OUT_TOP_BACK_RIGHT        = 0x20000,
+
+    OUT_MONO     = OUT_FRONT_LEFT,
+    OUT_STEREO   = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT),
+    OUT_QUAD     = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT |
+            OUT_BACK_LEFT | OUT_BACK_RIGHT),
+    OUT_QUAD_BACK = OUT_QUAD,
+    /* like OUT_QUAD_BACK with *_SIDE_* instead of *_BACK_* */
+    OUT_QUAD_SIDE = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT |
+            OUT_SIDE_LEFT | OUT_SIDE_RIGHT),
+    OUT_5POINT1  = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT |
+            OUT_FRONT_CENTER | OUT_LOW_FREQUENCY |
+            OUT_BACK_LEFT | OUT_BACK_RIGHT),
+    OUT_5POINT1_BACK = OUT_5POINT1,
+    /* like OUT_5POINT1_BACK with *_SIDE_* instead of *_BACK_* */
+    OUT_5POINT1_SIDE = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT |
+            OUT_FRONT_CENTER | OUT_LOW_FREQUENCY |
+            OUT_SIDE_LEFT | OUT_SIDE_RIGHT),
+    /* matches the correct AudioFormat.CHANNEL_OUT_7POINT1_SURROUND */
+    OUT_7POINT1  = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT |
+            OUT_FRONT_CENTER | OUT_LOW_FREQUENCY |
+            OUT_BACK_LEFT | OUT_BACK_RIGHT |
+            OUT_SIDE_LEFT | OUT_SIDE_RIGHT),
+    OUT_ALL      = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT |
+            OUT_FRONT_CENTER | OUT_LOW_FREQUENCY |
+            OUT_BACK_LEFT | OUT_BACK_RIGHT |
+            OUT_FRONT_LEFT_OF_CENTER | OUT_FRONT_RIGHT_OF_CENTER |
+            OUT_BACK_CENTER |
+            OUT_SIDE_LEFT | OUT_SIDE_RIGHT |
+            OUT_TOP_CENTER |
+            OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_CENTER | OUT_TOP_FRONT_RIGHT |
+            OUT_TOP_BACK_LEFT | OUT_TOP_BACK_CENTER | OUT_TOP_BACK_RIGHT),
+
+    /* These are bits only, not complete values */
+
+    /* input channels */
+    IN_LEFT            = 0x4,
+    IN_RIGHT           = 0x8,
+    IN_FRONT           = 0x10,
+    IN_BACK            = 0x20,
+    IN_LEFT_PROCESSED  = 0x40,
+    IN_RIGHT_PROCESSED = 0x80,
+    IN_FRONT_PROCESSED = 0x100,
+    IN_BACK_PROCESSED  = 0x200,
+    IN_PRESSURE        = 0x400,
+    IN_X_AXIS          = 0x800,
+    IN_Y_AXIS          = 0x1000,
+    IN_Z_AXIS          = 0x2000,
+    IN_VOICE_UPLINK    = 0x4000,
+    IN_VOICE_DNLINK    = 0x8000,
+
+    IN_MONO   = IN_FRONT,
+    IN_STEREO = (IN_LEFT | IN_RIGHT),
+    IN_FRONT_BACK = (IN_FRONT | IN_BACK),
+    IN_ALL    = (IN_LEFT | IN_RIGHT | IN_FRONT | IN_BACK|
+            IN_LEFT_PROCESSED | IN_RIGHT_PROCESSED |
+            IN_FRONT_PROCESSED | IN_BACK_PROCESSED|
+            IN_PRESSURE |
+            IN_X_AXIS | IN_Y_AXIS | IN_Z_AXIS |
+            IN_VOICE_UPLINK | IN_VOICE_DNLINK),
+
+    COUNT_MAX    = 30,
+    INDEX_HDR    = REPRESENTATION_INDEX << COUNT_MAX,
+    INDEX_MASK_1 = INDEX_HDR | ((1 << 1) - 1),
+    INDEX_MASK_2 = INDEX_HDR | ((1 << 2) - 1),
+    INDEX_MASK_3 = INDEX_HDR | ((1 << 3) - 1),
+    INDEX_MASK_4 = INDEX_HDR | ((1 << 4) - 1),
+    INDEX_MASK_5 = INDEX_HDR | ((1 << 5) - 1),
+    INDEX_MASK_6 = INDEX_HDR | ((1 << 6) - 1),
+    INDEX_MASK_7 = INDEX_HDR | ((1 << 7) - 1),
+    INDEX_MASK_8 = INDEX_HDR | ((1 << 8) - 1)
+};
+
+
+/*
+ * Expresses the convention when stereo audio samples are stored interleaved
+ * in an array.  This should improve readability by allowing code to use
+ * symbolic indices instead of hard-coded [0] and [1].
+ *
+ * For multi-channel beyond stereo, the platform convention is that channels
+ * are interleaved in order from least significant channel mask bit to most
+ * significant channel mask bit, with unused bits skipped.  Any exceptions
+ * to this convention will be noted at the appropriate API.
+ */
+@export(name="", value_prefix="AUDIO_INTERLEAVE_")
+enum AudioInterleave {
+    LEFT   = 0,
+    RIGHT  = 1,
+};
+
+/*
+ * Major modes for a mobile device. The current mode setting affects audio
+ * routing.
+ */
+@export(name="audio_mode_t", value_prefix="AUDIO_MODE_")
+enum AudioMode {
+    INVALID          = -2,
+    CURRENT          = -1,
+    NORMAL           = 0,
+    RINGTONE         = 1,
+    IN_CALL          = 2,
+    IN_COMMUNICATION = 3,
+
+    CNT,
+    MAX              = CNT - 1,
+};
+
+@export(name="", value_prefix="AUDIO_DEVICE_")
+enum AudioDevice : uint32_t {
+    NONE                          = 0x0,
+    /* reserved bits */
+    BIT_IN                        = 0x80000000,
+    BIT_DEFAULT                   = 0x40000000,
+    /* output devices */
+    OUT_EARPIECE                  = 0x1,
+    OUT_SPEAKER                   = 0x2,
+    OUT_WIRED_HEADSET             = 0x4,
+    OUT_WIRED_HEADPHONE           = 0x8,
+    OUT_BLUETOOTH_SCO             = 0x10,
+    OUT_BLUETOOTH_SCO_HEADSET     = 0x20,
+    OUT_BLUETOOTH_SCO_CARKIT      = 0x40,
+    OUT_BLUETOOTH_A2DP            = 0x80,
+    OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100,
+    OUT_BLUETOOTH_A2DP_SPEAKER    = 0x200,
+    OUT_AUX_DIGITAL               = 0x400,
+    OUT_HDMI                      = OUT_AUX_DIGITAL,
+    /* uses an analog connection (multiplexed over the USB pins for instance) */
+    OUT_ANLG_DOCK_HEADSET         = 0x800,
+    OUT_DGTL_DOCK_HEADSET         = 0x1000,
+    /* USB accessory mode: Android device is USB device and dock is USB host */
+    OUT_USB_ACCESSORY             = 0x2000,
+    /* USB host mode: Android device is USB host and dock is USB device */
+    OUT_USB_DEVICE                = 0x4000,
+    OUT_REMOTE_SUBMIX             = 0x8000,
+    /* Telephony voice TX path */
+    OUT_TELEPHONY_TX              = 0x10000,
+    /* Analog jack with line impedance detected */
+    OUT_LINE                      = 0x20000,
+    /* HDMI Audio Return Channel */
+    OUT_HDMI_ARC                  = 0x40000,
+    /* S/PDIF out */
+    OUT_SPDIF                     = 0x80000,
+    /* FM transmitter out */
+    OUT_FM                        = 0x100000,
+    /* Line out for av devices */
+    OUT_AUX_LINE                  = 0x200000,
+    /* limited-output speaker device for acoustic safety */
+    OUT_SPEAKER_SAFE              = 0x400000,
+    OUT_IP                        = 0x800000,
+    /* audio bus implemented by the audio system (e.g an MOST stereo channel) */
+    OUT_BUS                       = 0x1000000,
+    OUT_DEFAULT                   = BIT_DEFAULT,
+    OUT_ALL      = (OUT_EARPIECE |
+            OUT_SPEAKER |
+            OUT_WIRED_HEADSET |
+            OUT_WIRED_HEADPHONE |
+            OUT_BLUETOOTH_SCO |
+            OUT_BLUETOOTH_SCO_HEADSET |
+            OUT_BLUETOOTH_SCO_CARKIT |
+            OUT_BLUETOOTH_A2DP |
+            OUT_BLUETOOTH_A2DP_HEADPHONES |
+            OUT_BLUETOOTH_A2DP_SPEAKER |
+            OUT_HDMI |
+            OUT_ANLG_DOCK_HEADSET |
+            OUT_DGTL_DOCK_HEADSET |
+            OUT_USB_ACCESSORY |
+            OUT_USB_DEVICE |
+            OUT_REMOTE_SUBMIX |
+            OUT_TELEPHONY_TX |
+            OUT_LINE |
+            OUT_HDMI_ARC |
+            OUT_SPDIF |
+            OUT_FM |
+            OUT_AUX_LINE |
+            OUT_SPEAKER_SAFE |
+            OUT_IP |
+            OUT_BUS |
+            OUT_DEFAULT),
+    OUT_ALL_A2DP = (OUT_BLUETOOTH_A2DP |
+            OUT_BLUETOOTH_A2DP_HEADPHONES |
+            OUT_BLUETOOTH_A2DP_SPEAKER),
+    OUT_ALL_SCO  = (OUT_BLUETOOTH_SCO |
+            OUT_BLUETOOTH_SCO_HEADSET |
+            OUT_BLUETOOTH_SCO_CARKIT),
+    OUT_ALL_USB  = (OUT_USB_ACCESSORY | OUT_USB_DEVICE),
+    /* input devices */
+    IN_COMMUNICATION         = BIT_IN | 0x1,
+    IN_AMBIENT               = BIT_IN | 0x2,
+    IN_BUILTIN_MIC           = BIT_IN | 0x4,
+    IN_BLUETOOTH_SCO_HEADSET = BIT_IN | 0x8,
+    IN_WIRED_HEADSET         = BIT_IN | 0x10,
+    IN_AUX_DIGITAL           = BIT_IN | 0x20,
+    IN_HDMI                  = IN_AUX_DIGITAL,
+    /* Telephony voice RX path */
+    IN_VOICE_CALL            = BIT_IN | 0x40,
+    IN_TELEPHONY_RX          = IN_VOICE_CALL,
+    IN_BACK_MIC              = BIT_IN | 0x80,
+    IN_REMOTE_SUBMIX         = BIT_IN | 0x100,
+    IN_ANLG_DOCK_HEADSET     = BIT_IN | 0x200,
+    IN_DGTL_DOCK_HEADSET     = BIT_IN | 0x400,
+    IN_USB_ACCESSORY         = BIT_IN | 0x800,
+    IN_USB_DEVICE            = BIT_IN | 0x1000,
+    /* FM tuner input */
+    IN_FM_TUNER              = BIT_IN | 0x2000,
+    /* TV tuner input */
+    IN_TV_TUNER              = BIT_IN | 0x4000,
+    /* Analog jack with line impedance detected */
+    IN_LINE                  = BIT_IN | 0x8000,
+    /* S/PDIF in */
+    IN_SPDIF                 = BIT_IN | 0x10000,
+    IN_BLUETOOTH_A2DP        = BIT_IN | 0x20000,
+    IN_LOOPBACK              = BIT_IN | 0x40000,
+    IN_IP                    = BIT_IN | 0x80000,
+    /* audio bus implemented by the audio system (e.g an MOST stereo channel) */
+    IN_BUS                   = BIT_IN | 0x100000,
+    IN_DEFAULT               = BIT_IN | BIT_DEFAULT,
+
+    IN_ALL     = (IN_COMMUNICATION |
+            IN_AMBIENT |
+            IN_BUILTIN_MIC |
+            IN_BLUETOOTH_SCO_HEADSET |
+            IN_WIRED_HEADSET |
+            IN_HDMI |
+            IN_TELEPHONY_RX |
+            IN_BACK_MIC |
+            IN_REMOTE_SUBMIX |
+            IN_ANLG_DOCK_HEADSET |
+            IN_DGTL_DOCK_HEADSET |
+            IN_USB_ACCESSORY |
+            IN_USB_DEVICE |
+            IN_FM_TUNER |
+            IN_TV_TUNER |
+            IN_LINE |
+            IN_SPDIF |
+            IN_BLUETOOTH_A2DP |
+            IN_LOOPBACK |
+            IN_IP |
+            IN_BUS |
+            IN_DEFAULT),
+    IN_ALL_SCO = IN_BLUETOOTH_SCO_HEADSET,
+    IN_ALL_USB  = (IN_USB_ACCESSORY | IN_USB_DEVICE),
+};
+
+/*
+ * The audio output flags serve two purposes:
+ *
+ *  - when an AudioTrack is created they indicate a "wish" to be connected to an
+ *    output stream with attributes corresponding to the specified flags;
+ *
+ *  - when present in an output profile descriptor listed for a particular audio
+ *    hardware module, they indicate that an output stream can be opened that
+ *    supports the attributes indicated by the flags.
+ *
+ * The audio policy manager will try to match the flags in the request
+ * (when getOuput() is called) to an available output stream.
+ */
+@export(name="audio_output_flags_t", value_prefix="AUDIO_OUTPUT_FLAG_")
+enum AudioOutputFlag {
+    NONE    = 0x0, // no attributes
+    DIRECT  = 0x1, // this output directly connects a track
+                   // to one output stream: no software mixer
+    PRIMARY = 0x2, // this output is the primary output of the device. It is
+                   // unique and must be present. It is opened by default and
+                   // receives routing, audio mode and volume controls related
+                   // to voice calls.
+    FAST    = 0x4,    // output supports "fast tracks", defined elsewhere
+    DEEP_BUFFER      = 0x8,   // use deep audio buffers
+    COMPRESS_OFFLOAD = 0x10,  // offload playback of compressed streams to
+                              // hardware codec
+    NON_BLOCKING     = 0x20,  // use non-blocking write
+    HW_AV_SYNC = 0x40,   // output uses a hardware A/V sync
+    TTS        = 0x80,   // output for streams transmitted through speaker at a
+                         // sample rate high enough to accommodate lower-range
+                         // ultrasonic p/b
+    RAW        = 0x100,  // minimize signal processing
+    SYNC       = 0x200,  // synchronize I/O streams
+    IEC958_NONAUDIO = 0x400, // Audio stream contains compressed audio in SPDIF
+                             // data bursts, not PCM.
+};
+
+/*
+ * The audio input flags are analogous to audio output flags.
+ * Currently they are used only when an AudioRecord is created,
+ * to indicate a preference to be connected to an input stream with
+ * attributes corresponding to the specified flags.
+ */
+@export(name="audio_input_flags_t", value_prefix="AUDIO_INPUT_FLAG_")
+enum AudioInputFlag {
+    NONE       = 0x0,  // no attributes
+    FAST       = 0x1,  // prefer an input that supports "fast tracks"
+    HW_HOTWORD = 0x2,  // prefer an input that captures from hw hotword source
+    RAW        = 0x4,  // minimize signal processing
+    SYNC       = 0x8,  // synchronize I/O streams
+};
+
+/*
+ * Additional information about the stream passed to hardware decoders.
+ */
+struct AudioOffloadInfo {
+    uint32_t sampleRateHz;
+    AudioChannelMask channelMask;
+    AudioFormat format;
+    AudioStreamType streamType;
+    uint32_t bitRatePerSecond;
+    int64_t durationMicroseconds;  // -1 if unknown
+    bool hasVideo;
+    bool isStreaming;
+};
+
+/*
+ * Commonly used audio stream configuration parameters.
+ */
+struct AudioConfig {
+    uint32_t sampleRateHz;
+    AudioChannelMask channelMask;
+    AudioFormat format;
+    AudioOffloadInfo offloadInfo;
+    uint64_t frameCount;
+};
+
+
+/*
+ *
+ *  Volume control
+ *
+ */
+
+/*
+ * Type of gain control exposed by an audio port.
+ */
+@export(name="", value_prefix="AUDIO_GAIN_MODE_")
+enum AudioGainMode : uint32_t {
+    JOINT = 0x1,    // supports joint channel gain control
+    CHANNELS = 0x2, // supports separate channel gain control
+    RAMP = 0x4      // supports gain ramps
+};
+
+/*
+ * An audio_gain struct is a representation of a gain stage.
+ * A gain stage is always attached to an audio port.
+ */
+struct AudioGain {
+    AudioGainMode mode;
+    AudioChannelMask channelMask; // channels which gain an be controlled
+    int32_t minValue;     // minimum gain value in millibels
+    int32_t maxValue;     // maximum gain value in millibels
+    int32_t defaultValue; // default gain value in millibels
+    uint32_t stepValue;   // gain step in millibels
+    uint32_t minRampMs;   // minimum ramp duration in ms
+    uint32_t maxRampMs;   // maximum ramp duration in ms
+};
+
+/*
+ * The gain configuration structure is used to get or set the gain values of a
+ * given port.
+ */
+struct AudioGainConfig {
+    int32_t index;  // index of the corresponding AudioGain in AudioPort.gains
+    AudioGainMode mode;
+    AudioChannelMask channelMask;  // channels which gain value follows
+    /*
+     * 4 = sizeof(AudioChannelMask),
+     * 8 is not "FCC_8", so it won't need to be changed for > 8 channels.
+     * Gain values in millibels for each channel ordered from LSb to MSb in
+     * channel mask. The number of values is 1 in joint mode or
+     * popcount(channel_mask).
+     */
+    int32_t[4 * 8] values;
+    uint32_t rampDurationMs;  // ramp duration in ms
+};
+
+
+/*
+ *
+ *  Routing control
+ *
+ */
+
+/*
+ * Types defined here are used to describe an audio source or sink at internal
+ * framework interfaces (audio policy, patch panel) or at the audio HAL.
+ * Sink and sources are grouped in a concept of “audio port” representing an
+ * audio end point at the edge of the system managed by the module exposing
+ * the interface.
+ */
+
+/* Audio port role: either source or sink */
+@export(name="audio_port_role_t", value_prefix="AUDIO_PORT_ROLE_")
+enum AudioPortRole {
+    NONE,
+    SOURCE,
+    SINK,
+};
+
+/*
+ * Audio port type indicates if it is a session (e.g AudioTrack), a mix (e.g
+ * PlaybackThread output) or a physical device (e.g OUT_SPEAKER)
+ */
+@export(name="audio_port_type_t", value_prefix="AUDIO_PORT_TYPE_")
+enum AudioPortType {
+    NONE,
+    DEVICE,
+    MIX,
+    SESSION,
+};
+
+/*
+ * Extension for audio port configuration structure when the audio port is a
+ * hardware device.
+ */
+struct AudioPortConfigDeviceExt {
+    AudioModuleHandle hwModule;  // module the device is attached to
+    AudioDevice type;            // device type (e.g OUT_SPEAKER)
+    uint8_t[32] address;         // device address. "" if N/A
+};
+
+/*
+ * Extension for audio port configuration structure when the audio port is an
+ * audio session.
+ */
+struct AudioPortConfigSessionExt {
+    AudioSession session;
+};
+
+/*
+ * Flags indicating which fields are to be considered in AudioPortConfig.
+ */
+@export(name="", value_prefix="AUDIO_PORT_CONFIG_")
+enum AudioPortConfigMask : uint32_t {
+    SAMPLE_RATE = 0x1,
+    CHANNEL_MASK =  0x2,
+    FORMAT = 0x4,
+    GAIN = 0x8,
+    ALL = SAMPLE_RATE | CHANNEL_MASK | FORMAT | GAIN
+};
+
+/*
+ * Audio port configuration structure used to specify a particular configuration
+ * of an audio port.
+ */
+struct AudioPortConfig {
+    AudioPortHandle id;
+    AudioPortConfigMask configMask;
+    uint32_t sampleRateHz;
+    AudioChannelMask channelMask;
+    AudioFormat format;
+    AudioGainConfig gain;
+    AudioPortType type;  // type is used as a discriminator for Ext union
+    AudioPortRole role;  // role is used as a discriminator for UseCase union
+    union Ext {
+        AudioPortConfigDeviceExt device;
+        struct AudioPortConfigMixExt {
+            AudioModuleHandle hwModule; // module the stream is attached to
+            AudioIoHandle ioHandle;     // I/O handle of the input/output stream
+            union UseCase {
+                AudioStreamType stream;
+                AudioSource source;
+            } useCase;
+        } mix;
+        AudioPortConfigSessionExt session;
+    } ext;
+};
+
+/*
+ * Extension for audio port structure when the audio port is a hardware device.
+ */
+struct AudioPortDeviceExt {
+    AudioModuleHandle hwModule;    // module the device is attached to
+    AudioDevice type;
+    uint8_t[32] address;
+};
+
+/*
+ * Latency class of the audio mix.
+ */
+@export(name="audio_mix_latency_class_t", value_prefix="AUDIO_LATENCY_")
+enum AudioMixLatencyClass {
+    LOW,
+    NORMAL
+} ;
+
+struct AudioPortMixExt {
+    AudioModuleHandle hwModule;     // module the stream is attached to
+    AudioIoHandle ioHandle;         // I/O handle of the stream
+    AudioMixLatencyClass latencyClass;
+};
+
+/*
+ * Extension for audio port structure when the audio port is an audio session.
+ */
+struct AudioPortSessionExt {
+    AudioSession session;
+};
+
+struct AudioPort {
+    AudioPortHandle id;
+    AudioPortRole role;
+    string name;
+    vec<uint32_t> sampleRates;
+    vec<AudioChannelMask> channelMasks;
+    vec<AudioFormat> formats;
+    vec<AudioGain> gains;
+    AudioPortConfig activeConfig; // current audio port configuration
+    AudioPortType type;  // type is used as a discriminator
+    union Ext {
+        AudioPortDeviceExt device;
+        AudioPortMixExt mix;
+        AudioPortSessionExt session;
+    } ext;
+};
diff --git a/audio/common/2.0/vts/types.vts b/audio/common/2.0/vts/types.vts
new file mode 100644 (file)
index 0000000..9c79611
--- /dev/null
@@ -0,0 +1,1678 @@
+component_class: HAL_HIDL
+component_type_version: 2.0
+component_name: "types"
+
+package: "android.hardware.audio.common"
+
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioHandleConsts"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "AUDIO_IO_HANDLE_NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "AUDIO_MODULE_HANDLE_NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "AUDIO_PORT_HANDLE_NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "AUDIO_PATCH_HANDLE_NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::Uuid"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "timeLow"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "timeMid"
+        type: TYPE_SCALAR
+        scalar_type: "uint16_t"
+    }
+    struct_value: {
+        name: "versionAndTimeHigh"
+        type: TYPE_SCALAR
+        scalar_type: "uint16_t"
+    }
+    struct_value: {
+        name: "variantAndClockSeqHigh"
+        type: TYPE_SCALAR
+        scalar_type: "uint16_t"
+    }
+    struct_value: {
+        name: "node"
+        type: TYPE_ARRAY
+        vector_value: {
+            vector_size: 6
+            type: TYPE_SCALAR
+            scalar_type: "uint8_t"
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioStreamType"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "DEFAULT"
+        scalar_value: {
+            int32_t: -1
+        }
+        enumerator: "MIN"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "VOICE_CALL"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "SYSTEM"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "RING"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "MUSIC"
+        scalar_value: {
+            int32_t: 3
+        }
+        enumerator: "ALARM"
+        scalar_value: {
+            int32_t: 4
+        }
+        enumerator: "NOTIFICATION"
+        scalar_value: {
+            int32_t: 5
+        }
+        enumerator: "BLUETOOTH_SCO"
+        scalar_value: {
+            int32_t: 6
+        }
+        enumerator: "ENFORCED_AUDIBLE"
+        scalar_value: {
+            int32_t: 7
+        }
+        enumerator: "DTMF"
+        scalar_value: {
+            int32_t: 8
+        }
+        enumerator: "TTS"
+        scalar_value: {
+            int32_t: 9
+        }
+        enumerator: "ACCESSIBILITY"
+        scalar_value: {
+            int32_t: 10
+        }
+        enumerator: "REROUTING"
+        scalar_value: {
+            int32_t: 11
+        }
+        enumerator: "PATCH"
+        scalar_value: {
+            int32_t: 12
+        }
+        enumerator: "PUBLIC_CNT"
+        scalar_value: {
+            int32_t: 10
+        }
+        enumerator: "FOR_POLICY_CNT"
+        scalar_value: {
+            int32_t: 12
+        }
+        enumerator: "CNT"
+        scalar_value: {
+            int32_t: 13
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioSource"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "DEFAULT"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "MIC"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "VOICE_UPLINK"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "VOICE_DOWNLINK"
+        scalar_value: {
+            int32_t: 3
+        }
+        enumerator: "VOICE_CALL"
+        scalar_value: {
+            int32_t: 4
+        }
+        enumerator: "CAMCORDER"
+        scalar_value: {
+            int32_t: 5
+        }
+        enumerator: "VOICE_RECOGNITION"
+        scalar_value: {
+            int32_t: 6
+        }
+        enumerator: "VOICE_COMMUNICATION"
+        scalar_value: {
+            int32_t: 7
+        }
+        enumerator: "REMOTE_SUBMIX"
+        scalar_value: {
+            int32_t: 8
+        }
+        enumerator: "UNPROCESSED"
+        scalar_value: {
+            int32_t: 9
+        }
+        enumerator: "CNT"
+        scalar_value: {
+            int32_t: 10
+        }
+        enumerator: "MAX"
+        scalar_value: {
+            int32_t: 9
+        }
+        enumerator: "FM_TUNER"
+        scalar_value: {
+            int32_t: 1998
+        }
+        enumerator: "HOTWORD"
+        scalar_value: {
+            int32_t: 1999
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioSessionConsts"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "OUTPUT_STAGE"
+        scalar_value: {
+            int32_t: -1
+        }
+        enumerator: "OUTPUT_MIX"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "ALLOCATE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioFormat"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "INVALID"
+        scalar_value: {
+            uint32_t: 4294967295
+        }
+        enumerator: "DEFAULT"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "PCM"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "MP3"
+        scalar_value: {
+            uint32_t: 16777216
+        }
+        enumerator: "AMR_NB"
+        scalar_value: {
+            uint32_t: 33554432
+        }
+        enumerator: "AMR_WB"
+        scalar_value: {
+            uint32_t: 50331648
+        }
+        enumerator: "AAC"
+        scalar_value: {
+            uint32_t: 67108864
+        }
+        enumerator: "HE_AAC_V1"
+        scalar_value: {
+            uint32_t: 83886080
+        }
+        enumerator: "HE_AAC_V2"
+        scalar_value: {
+            uint32_t: 100663296
+        }
+        enumerator: "VORBIS"
+        scalar_value: {
+            uint32_t: 117440512
+        }
+        enumerator: "OPUS"
+        scalar_value: {
+            uint32_t: 134217728
+        }
+        enumerator: "AC3"
+        scalar_value: {
+            uint32_t: 150994944
+        }
+        enumerator: "E_AC3"
+        scalar_value: {
+            uint32_t: 167772160
+        }
+        enumerator: "DTS"
+        scalar_value: {
+            uint32_t: 184549376
+        }
+        enumerator: "DTS_HD"
+        scalar_value: {
+            uint32_t: 201326592
+        }
+        enumerator: "IEC61937"
+        scalar_value: {
+            uint32_t: 218103808
+        }
+        enumerator: "DOLBY_TRUEHD"
+        scalar_value: {
+            uint32_t: 234881024
+        }
+        enumerator: "MAIN_MASK"
+        scalar_value: {
+            uint32_t: 4278190080
+        }
+        enumerator: "SUB_MASK"
+        scalar_value: {
+            uint32_t: 16777215
+        }
+        enumerator: "PCM_SUB_16_BIT"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "PCM_SUB_8_BIT"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "PCM_SUB_32_BIT"
+        scalar_value: {
+            uint32_t: 3
+        }
+        enumerator: "PCM_SUB_8_24_BIT"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "PCM_SUB_FLOAT"
+        scalar_value: {
+            uint32_t: 5
+        }
+        enumerator: "PCM_SUB_24_BIT_PACKED"
+        scalar_value: {
+            uint32_t: 6
+        }
+        enumerator: "MP3_SUB_NONE"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "AMR_SUB_NONE"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "AAC_SUB_MAIN"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "AAC_SUB_LC"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "AAC_SUB_SSR"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "AAC_SUB_LTP"
+        scalar_value: {
+            uint32_t: 8
+        }
+        enumerator: "AAC_SUB_HE_V1"
+        scalar_value: {
+            uint32_t: 16
+        }
+        enumerator: "AAC_SUB_SCALABLE"
+        scalar_value: {
+            uint32_t: 32
+        }
+        enumerator: "AAC_SUB_ERLC"
+        scalar_value: {
+            uint32_t: 64
+        }
+        enumerator: "AAC_SUB_LD"
+        scalar_value: {
+            uint32_t: 128
+        }
+        enumerator: "AAC_SUB_HE_V2"
+        scalar_value: {
+            uint32_t: 256
+        }
+        enumerator: "AAC_SUB_ELD"
+        scalar_value: {
+            uint32_t: 512
+        }
+        enumerator: "VORBIS_SUB_NONE"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "PCM_16_BIT"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "PCM_8_BIT"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "PCM_32_BIT"
+        scalar_value: {
+            uint32_t: 3
+        }
+        enumerator: "PCM_8_24_BIT"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "PCM_FLOAT"
+        scalar_value: {
+            uint32_t: 5
+        }
+        enumerator: "PCM_24_BIT_PACKED"
+        scalar_value: {
+            uint32_t: 6
+        }
+        enumerator: "AAC_MAIN"
+        scalar_value: {
+            uint32_t: 67108865
+        }
+        enumerator: "AAC_LC"
+        scalar_value: {
+            uint32_t: 67108866
+        }
+        enumerator: "AAC_SSR"
+        scalar_value: {
+            uint32_t: 67108868
+        }
+        enumerator: "AAC_LTP"
+        scalar_value: {
+            uint32_t: 67108872
+        }
+        enumerator: "AAC_HE_V1"
+        scalar_value: {
+            uint32_t: 67108880
+        }
+        enumerator: "AAC_SCALABLE"
+        scalar_value: {
+            uint32_t: 67108896
+        }
+        enumerator: "AAC_ERLC"
+        scalar_value: {
+            uint32_t: 67108928
+        }
+        enumerator: "AAC_LD"
+        scalar_value: {
+            uint32_t: 67108992
+        }
+        enumerator: "AAC_HE_V2"
+        scalar_value: {
+            uint32_t: 67109120
+        }
+        enumerator: "AAC_ELD"
+        scalar_value: {
+            uint32_t: 67109376
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::FixedChannelCount"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "FCC_2"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "FCC_8"
+        scalar_value: {
+            int32_t: 8
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioChannelMask"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "REPRESENTATION_POSITION"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "REPRESENTATION_INDEX"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "NONE"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "INVALID"
+        scalar_value: {
+            uint32_t: 3221225472
+        }
+        enumerator: "OUT_FRONT_LEFT"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "OUT_FRONT_RIGHT"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "OUT_FRONT_CENTER"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "OUT_LOW_FREQUENCY"
+        scalar_value: {
+            uint32_t: 8
+        }
+        enumerator: "OUT_BACK_LEFT"
+        scalar_value: {
+            uint32_t: 16
+        }
+        enumerator: "OUT_BACK_RIGHT"
+        scalar_value: {
+            uint32_t: 32
+        }
+        enumerator: "OUT_FRONT_LEFT_OF_CENTER"
+        scalar_value: {
+            uint32_t: 64
+        }
+        enumerator: "OUT_FRONT_RIGHT_OF_CENTER"
+        scalar_value: {
+            uint32_t: 128
+        }
+        enumerator: "OUT_BACK_CENTER"
+        scalar_value: {
+            uint32_t: 256
+        }
+        enumerator: "OUT_SIDE_LEFT"
+        scalar_value: {
+            uint32_t: 512
+        }
+        enumerator: "OUT_SIDE_RIGHT"
+        scalar_value: {
+            uint32_t: 1024
+        }
+        enumerator: "OUT_TOP_CENTER"
+        scalar_value: {
+            uint32_t: 2048
+        }
+        enumerator: "OUT_TOP_FRONT_LEFT"
+        scalar_value: {
+            uint32_t: 4096
+        }
+        enumerator: "OUT_TOP_FRONT_CENTER"
+        scalar_value: {
+            uint32_t: 8192
+        }
+        enumerator: "OUT_TOP_FRONT_RIGHT"
+        scalar_value: {
+            uint32_t: 16384
+        }
+        enumerator: "OUT_TOP_BACK_LEFT"
+        scalar_value: {
+            uint32_t: 32768
+        }
+        enumerator: "OUT_TOP_BACK_CENTER"
+        scalar_value: {
+            uint32_t: 65536
+        }
+        enumerator: "OUT_TOP_BACK_RIGHT"
+        scalar_value: {
+            uint32_t: 131072
+        }
+        enumerator: "OUT_MONO"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "OUT_STEREO"
+        scalar_value: {
+            uint32_t: 3
+        }
+        enumerator: "OUT_QUAD"
+        scalar_value: {
+            uint32_t: 51
+        }
+        enumerator: "OUT_QUAD_BACK"
+        scalar_value: {
+            uint32_t: 51
+        }
+        enumerator: "OUT_QUAD_SIDE"
+        scalar_value: {
+            uint32_t: 1539
+        }
+        enumerator: "OUT_5POINT1"
+        scalar_value: {
+            uint32_t: 63
+        }
+        enumerator: "OUT_5POINT1_BACK"
+        scalar_value: {
+            uint32_t: 63
+        }
+        enumerator: "OUT_5POINT1_SIDE"
+        scalar_value: {
+            uint32_t: 1551
+        }
+        enumerator: "OUT_7POINT1"
+        scalar_value: {
+            uint32_t: 1599
+        }
+        enumerator: "OUT_ALL"
+        scalar_value: {
+            uint32_t: 262143
+        }
+        enumerator: "IN_LEFT"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "IN_RIGHT"
+        scalar_value: {
+            uint32_t: 8
+        }
+        enumerator: "IN_FRONT"
+        scalar_value: {
+            uint32_t: 16
+        }
+        enumerator: "IN_BACK"
+        scalar_value: {
+            uint32_t: 32
+        }
+        enumerator: "IN_LEFT_PROCESSED"
+        scalar_value: {
+            uint32_t: 64
+        }
+        enumerator: "IN_RIGHT_PROCESSED"
+        scalar_value: {
+            uint32_t: 128
+        }
+        enumerator: "IN_FRONT_PROCESSED"
+        scalar_value: {
+            uint32_t: 256
+        }
+        enumerator: "IN_BACK_PROCESSED"
+        scalar_value: {
+            uint32_t: 512
+        }
+        enumerator: "IN_PRESSURE"
+        scalar_value: {
+            uint32_t: 1024
+        }
+        enumerator: "IN_X_AXIS"
+        scalar_value: {
+            uint32_t: 2048
+        }
+        enumerator: "IN_Y_AXIS"
+        scalar_value: {
+            uint32_t: 4096
+        }
+        enumerator: "IN_Z_AXIS"
+        scalar_value: {
+            uint32_t: 8192
+        }
+        enumerator: "IN_VOICE_UPLINK"
+        scalar_value: {
+            uint32_t: 16384
+        }
+        enumerator: "IN_VOICE_DNLINK"
+        scalar_value: {
+            uint32_t: 32768
+        }
+        enumerator: "IN_MONO"
+        scalar_value: {
+            uint32_t: 16
+        }
+        enumerator: "IN_STEREO"
+        scalar_value: {
+            uint32_t: 12
+        }
+        enumerator: "IN_FRONT_BACK"
+        scalar_value: {
+            uint32_t: 48
+        }
+        enumerator: "IN_ALL"
+        scalar_value: {
+            uint32_t: 65532
+        }
+        enumerator: "COUNT_MAX"
+        scalar_value: {
+            uint32_t: 30
+        }
+        enumerator: "INDEX_HDR"
+        scalar_value: {
+            uint32_t: 2147483648
+        }
+        enumerator: "INDEX_MASK_1"
+        scalar_value: {
+            uint32_t: 2147483649
+        }
+        enumerator: "INDEX_MASK_2"
+        scalar_value: {
+            uint32_t: 2147483651
+        }
+        enumerator: "INDEX_MASK_3"
+        scalar_value: {
+            uint32_t: 2147483655
+        }
+        enumerator: "INDEX_MASK_4"
+        scalar_value: {
+            uint32_t: 2147483663
+        }
+        enumerator: "INDEX_MASK_5"
+        scalar_value: {
+            uint32_t: 2147483679
+        }
+        enumerator: "INDEX_MASK_6"
+        scalar_value: {
+            uint32_t: 2147483711
+        }
+        enumerator: "INDEX_MASK_7"
+        scalar_value: {
+            uint32_t: 2147483775
+        }
+        enumerator: "INDEX_MASK_8"
+        scalar_value: {
+            uint32_t: 2147483903
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioInterleave"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "LEFT"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "RIGHT"
+        scalar_value: {
+            int32_t: 1
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioMode"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "INVALID"
+        scalar_value: {
+            int32_t: -2
+        }
+        enumerator: "CURRENT"
+        scalar_value: {
+            int32_t: -1
+        }
+        enumerator: "NORMAL"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "RINGTONE"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "IN_CALL"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "IN_COMMUNICATION"
+        scalar_value: {
+            int32_t: 3
+        }
+        enumerator: "CNT"
+        scalar_value: {
+            int32_t: 4
+        }
+        enumerator: "MAX"
+        scalar_value: {
+            int32_t: 3
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioDevice"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "NONE"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "BIT_IN"
+        scalar_value: {
+            uint32_t: 2147483648
+        }
+        enumerator: "BIT_DEFAULT"
+        scalar_value: {
+            uint32_t: 1073741824
+        }
+        enumerator: "OUT_EARPIECE"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "OUT_SPEAKER"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "OUT_WIRED_HEADSET"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "OUT_WIRED_HEADPHONE"
+        scalar_value: {
+            uint32_t: 8
+        }
+        enumerator: "OUT_BLUETOOTH_SCO"
+        scalar_value: {
+            uint32_t: 16
+        }
+        enumerator: "OUT_BLUETOOTH_SCO_HEADSET"
+        scalar_value: {
+            uint32_t: 32
+        }
+        enumerator: "OUT_BLUETOOTH_SCO_CARKIT"
+        scalar_value: {
+            uint32_t: 64
+        }
+        enumerator: "OUT_BLUETOOTH_A2DP"
+        scalar_value: {
+            uint32_t: 128
+        }
+        enumerator: "OUT_BLUETOOTH_A2DP_HEADPHONES"
+        scalar_value: {
+            uint32_t: 256
+        }
+        enumerator: "OUT_BLUETOOTH_A2DP_SPEAKER"
+        scalar_value: {
+            uint32_t: 512
+        }
+        enumerator: "OUT_AUX_DIGITAL"
+        scalar_value: {
+            uint32_t: 1024
+        }
+        enumerator: "OUT_HDMI"
+        scalar_value: {
+            uint32_t: 1024
+        }
+        enumerator: "OUT_ANLG_DOCK_HEADSET"
+        scalar_value: {
+            uint32_t: 2048
+        }
+        enumerator: "OUT_DGTL_DOCK_HEADSET"
+        scalar_value: {
+            uint32_t: 4096
+        }
+        enumerator: "OUT_USB_ACCESSORY"
+        scalar_value: {
+            uint32_t: 8192
+        }
+        enumerator: "OUT_USB_DEVICE"
+        scalar_value: {
+            uint32_t: 16384
+        }
+        enumerator: "OUT_REMOTE_SUBMIX"
+        scalar_value: {
+            uint32_t: 32768
+        }
+        enumerator: "OUT_TELEPHONY_TX"
+        scalar_value: {
+            uint32_t: 65536
+        }
+        enumerator: "OUT_LINE"
+        scalar_value: {
+            uint32_t: 131072
+        }
+        enumerator: "OUT_HDMI_ARC"
+        scalar_value: {
+            uint32_t: 262144
+        }
+        enumerator: "OUT_SPDIF"
+        scalar_value: {
+            uint32_t: 524288
+        }
+        enumerator: "OUT_FM"
+        scalar_value: {
+            uint32_t: 1048576
+        }
+        enumerator: "OUT_AUX_LINE"
+        scalar_value: {
+            uint32_t: 2097152
+        }
+        enumerator: "OUT_SPEAKER_SAFE"
+        scalar_value: {
+            uint32_t: 4194304
+        }
+        enumerator: "OUT_IP"
+        scalar_value: {
+            uint32_t: 8388608
+        }
+        enumerator: "OUT_BUS"
+        scalar_value: {
+            uint32_t: 16777216
+        }
+        enumerator: "OUT_DEFAULT"
+        scalar_value: {
+            uint32_t: 1073741824
+        }
+        enumerator: "OUT_ALL"
+        scalar_value: {
+            uint32_t: 1107296255
+        }
+        enumerator: "OUT_ALL_A2DP"
+        scalar_value: {
+            uint32_t: 896
+        }
+        enumerator: "OUT_ALL_SCO"
+        scalar_value: {
+            uint32_t: 112
+        }
+        enumerator: "OUT_ALL_USB"
+        scalar_value: {
+            uint32_t: 24576
+        }
+        enumerator: "IN_COMMUNICATION"
+        scalar_value: {
+            uint32_t: 2147483649
+        }
+        enumerator: "IN_AMBIENT"
+        scalar_value: {
+            uint32_t: 2147483650
+        }
+        enumerator: "IN_BUILTIN_MIC"
+        scalar_value: {
+            uint32_t: 2147483652
+        }
+        enumerator: "IN_BLUETOOTH_SCO_HEADSET"
+        scalar_value: {
+            uint32_t: 2147483656
+        }
+        enumerator: "IN_WIRED_HEADSET"
+        scalar_value: {
+            uint32_t: 2147483664
+        }
+        enumerator: "IN_AUX_DIGITAL"
+        scalar_value: {
+            uint32_t: 2147483680
+        }
+        enumerator: "IN_HDMI"
+        scalar_value: {
+            uint32_t: 2147483680
+        }
+        enumerator: "IN_VOICE_CALL"
+        scalar_value: {
+            uint32_t: 2147483712
+        }
+        enumerator: "IN_TELEPHONY_RX"
+        scalar_value: {
+            uint32_t: 2147483712
+        }
+        enumerator: "IN_BACK_MIC"
+        scalar_value: {
+            uint32_t: 2147483776
+        }
+        enumerator: "IN_REMOTE_SUBMIX"
+        scalar_value: {
+            uint32_t: 2147483904
+        }
+        enumerator: "IN_ANLG_DOCK_HEADSET"
+        scalar_value: {
+            uint32_t: 2147484160
+        }
+        enumerator: "IN_DGTL_DOCK_HEADSET"
+        scalar_value: {
+            uint32_t: 2147484672
+        }
+        enumerator: "IN_USB_ACCESSORY"
+        scalar_value: {
+            uint32_t: 2147485696
+        }
+        enumerator: "IN_USB_DEVICE"
+        scalar_value: {
+            uint32_t: 2147487744
+        }
+        enumerator: "IN_FM_TUNER"
+        scalar_value: {
+            uint32_t: 2147491840
+        }
+        enumerator: "IN_TV_TUNER"
+        scalar_value: {
+            uint32_t: 2147500032
+        }
+        enumerator: "IN_LINE"
+        scalar_value: {
+            uint32_t: 2147516416
+        }
+        enumerator: "IN_SPDIF"
+        scalar_value: {
+            uint32_t: 2147549184
+        }
+        enumerator: "IN_BLUETOOTH_A2DP"
+        scalar_value: {
+            uint32_t: 2147614720
+        }
+        enumerator: "IN_LOOPBACK"
+        scalar_value: {
+            uint32_t: 2147745792
+        }
+        enumerator: "IN_IP"
+        scalar_value: {
+            uint32_t: 2148007936
+        }
+        enumerator: "IN_BUS"
+        scalar_value: {
+            uint32_t: 2148532224
+        }
+        enumerator: "IN_DEFAULT"
+        scalar_value: {
+            uint32_t: 3221225472
+        }
+        enumerator: "IN_ALL"
+        scalar_value: {
+            uint32_t: 3223322623
+        }
+        enumerator: "IN_ALL_SCO"
+        scalar_value: {
+            uint32_t: 2147483656
+        }
+        enumerator: "IN_ALL_USB"
+        scalar_value: {
+            uint32_t: 2147489792
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioOutputFlag"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "DIRECT"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "PRIMARY"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "FAST"
+        scalar_value: {
+            int32_t: 4
+        }
+        enumerator: "DEEP_BUFFER"
+        scalar_value: {
+            int32_t: 8
+        }
+        enumerator: "COMPRESS_OFFLOAD"
+        scalar_value: {
+            int32_t: 16
+        }
+        enumerator: "NON_BLOCKING"
+        scalar_value: {
+            int32_t: 32
+        }
+        enumerator: "HW_AV_SYNC"
+        scalar_value: {
+            int32_t: 64
+        }
+        enumerator: "TTS"
+        scalar_value: {
+            int32_t: 128
+        }
+        enumerator: "RAW"
+        scalar_value: {
+            int32_t: 256
+        }
+        enumerator: "SYNC"
+        scalar_value: {
+            int32_t: 512
+        }
+        enumerator: "IEC958_NONAUDIO"
+        scalar_value: {
+            int32_t: 1024
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioInputFlag"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "FAST"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "HW_HOTWORD"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "RAW"
+        scalar_value: {
+            int32_t: 4
+        }
+        enumerator: "SYNC"
+        scalar_value: {
+            int32_t: 8
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioOffloadInfo"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "sampleRateHz"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "channelMask"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioChannelMask"
+    }
+    struct_value: {
+        name: "format"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioFormat"
+    }
+    struct_value: {
+        name: "streamType"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioStreamType"
+    }
+    struct_value: {
+        name: "bitRatePerSecond"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "durationMicroseconds"
+        type: TYPE_SCALAR
+        scalar_type: "int64_t"
+    }
+    struct_value: {
+        name: "hasVideo"
+        type: TYPE_SCALAR
+        scalar_type: "bool_t"
+    }
+    struct_value: {
+        name: "isStreaming"
+        type: TYPE_SCALAR
+        scalar_type: "bool_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioConfig"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "sampleRateHz"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "channelMask"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioChannelMask"
+    }
+    struct_value: {
+        name: "format"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioFormat"
+    }
+    struct_value: {
+        name: "offloadInfo"
+        type: TYPE_STRUCT
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioOffloadInfo"
+    }
+    struct_value: {
+        name: "frameCount"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioGainMode"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "JOINT"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "CHANNELS"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "RAMP"
+        scalar_value: {
+            uint32_t: 4
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioGain"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "mode"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioGainMode"
+    }
+    struct_value: {
+        name: "channelMask"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioChannelMask"
+    }
+    struct_value: {
+        name: "minValue"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "maxValue"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "defaultValue"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "stepValue"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "minRampMs"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "maxRampMs"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioGainConfig"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "index"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "mode"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioGainMode"
+    }
+    struct_value: {
+        name: "channelMask"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioChannelMask"
+    }
+    struct_value: {
+        name: "values"
+        type: TYPE_ARRAY
+        vector_value: {
+            vector_size: 32
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+    }
+    struct_value: {
+        name: "rampDurationMs"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortRole"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "SOURCE"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "SINK"
+        scalar_value: {
+            int32_t: 2
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortType"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "DEVICE"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "MIX"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "SESSION"
+        scalar_value: {
+            int32_t: 3
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortConfigDeviceExt"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "hwModule"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "type"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioDevice"
+    }
+    struct_value: {
+        name: "address"
+        type: TYPE_ARRAY
+        vector_value: {
+            vector_size: 32
+            type: TYPE_SCALAR
+            scalar_type: "uint8_t"
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortConfigSessionExt"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "session"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortConfigMask"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "SAMPLE_RATE"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "CHANNEL_MASK"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "FORMAT"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "GAIN"
+        scalar_value: {
+            uint32_t: 8
+        }
+        enumerator: "ALL"
+        scalar_value: {
+            uint32_t: 15
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortConfig"
+    type: TYPE_STRUCT
+    sub_struct: {
+        name: "::android::hardware::audio::common::V2_0::AudioPortConfig::Ext"
+        type: TYPE_UNION
+        sub_union: {
+            name: "::android::hardware::audio::common::V2_0::AudioPortConfig::Ext::AudioPortConfigMixExt"
+            type: TYPE_STRUCT
+            sub_struct: {
+                name: "::android::hardware::audio::common::V2_0::AudioPortConfig::Ext::AudioPortConfigMixExt::UseCase"
+                type: TYPE_UNION
+                union_value: {
+                    name: "stream"
+                    type: TYPE_ENUM
+                    predefined_type: "::android::hardware::audio::common::V2_0::AudioStreamType"
+                }
+                union_value: {
+                    name: "source"
+                    type: TYPE_ENUM
+                    predefined_type: "::android::hardware::audio::common::V2_0::AudioSource"
+                }
+            }
+            struct_value: {
+                name: "hwModule"
+                type: TYPE_SCALAR
+                scalar_type: "int32_t"
+            }
+            struct_value: {
+                name: "ioHandle"
+                type: TYPE_SCALAR
+                scalar_type: "int32_t"
+            }
+        }
+        union_value: {
+            name: "device"
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortConfigDeviceExt"
+        }
+        union_value: {
+            name: "mix"
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortConfig::Ext::AudioPortConfigMixExt"
+        }
+        union_value: {
+            name: "session"
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortConfigSessionExt"
+        }
+    }
+    struct_value: {
+        name: "id"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "configMask"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioPortConfigMask"
+    }
+    struct_value: {
+        name: "sampleRateHz"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "channelMask"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioChannelMask"
+    }
+    struct_value: {
+        name: "format"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioFormat"
+    }
+    struct_value: {
+        name: "gain"
+        type: TYPE_STRUCT
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioGainConfig"
+    }
+    struct_value: {
+        name: "type"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioPortType"
+    }
+    struct_value: {
+        name: "role"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioPortRole"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortDeviceExt"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "hwModule"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "type"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioDevice"
+    }
+    struct_value: {
+        name: "address"
+        type: TYPE_ARRAY
+        vector_value: {
+            vector_size: 32
+            type: TYPE_SCALAR
+            scalar_type: "uint8_t"
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioMixLatencyClass"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "LOW"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "NORMAL"
+        scalar_value: {
+            int32_t: 1
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortMixExt"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "hwModule"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "ioHandle"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "latencyClass"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioMixLatencyClass"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPortSessionExt"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "session"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPort"
+    type: TYPE_STRUCT
+    sub_struct: {
+        name: "::android::hardware::audio::common::V2_0::AudioPort::Ext"
+        type: TYPE_UNION
+        union_value: {
+            name: "device"
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortDeviceExt"
+        }
+        union_value: {
+            name: "mix"
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortMixExt"
+        }
+        union_value: {
+            name: "session"
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortSessionExt"
+        }
+    }
+    struct_value: {
+        name: "id"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "role"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioPortRole"
+    }
+    struct_value: {
+        name: "name"
+        type: TYPE_STRING
+    }
+    struct_value: {
+        name: "sampleRates"
+        type: TYPE_VECTOR
+        vector_value: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+    struct_value: {
+        name: "channelMasks"
+        type: TYPE_VECTOR
+        vector_value: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioChannelMask"
+        }
+    }
+    struct_value: {
+        name: "formats"
+        type: TYPE_VECTOR
+        vector_value: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioFormat"
+        }
+    }
+    struct_value: {
+        name: "gains"
+        type: TYPE_VECTOR
+        vector_value: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioGain"
+        }
+    }
+    struct_value: {
+        name: "activeConfig"
+        type: TYPE_STRUCT
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioPortConfig"
+    }
+    struct_value: {
+        name: "type"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::audio::common::V2_0::AudioPortType"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::audio::common::V2_0::AudioPatch"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "id"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "sources"
+        type: TYPE_VECTOR
+        vector_value: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortConfig"
+        }
+    }
+    struct_value: {
+        name: "sinks"
+        type: TYPE_VECTOR
+        vector_value: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::audio::common::V2_0::AudioPortConfig"
+        }
+    }
+}
+
diff --git a/audio/effect/2.0/Android.bp b/audio/effect/2.0/Android.bp
new file mode 100644 (file)
index 0000000..78829be
--- /dev/null
@@ -0,0 +1,157 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.audio.effect@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.audio.effect@2.0",
+    srcs: [
+        "types.hal",
+        "IAcousticEchoCancelerEffect.hal",
+        "IAutomaticGainControlEffect.hal",
+        "IBassBoostEffect.hal",
+        "IDownmixEffect.hal",
+        "IEffect.hal",
+        "IEffectBufferProviderCallback.hal",
+        "IEffectsFactory.hal",
+        "IEnvironmentalReverbEffect.hal",
+        "IEqualizerEffect.hal",
+        "ILoudnessEnhancerEffect.hal",
+        "INoiseSuppressionEffect.hal",
+        "IPresetReverbEffect.hal",
+        "IVirtualizerEffect.hal",
+        "IVisualizerEffect.hal",
+    ],
+    out: [
+        "android/hardware/audio/effect/2.0/types.cpp",
+        "android/hardware/audio/effect/2.0/AcousticEchoCancelerEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/AutomaticGainControlEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/BassBoostEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/DownmixEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/EffectAll.cpp",
+        "android/hardware/audio/effect/2.0/EffectBufferProviderCallbackAll.cpp",
+        "android/hardware/audio/effect/2.0/EffectsFactoryAll.cpp",
+        "android/hardware/audio/effect/2.0/EnvironmentalReverbEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/EqualizerEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/LoudnessEnhancerEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/NoiseSuppressionEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/PresetReverbEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/VirtualizerEffectAll.cpp",
+        "android/hardware/audio/effect/2.0/VisualizerEffectAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.audio.effect@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.audio.effect@2.0",
+    srcs: [
+        "types.hal",
+        "IAcousticEchoCancelerEffect.hal",
+        "IAutomaticGainControlEffect.hal",
+        "IBassBoostEffect.hal",
+        "IDownmixEffect.hal",
+        "IEffect.hal",
+        "IEffectBufferProviderCallback.hal",
+        "IEffectsFactory.hal",
+        "IEnvironmentalReverbEffect.hal",
+        "IEqualizerEffect.hal",
+        "ILoudnessEnhancerEffect.hal",
+        "INoiseSuppressionEffect.hal",
+        "IPresetReverbEffect.hal",
+        "IVirtualizerEffect.hal",
+        "IVisualizerEffect.hal",
+    ],
+    out: [
+        "android/hardware/audio/effect/2.0/types.h",
+        "android/hardware/audio/effect/2.0/IAcousticEchoCancelerEffect.h",
+        "android/hardware/audio/effect/2.0/IHwAcousticEchoCancelerEffect.h",
+        "android/hardware/audio/effect/2.0/BnAcousticEchoCancelerEffect.h",
+        "android/hardware/audio/effect/2.0/BpAcousticEchoCancelerEffect.h",
+        "android/hardware/audio/effect/2.0/BsAcousticEchoCancelerEffect.h",
+        "android/hardware/audio/effect/2.0/IAutomaticGainControlEffect.h",
+        "android/hardware/audio/effect/2.0/IHwAutomaticGainControlEffect.h",
+        "android/hardware/audio/effect/2.0/BnAutomaticGainControlEffect.h",
+        "android/hardware/audio/effect/2.0/BpAutomaticGainControlEffect.h",
+        "android/hardware/audio/effect/2.0/BsAutomaticGainControlEffect.h",
+        "android/hardware/audio/effect/2.0/IBassBoostEffect.h",
+        "android/hardware/audio/effect/2.0/IHwBassBoostEffect.h",
+        "android/hardware/audio/effect/2.0/BnBassBoostEffect.h",
+        "android/hardware/audio/effect/2.0/BpBassBoostEffect.h",
+        "android/hardware/audio/effect/2.0/BsBassBoostEffect.h",
+        "android/hardware/audio/effect/2.0/IDownmixEffect.h",
+        "android/hardware/audio/effect/2.0/IHwDownmixEffect.h",
+        "android/hardware/audio/effect/2.0/BnDownmixEffect.h",
+        "android/hardware/audio/effect/2.0/BpDownmixEffect.h",
+        "android/hardware/audio/effect/2.0/BsDownmixEffect.h",
+        "android/hardware/audio/effect/2.0/IEffect.h",
+        "android/hardware/audio/effect/2.0/IHwEffect.h",
+        "android/hardware/audio/effect/2.0/BnEffect.h",
+        "android/hardware/audio/effect/2.0/BpEffect.h",
+        "android/hardware/audio/effect/2.0/BsEffect.h",
+        "android/hardware/audio/effect/2.0/IEffectBufferProviderCallback.h",
+        "android/hardware/audio/effect/2.0/IHwEffectBufferProviderCallback.h",
+        "android/hardware/audio/effect/2.0/BnEffectBufferProviderCallback.h",
+        "android/hardware/audio/effect/2.0/BpEffectBufferProviderCallback.h",
+        "android/hardware/audio/effect/2.0/BsEffectBufferProviderCallback.h",
+        "android/hardware/audio/effect/2.0/IEffectsFactory.h",
+        "android/hardware/audio/effect/2.0/IHwEffectsFactory.h",
+        "android/hardware/audio/effect/2.0/BnEffectsFactory.h",
+        "android/hardware/audio/effect/2.0/BpEffectsFactory.h",
+        "android/hardware/audio/effect/2.0/BsEffectsFactory.h",
+        "android/hardware/audio/effect/2.0/IEnvironmentalReverbEffect.h",
+        "android/hardware/audio/effect/2.0/IHwEnvironmentalReverbEffect.h",
+        "android/hardware/audio/effect/2.0/BnEnvironmentalReverbEffect.h",
+        "android/hardware/audio/effect/2.0/BpEnvironmentalReverbEffect.h",
+        "android/hardware/audio/effect/2.0/BsEnvironmentalReverbEffect.h",
+        "android/hardware/audio/effect/2.0/IEqualizerEffect.h",
+        "android/hardware/audio/effect/2.0/IHwEqualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BnEqualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BpEqualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BsEqualizerEffect.h",
+        "android/hardware/audio/effect/2.0/ILoudnessEnhancerEffect.h",
+        "android/hardware/audio/effect/2.0/IHwLoudnessEnhancerEffect.h",
+        "android/hardware/audio/effect/2.0/BnLoudnessEnhancerEffect.h",
+        "android/hardware/audio/effect/2.0/BpLoudnessEnhancerEffect.h",
+        "android/hardware/audio/effect/2.0/BsLoudnessEnhancerEffect.h",
+        "android/hardware/audio/effect/2.0/INoiseSuppressionEffect.h",
+        "android/hardware/audio/effect/2.0/IHwNoiseSuppressionEffect.h",
+        "android/hardware/audio/effect/2.0/BnNoiseSuppressionEffect.h",
+        "android/hardware/audio/effect/2.0/BpNoiseSuppressionEffect.h",
+        "android/hardware/audio/effect/2.0/BsNoiseSuppressionEffect.h",
+        "android/hardware/audio/effect/2.0/IPresetReverbEffect.h",
+        "android/hardware/audio/effect/2.0/IHwPresetReverbEffect.h",
+        "android/hardware/audio/effect/2.0/BnPresetReverbEffect.h",
+        "android/hardware/audio/effect/2.0/BpPresetReverbEffect.h",
+        "android/hardware/audio/effect/2.0/BsPresetReverbEffect.h",
+        "android/hardware/audio/effect/2.0/IVirtualizerEffect.h",
+        "android/hardware/audio/effect/2.0/IHwVirtualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BnVirtualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BpVirtualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BsVirtualizerEffect.h",
+        "android/hardware/audio/effect/2.0/IVisualizerEffect.h",
+        "android/hardware/audio/effect/2.0/IHwVisualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BnVisualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BpVisualizerEffect.h",
+        "android/hardware/audio/effect/2.0/BsVisualizerEffect.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.audio.effect@2.0",
+    generated_sources: ["android.hardware.audio.effect@2.0_genc++"],
+    generated_headers: ["android.hardware.audio.effect@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.audio.effect@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.audio.common@2.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.audio.common@2.0",
+    ],
+}
diff --git a/audio/effect/2.0/Android.mk b/audio/effect/2.0/Android.mk
new file mode 100644 (file)
index 0000000..a30de1c
--- /dev/null
@@ -0,0 +1,51 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.audio.effect@2.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/audio/effect/2.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/IAcousticEchoCancelerEffect.hal
+$(GEN): $(LOCAL_PATH)/IAutomaticGainControlEffect.hal
+$(GEN): $(LOCAL_PATH)/IBassBoostEffect.hal
+$(GEN): $(LOCAL_PATH)/IDownmixEffect.hal
+$(GEN): $(LOCAL_PATH)/IEffect.hal
+$(GEN): $(LOCAL_PATH)/IEffectBufferProviderCallback.hal
+$(GEN): $(LOCAL_PATH)/IEffectsFactory.hal
+$(GEN): $(LOCAL_PATH)/IEnvironmentalReverbEffect.hal
+$(GEN): $(LOCAL_PATH)/IEqualizerEffect.hal
+$(GEN): $(LOCAL_PATH)/ILoudnessEnhancerEffect.hal
+$(GEN): $(LOCAL_PATH)/INoiseSuppressionEffect.hal
+$(GEN): $(LOCAL_PATH)/IPresetReverbEffect.hal
+$(GEN): $(LOCAL_PATH)/IVirtualizerEffect.hal
+$(GEN): $(LOCAL_PATH)/IVisualizerEffect.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.audio.effect@2.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/audio/effect/2.0/IAcousticEchoCancelerEffect.hal b/audio/effect/2.0/IAcousticEchoCancelerEffect.hal
new file mode 100644 (file)
index 0000000..9e2e0c3
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IAcousticEchoCancelerEffect extends IEffect {
+    /*
+     * Sets echo delay value in milliseconds.
+     */
+    setEchoDelay(uint32_t echoDelayMs) generates (Result retval);
+
+    /*
+     * Gets echo delay value in milliseconds.
+     */
+    getEchoDelay() generates (Result retval, uint32_t echoDelayMs);
+};
diff --git a/audio/effect/2.0/IAutomaticGainControlEffect.hal b/audio/effect/2.0/IAutomaticGainControlEffect.hal
new file mode 100644 (file)
index 0000000..a02002d
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IAutomaticGainControlEffect extends IEffect {
+    /*
+     * Sets target level in millibels.
+     */
+    setTargetLevel(int16_t targetLevelMb) generates (Result retval);
+
+    /*
+     * Gets target level.
+     */
+    getTargetLevel() generates (Result retval, int16_t targetLevelMb);
+
+    /*
+     * Sets gain in the compression range in millibels.
+     */
+    setCompGain(int16_t compGainMb) generates (Result retval);
+
+    /*
+     * Gets gain in the compression range.
+     */
+    getCompGain() generates (Result retval, int16_t compGainMb);
+
+    /*
+     * Enables or disables limiter.
+     */
+    setLimiterEnabled(bool enabled) generates (Result retval);
+
+    /*
+     * Returns whether limiter is enabled.
+     */
+    isLimiterEnabled() generates (Result retval, bool enabled);
+
+    struct AllProperties {
+        int16_t targetLevelMb;
+        int16_t compGainMb;
+        bool limiterEnabled;
+    };
+
+    /*
+     * Sets all properties at once.
+     */
+    setAllProperties(AllProperties properties) generates (Result retval);
+
+    /*
+     * Gets all properties at once.
+     */
+    getAllProperties() generates (Result retval, AllProperties properties);
+};
diff --git a/audio/effect/2.0/IBassBoostEffect.hal b/audio/effect/2.0/IBassBoostEffect.hal
new file mode 100644 (file)
index 0000000..bcf7b7d
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IBassBoostEffect extends IEffect {
+    /*
+     * Returns whether setting bass boost strength is supported.
+     */
+    isStrengthSupported() generates (Result retval, bool strengthSupported);
+
+    enum StrengthRange : uint16_t {
+        MIN = 0,
+        MAX = 1000
+    };
+
+    /*
+     * Sets bass boost strength.
+     *
+     * @param strength strength of the effect. The valid range for strength
+     *                 strength is [0, 1000], where 0 per mille designates the
+     *                 mildest effect and 1000 per mille designates the
+     *                 strongest.
+     * @return retval operation completion status.
+     */
+    setStrength(uint16_t strength) generates (Result retval);
+
+    /*
+     * Gets virtualization strength.
+     */
+    getStrength() generates (Result retval, uint16_t strength);
+};
diff --git a/audio/effect/2.0/IDownmixEffect.hal b/audio/effect/2.0/IDownmixEffect.hal
new file mode 100644 (file)
index 0000000..817e14c
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IDownmixEffect extends IEffect {
+    enum Type {
+        STRIP, // throw away the extra channels
+        FOLD   // mix the extra channels with FL/FR
+    };
+
+    setType(Type preset) generates (Result retval);
+
+    getType() generates (Result retval, Type preset);
+};
diff --git a/audio/effect/2.0/IEffect.hal b/audio/effect/2.0/IEffect.hal
new file mode 100644 (file)
index 0000000..615a460
--- /dev/null
@@ -0,0 +1,409 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffectBufferProviderCallback;
+
+interface IEffect {
+    /*
+     * Initialize effect engine--all configurations return to default.
+     *
+     * @return retval operation completion status.
+     */
+    @entry
+    @callflow(next={"*"})
+    init() generates (Result retval);
+
+    /*
+     * Apply new audio parameters configurations for input and output buffers.
+     * The provider callbacks may be empty, but in this case the buffer
+     * must be provided in the EffectConfig structure.
+     *
+     * @param config configuration descriptor.
+     * @param inputBufferProvider optional buffer provider reference.
+     * @param outputBufferProvider optional buffer provider reference.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setConfig(EffectConfig config,
+            IEffectBufferProviderCallback inputBufferProvider,
+            IEffectBufferProviderCallback outputBufferProvider)
+            generates (Result retval);
+
+    /*
+     * Reset the effect engine. Keep configuration but resets state and buffer
+     * content.
+     *
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    reset() generates (Result retval);
+
+    /*
+     * Enable processing.
+     *
+     * @return retval operation completion status.
+     */
+    @callflow(next={"process"})
+    enable() generates (Result retval);
+
+    /*
+     * Disable processing.
+     *
+     * @return retval operation completion status.
+     */
+    @exit
+    disable() generates (Result retval);
+
+    /*
+     * Set the rendering device the audio output path is connected to.  The
+     * effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its
+     * descriptor to receive this command when the device changes.
+     *
+     * @param device output device specification.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setDevice(AudioDevice device) generates (Result retval);
+
+    /*
+     * Set and get volume. Used by audio framework to delegate volume control to
+     * effect engine.  The effect implementation must set EFFECT_FLAG_VOLUME_IND
+     * or EFFECT_FLAG_VOLUME_CTRL flag in its descriptor to receive this command
+     * before every call to 'process' function If EFFECT_FLAG_VOLUME_CTRL flag
+     * is set in the effect descriptor, the effect engine must return the volume
+     * that should be applied before the effect is processed. The overall volume
+     * (the volume actually applied by the effect engine multiplied by the
+     * returned value) should match the value indicated in the command.
+     *
+     * @param volumes vector containing volume for each channel defined in
+     *                EffectConfig for output buffer expressed in 8.24 fixed
+     *                point format.
+     * @return result updated volume values. It is OK to receive an empty vector
+     *                as a result in which case the effect framework has
+     *                delegated volume control to another effect.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setAndGetVolume(vec<uint32_t> volumes)
+            generates (Result retval, vec<uint32_t> result);
+
+    /*
+     * Set the audio mode. The effect implementation must set
+     * EFFECT_FLAG_AUDIO_MODE_IND flag in its descriptor to receive this command
+     * when the audio mode changes.
+     *
+     * @param mode desired audio mode.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setAudioMode(AudioMode mode) generates (Result retval);
+
+    /*
+     * Apply new audio parameters configurations for input and output buffers of
+     * reverse stream.  An example of reverse stream is the echo reference
+     * supplied to an Acoustic Echo Canceler.
+     *
+     * @param config configuration descriptor.
+     * @param inputBufferProvider optional buffer provider reference.
+     * @param outputBufferProvider optional buffer provider reference.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setConfigReverse(EffectConfig config,
+            IEffectBufferProviderCallback inputBufferProvider,
+            IEffectBufferProviderCallback outputBufferProvider)
+            generates (Result retval);
+
+    /*
+     * Set the capture device the audio input path is connected to. The effect
+     * implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to
+     * receive this command when the device changes.
+     *
+     * @param device input device specification.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setInputDevice(AudioDevice device) generates (Result retval);
+
+    /*
+     * Read audio parameters configurations for input and output buffers.
+     *
+     * @return retval operation completion status.
+     * @return config configuration descriptor.
+     */
+    @callflow(next={"*"})
+    getConfig() generates (Result retval, EffectConfig config);
+
+    /*
+     * Read audio parameters configurations for input and output buffers of
+     * reverse stream.
+     *
+     * @return retval operation completion status.
+     * @return config configuration descriptor.
+     */
+    @callflow(next={"*"})
+    getConfigReverse() generates (Result retval, EffectConfig config);
+
+    /*
+     * Queries for supported combinations of main and auxiliary channels
+     * (e.g. for a multi-microphone noise suppressor).
+     *
+     * @param maxConfigs maximum number of the combinations to return.
+     * @return retval absence of the feature support is indicated using
+     *                NOT_SUPPORTED code. RESULT_TOO_BIG is returned if
+     *                the number of supported combinations exceeds 'maxConfigs'.
+     * @return result list of configuration descriptors.
+     */
+    @callflow(next={"*"})
+    getSupportedAuxChannelsConfigs(uint32_t maxConfigs)
+            generates (Result retval, vec<EffectAuxChannelsConfig> result);
+
+    /*
+     * Retrieves the current configuration of main and auxiliary channels.
+     *
+     * @return retval absence of the feature support is indicated using
+     *                NOT_SUPPORTED code.
+     * @return result configuration descriptor.
+     */
+    @callflow(next={"*"})
+    getAuxChannelsConfig()
+            generates (Result retval, EffectAuxChannelsConfig result);
+
+    /*
+     * Sets the current configuration of main and auxiliary channels.
+     *
+     * @return retval operation completion status; absence of the feature
+     *                support is indicated using NOT_SUPPORTED code.
+     */
+    @callflow(next={"*"})
+    setAuxChannelsConfig(EffectAuxChannelsConfig config)
+            generates (Result retval);
+
+    /*
+     * Set the audio source the capture path is configured for (Camcorder, voice
+     * recognition...).
+     *
+     * @param source source descriptor.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setAudioSource(AudioSource source) generates (Result retval);
+
+    /*
+     * This command indicates if the playback thread the effect is attached to
+     * is offloaded or not, and updates the I/O handle of the playback thread
+     * the effect is attached to.
+     *
+     * @param param effect offload descriptor.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    offload(EffectOffloadParameter param) generates (Result retval);
+
+    /*
+     * Returns the effect descriptor.
+     *
+     * @return retval operation completion status.
+     * @return descriptor effect descriptor.
+     */
+    @callflow(next={"*"})
+    getDescriptor() generates (Result retval, EffectDescriptor descriptor);
+
+    /*
+     * Effect process function. Takes input samples as specified (count and
+     * location) in input buffer and returns processed samples as specified in
+     * output buffer. If the buffer descriptor is empty the function must use
+     * either the buffer or the buffer provider callback installed by the
+     * setConfig command.  The effect framework must call the 'process' function
+     * after the 'enable' command is received and until the 'disable' is
+     * received. When the engine receives the 'disable' command it should turn
+     * off the effect gracefully and when done indicate that it is OK to stop
+     * calling the 'process' function by returning the INVALID_STATE status.
+     *
+     * Output audio buffer must contain no more frames than the input audio
+     * buffer. Since the effect may transform input channels into a different
+     * amount of channels, the caller provides the output frame size.
+     *
+     * @param inBuffer input audio buffer.
+     * @param outFrameSize output frame size in bytes.
+     * @return retval operation completion status.
+     * @return outBuffer output audio buffer.
+     */
+    // TODO(mnaganov): replace with FMQ version.
+    @callflow(next={"*"})
+    process(AudioBuffer inBuffer, uint32_t outFrameSize)
+            generates (Result retval, AudioBuffer outBuffer);
+
+    /*
+     * Process reverse stream function. This function is used to pass a
+     * reference stream to the effect engine. If the engine does not need a
+     * reference stream, this function MUST return NOT_SUPPORTED. For example,
+     * this function would typically implemented by an Echo Canceler.
+     *
+     * Output audio buffer must contain no more frames than the input audio
+     * buffer. Since the effect may transform input channels into a different
+     * amount of channels, the caller provides the output frame size.
+     *
+     * @param inBuffer input audio buffer.
+     * @param outFrameSize output frame size in bytes.
+     * @return retval operation completion status.
+     * @return outBuffer output audio buffer.
+     */
+    // TODO(mnaganov): replace with FMQ version.
+    @callflow(next={"*"})
+    processReverse(AudioBuffer inBuffer, uint32_t outFrameSize)
+            generates (Result retval, AudioBuffer outBuffer);
+
+    /*
+     * Execute a vendor specific command on the effect. The command code
+     * and data, as well as result data are not interpreted by Android
+     * Framework and are passed as-is between the application and the effect.
+     *
+     * The effect must use standard POSIX.1-2001 error codes for the operation
+     * completion status.
+     *
+     * Use this method only if the effect is provided by a third party, and
+     * there is no interface defined for it. This method only works for effects
+     * implemented in software.
+     *
+     * @param commandId the ID of the command.
+     * @param data command data.
+     * @param resultMaxSize maximum size in bytes of the result; can be 0.
+     * @return status command completion status.
+     * @return result result data.
+     */
+    command(uint32_t commandId, vec<uint8_t> data, uint32_t resultMaxSize)
+            generates (int32_t status, vec<uint8_t> result);
+
+    /*
+     * Set a vendor-specific parameter and apply it immediately. The parameter
+     * code and data are not interpreted by Android Framework and are passed
+     * as-is between the application and the effect.
+     *
+     * The effect must use INVALID_ARGUMENTS return code if the parameter ID is
+     * unknown or if provided parameter data is invalid. If the effect does not
+     * support setting vendor-specific parameters, it must return NOT_SUPPORTED.
+     *
+     * Use this method only if the effect is provided by a third party, and
+     * there is no interface defined for it. This method only works for effects
+     * implemented in software.
+     *
+     * @param parameter identifying data of the parameter.
+     * @param value the value of the parameter.
+     * @return retval operation completion status.
+     */
+    @callflow(next={"*"})
+    setParameter(vec<uint8_t> parameter, vec<uint8_t> value)
+            generates (Result retval);
+
+    /*
+     * Get a vendor-specific parameter value. The parameter code and returned
+     * data are not interpreted by Android Framework and are passed as-is
+     * between the application and the effect.
+     *
+     * The effect must use INVALID_ARGUMENTS return code if the parameter ID is
+     * unknown. If the effect does not support setting vendor-specific
+     * parameters, it must return NOT_SUPPORTED.
+     *
+     * Use this method only if the effect is provided by a third party, and
+     * there is no interface defined for it.  This method only works for effects
+     * implemented in software.
+     *
+     * @param parameter identifying data of the parameter.
+     * @param valueMaxSize maximum size in bytes of the value.
+     * @return retval operation completion status.
+     * @return result the value of the parameter.
+     */
+    @callflow(next={"*"})
+    getParameter(vec<uint8_t> parameter, uint32_t valueMaxSize)
+            generates (Result retval, vec<uint8_t> value);
+
+    /*
+     * Get supported configs for a vendor-specific feature. The configs returned
+     * are not interpreted by Android Framework and are passed as-is between the
+     * application and the effect.
+     *
+     * The effect must use INVALID_ARGUMENTS return code if the feature ID is
+     * unknown. If the effect does not support getting vendor-specific feature
+     * configs, it must return NOT_SUPPORTED. If the feature is supported but
+     * the total number of supported configurations exceeds the maximum number
+     * indicated by the caller, the method must return RESULT_TOO_BIG.
+     *
+     * Use this method only if the effect is provided by a third party, and
+     * there is no interface defined for it.  This method only works for effects
+     * implemented in software.
+     *
+     * @param featureId feature identifier.
+     * @param maxConfigs maximum number of configs to return.
+     * @param configSize size of each config in bytes.
+     * @return retval operation completion status.
+     * @return configsCount number of configs returned.
+     * @return configsData data for all the configs returned.
+     */
+    @callflow(next={"*"})
+    getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize) generates (
+                    Result retval,
+                    uint32_t configsCount,
+                    vec<uint8_t> configsData);
+
+    /*
+     * Get the current config for a vendor-specific feature. The config returned
+     * is not interpreted by Android Framework and is passed as-is between the
+     * application and the effect.
+     *
+     * The effect must use INVALID_ARGUMENTS return code if the feature ID is
+     * unknown. If the effect does not support getting vendor-specific
+     * feature configs, it must return NOT_SUPPORTED.
+     *
+     * Use this method only if the effect is provided by a third party, and
+     * there is no interface defined for it.  This method only works for effects
+     * implemented in software.
+     *
+     * @param featureId feature identifier.
+     * @param configSize size of the config in bytes.
+     * @return retval operation completion status.
+     * @return configData config data.
+     */
+    @callflow(next={"*"})
+    getCurrentConfigForFeature(uint32_t featureId, uint32_t configSize)
+            generates (Result retval, vec<uint8_t> configData);
+
+    /*
+     * Set the current config for a vendor-specific feature. The config data
+     * is not interpreted by Android Framework and is passed as-is between the
+     * application and the effect.
+     *
+     * The effect must use INVALID_ARGUMENTS return code if the feature ID is
+     * unknown. If the effect does not support getting vendor-specific
+     * feature configs, it must return NOT_SUPPORTED.
+     *
+     * Use this method only if the effect is provided by a third party, and
+     * there is no interface defined for it.  This method only works for effects
+     * implemented in software.
+     *
+     * @param featureId feature identifier.
+     * @param configData config data.
+     * @return retval operation completion status.
+     */
+    setCurrentConfigForFeature(uint32_t featureId, vec<uint8_t> configData)
+            generates (Result retval);
+};
diff --git a/audio/effect/2.0/IEffectBufferProviderCallback.hal b/audio/effect/2.0/IEffectBufferProviderCallback.hal
new file mode 100644 (file)
index 0000000..545e2e5
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+/*
+ * This callback interface contains functions that can be used by the effect
+ * engine 'process' function to exchange input and output audio buffers.
+ */
+interface IEffectBufferProviderCallback {
+    /*
+     * Called to retrieve a buffer where data should read from by 'process'
+     * function.
+     *
+     * @return buffer audio buffer for processing
+     */
+    // TODO(mnaganov): replace with FMQ version.
+    getBuffer() generates (AudioBuffer buffer);
+
+    /*
+     * Called to provide a buffer with the data written by 'process' function.
+     *
+     * @param buffer audio buffer for processing
+     */
+    // TODO(mnaganov): replace with FMQ version.
+    putBuffer(AudioBuffer buffer);
+};
diff --git a/audio/effect/2.0/IEffectsFactory.hal b/audio/effect/2.0/IEffectsFactory.hal
new file mode 100644 (file)
index 0000000..c82b4a2
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IEffectsFactory {
+    /*
+     * Returns descriptors of different effects in all loaded libraries.
+     *
+     * @return retval operation completion status.
+     * @return result list of effect descriptors.
+     */
+    getAllDescriptors() generates(Result retval, vec<EffectDescriptor> result);
+
+    /*
+     * Returns a descriptor of a particular effect.
+     *
+     * @return retval operation completion status.
+     * @return result effect descriptor.
+     */
+    getDescriptor(Uuid uid) generates(Result retval, EffectDescriptor result);
+
+    /*
+     * Creates an effect engine of the specified type.  To release the effect
+     * engine, it is necessary to release references to the returned effect
+     * object.
+     *
+     * @param uid effect uuid.
+     * @param session audio session to which this effect instance will be
+     *                attached.  All effects created with the same session ID
+     *                are connected in series and process the same signal
+     *                stream.
+     * @param ioHandle identifies the output or input stream this effect is
+     *                 directed to in audio HAL.
+     * @return retval operation completion status.
+     * @return result the interface for the created effect.
+     * @return effectId the unique ID of the effect to be used with
+     *                  IStream::addEffect and IStream::removeEffect methods.
+     */
+    createEffect(Uuid uid, AudioSession session, AudioIoHandle ioHandle)
+        generates (Result retval, IEffect result, uint64_t effectId);
+
+    /*
+     * Dumps information about effects into the provided file descriptor.
+     * This is used for the dumpsys facility.
+     *
+     * @param fd dump file descriptor.
+     */
+    debugDump(handle fd);
+};
diff --git a/audio/effect/2.0/IEnvironmentalReverbEffect.hal b/audio/effect/2.0/IEnvironmentalReverbEffect.hal
new file mode 100644 (file)
index 0000000..d9b1ee6
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IEnvironmentalReverbEffect extends IEffect {
+    /*
+     * Sets whether the effect should be bypassed.
+     */
+    setBypass(bool bypass) generates (Result retval);
+
+    /*
+     * Gets whether the effect should be bypassed.
+     */
+    getBypass() generates (Result retval, bool bypass);
+
+    enum ParamRange : int16_t {
+        ROOM_LEVEL_MIN = -6000,
+        ROOM_LEVEL_MAX = 0,
+        ROOM_HF_LEVEL_MIN = -4000,
+        ROOM_HF_LEVEL_MAX = 0,
+        DECAY_TIME_MIN = 100,
+        DECAY_TIME_MAX = 20000,
+        DECAY_HF_RATIO_MIN = 100,
+        DECAY_HF_RATIO_MAX = 1000,
+        REFLECTIONS_LEVEL_MIN = -6000,
+        REFLECTIONS_LEVEL_MAX = 0,
+        REFLECTIONS_DELAY_MIN = 0,
+        REFLECTIONS_DELAY_MAX = 65,
+        REVERB_LEVEL_MIN = -6000,
+        REVERB_LEVEL_MAX = 0,
+        REVERB_DELAY_MIN = 0,
+        REVERB_DELAY_MAX = 65,
+        DIFFUSION_MIN = 0,
+        DIFFUSION_MAX = 1000,
+        DENSITY_MIN = 0,
+        DENSITY_MAX = 1000
+    };
+
+    /*
+     * Sets the room level.
+     */
+    setRoomLevel(int16_t roomLevel) generates (Result retval);
+
+    /*
+     * Gets the room level.
+     */
+    getRoomLevel() generates (Result retval, int16_t roomLevel);
+
+    /*
+     * Sets the room high frequences level.
+     */
+    setRoomHfLevel(int16_t roomHfLevel) generates (Result retval);
+
+    /*
+     * Gets the room high frequences level.
+     */
+    getRoomHfLevel() generates (Result retval, int16_t roomHfLevel);
+
+    /*
+     * Sets the room decay time.
+     */
+    setDecayTime(uint32_t decayTime) generates (Result retval);
+
+    /*
+     * Gets the room decay time.
+     */
+    getDecayTime() generates (Result retval, uint32_t decayTime);
+
+    /*
+     * Sets the ratio of high frequences decay.
+     */
+    setDecayHfRatio(int16_t decayHfRatio) generates (Result retval);
+
+    /*
+     * Gets the ratio of high frequences decay.
+     */
+    getDecayHfRatio() generates (Result retval, int16_t decayHfRatio);
+
+    /*
+     * Sets the level of reflections in the room.
+     */
+    setReflectionsLevel(int16_t reflectionsLevel) generates (Result retval);
+
+    /*
+     * Gets the level of reflections in the room.
+     */
+    getReflectionsLevel() generates (Result retval, int16_t reflectionsLevel);
+
+    /*
+     * Sets the reflections delay in the room.
+     */
+    setReflectionsDelay(uint32_t reflectionsDelay) generates (Result retval);
+
+    /*
+     * Gets the reflections delay in the room.
+     */
+    getReflectionsDelay() generates (Result retval, uint32_t reflectionsDelay);
+
+    /*
+     * Sets the reverb level of the room.
+     */
+    setReverbLevel(int16_t reverbLevel) generates (Result retval);
+
+    /*
+     * Gets the reverb level of the room.
+     */
+    getReverbLevel() generates (Result retval, int16_t reverbLevel);
+
+    /*
+     * Sets the reverb delay of the room.
+     */
+    setReverbDelay(uint32_t reverDelay) generates (Result retval);
+
+    /*
+     * Gets the reverb delay of the room.
+     */
+    getReverbDelay() generates (Result retval, uint32_t reverbDelay);
+
+    /*
+     * Sets room diffusion.
+     */
+    setDiffusion(int16_t diffusion) generates (Result retval);
+
+    /*
+     * Gets room diffusion.
+     */
+    getDiffusion() generates (Result retval, int16_t diffusion);
+
+    /*
+     * Sets room wall density.
+     */
+    setDensity(int16_t density) generates (Result retval);
+
+    /*
+     * Gets room wall density.
+     */
+    getDensity() generates (Result retval, int16_t density);
+
+    struct AllProperties {
+        int16_t  roomLevel;         // in millibels,    range -6000 to 0
+        int16_t  roomHfLevel;       // in millibels,    range -4000 to 0
+        uint32_t decayTime;         // in milliseconds, range 100 to 20000
+        int16_t  decayHfRatio;      // in permilles,    range 100 to 1000
+        int16_t  reflectionsLevel;  // in millibels,    range -6000 to 0
+        uint32_t reflectionsDelay;  // in milliseconds, range 0 to 65
+        int16_t  reverbLevel;       // in millibels,    range -6000 to 0
+        uint32_t reverbDelay;       // in milliseconds, range 0 to 65
+        int16_t  diffusion;         // in permilles,    range 0 to 1000
+        int16_t  density;           // in permilles,    range 0 to 1000
+    };
+
+    /*
+     * Sets all properties at once.
+     */
+    setAllProperties(AllProperties properties) generates (Result retval);
+
+    /*
+     * Gets all properties at once.
+     */
+    getAllProperties() generates (Result retval, AllProperties properties);
+};
diff --git a/audio/effect/2.0/IEqualizerEffect.hal b/audio/effect/2.0/IEqualizerEffect.hal
new file mode 100644 (file)
index 0000000..afcc4b6
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IEqualizerEffect extends IEffect {
+    /*
+     * Gets the number of frequency bands that the equalizer supports.
+     */
+    getNumBands() generates (Result retval, uint16_t numBands);
+
+    /*
+     * Returns the minimum and maximum band levels supported.
+     */
+    getLevelRange()
+            generates (Result retval, uint16_t minLevel, uint16_t maxLevel);
+
+    /*
+     * Sets the gain for the given equalizer band.
+     */
+    setBandLevel(uint16_t band, uint16_t level) generates (Result retval);
+
+    /*
+     * Gets the gain for the given equalizer band.
+     */
+    getBandLevel(uint16_t band) generates (Result retval, uint16_t level);
+
+    /*
+     * Gets the center frequency of the given band.
+     */
+    getBandCenterFrequency(uint16_t band)
+            generates (Result retval, uint32_t centerFreq);
+
+    /*
+     * Gets the frequency range of the given frequency band.
+     */
+    getBandFrequencyRange(uint16_t band)
+            generates (Result retval, uint32_t minFreqHz, uint32_t maxFreqHz);
+
+    /*
+     * Gets the band that has the most effect on the given frequency.
+     */
+    getBandForFrequency(uint32_t freq) generates (Result retval, uint16_t band);
+
+    /*
+     * Gets the names of all presets the equalizer supports.
+     */
+    getPresetNames() generates (Result retval, vec<string> names);
+
+    /*
+     * Sets the current preset using the index of the preset in the names
+     * vector returned via 'getPresetNames'.
+     */
+    setCurrentPreset(uint16_t preset) generates (Result retval);
+
+    /*
+     * Gets the current preset.
+     */
+    getCurrentPreset() generates (Result retval, uint16_t preset);
+
+    struct AllProperties {
+        uint16_t curPreset;
+        vec<uint16_t> bandLevels;
+    };
+
+    /*
+     * Sets all properties at once.
+     */
+    setAllProperties(AllProperties properties) generates (Result retval);
+
+    /*
+     * Gets all properties at once.
+     */
+    getAllProperties() generates (Result retval, AllProperties properties);
+};
diff --git a/audio/effect/2.0/ILoudnessEnhancerEffect.hal b/audio/effect/2.0/ILoudnessEnhancerEffect.hal
new file mode 100644 (file)
index 0000000..3e1ee4e
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface ILoudnessEnhancerEffect extends IEffect {
+    /*
+     * Sets target gain expressed in millibels.
+     */
+    setTargetGain(int32_t targetGainMb) generates (Result retval);
+
+    /*
+     * Gets target gain expressed in millibels.
+     */
+    getTargetGain() generates (Result retval, int32_t targetGainMb);
+};
diff --git a/audio/effect/2.0/INoiseSuppressionEffect.hal b/audio/effect/2.0/INoiseSuppressionEffect.hal
new file mode 100644 (file)
index 0000000..58e439f
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface INoiseSuppressionEffect extends IEffect {
+    enum Level {
+        LOW,
+        MEDIUM,
+        HIGH
+    };
+
+    /*
+     * Sets suppression level.
+     */
+    setSuppressionLevel(Level level) generates (Result retval);
+
+    /*
+     * Gets suppression level.
+     */
+    getSuppressionLevel() generates (Result retval, Level level);
+
+    enum Type {
+        SINGLE_CHANNEL,
+        MULTI_CHANNEL
+    };
+
+    /*
+     * Set suppression type.
+     */
+    setSuppressionType(Type type) generates (Result retval);
+
+    /*
+     * Get suppression type.
+     */
+    getSuppressionType() generates (Result retval, Type type);
+
+    struct AllProperties {
+        Level level;
+        Type type;
+    };
+
+    /*
+     * Sets all properties at once.
+     */
+    setAllProperties(AllProperties properties) generates (Result retval);
+
+    /*
+     * Gets all properties at once.
+     */
+    getAllProperties() generates (Result retval, AllProperties properties);
+};
diff --git a/audio/effect/2.0/IPresetReverbEffect.hal b/audio/effect/2.0/IPresetReverbEffect.hal
new file mode 100644 (file)
index 0000000..58dfd40
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IPresetReverbEffect extends IEffect {
+    enum Preset {
+        NONE,        // no reverb or reflections
+        SMALLROOM,   // a small room less than five meters in length
+        MEDIUMROOM,  // a medium room with a length of ten meters or less
+        LARGEROOM,   // a large-sized room suitable for live performances
+        MEDIUMHALL,  // a medium-sized hall
+        LARGEHALL,   // a large-sized hall suitable for a full orchestra
+        PLATE,       // synthesis of the traditional plate reverb
+        LAST = PLATE
+    };
+
+    setPreset(Preset preset) generates (Result retval);
+
+    getPreset() generates (Result retval, Preset preset);
+};
diff --git a/audio/effect/2.0/IVirtualizerEffect.hal b/audio/effect/2.0/IVirtualizerEffect.hal
new file mode 100644 (file)
index 0000000..2b7116c
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IVirtualizerEffect extends IEffect {
+    /*
+     * Returns whether setting virtualization strength is supported.
+     */
+    isStrengthSupported() generates (bool strengthSupported);
+
+    enum StrengthRange : uint16_t {
+        MIN = 0,
+        MAX = 1000
+    };
+
+    /*
+     * Sets virtualization strength.
+     *
+     * @param strength strength of the effect. The valid range for strength
+     *                 strength is [0, 1000], where 0 per mille designates the
+     *                 mildest effect and 1000 per mille designates the
+     *                 strongest.
+     * @return retval operation completion status.
+     */
+    setStrength(uint16_t strength) generates (Result retval);
+
+    /*
+     * Gets virtualization strength.
+     */
+    getStrength() generates (Result retval, uint16_t strength);
+
+    struct SpeakerAngle {
+        AudioChannelMask mask; // speaker channel mask (1 bit set).
+        // all angles are expressed in degrees and
+        // are relative to the listener.
+        int16_t azimuth; // 0 is the direction the listener faces
+                         // 180 is behind the listener
+                         // -90 is to their left
+        int16_t elevation; // 0 is the horizontal plane
+                           // +90 is above the listener, -90 is below
+    };
+    /*
+     * Retrieves virtual speaker angles for the given channel mask on the
+     * specified device.
+     */
+    getVirtualSpeakerAngles(AudioChannelMask mask, AudioDevice device)
+            generates (Result retval, vec<SpeakerAngle> speakerAngles);
+
+    /*
+     * Forces the virtualizer effect for the given output device.
+     */
+    forceVirtualizationMode(AudioDevice device) generates (Result retval);
+
+    /*
+     * Returns audio device reflecting the current virtualization mode,
+     * AUDIO_DEVICE_NONE when not virtualizing.
+     */
+    getVirtualizationMode() generates (Result retval, AudioDevice device);
+};
diff --git a/audio/effect/2.0/IVisualizerEffect.hal b/audio/effect/2.0/IVisualizerEffect.hal
new file mode 100644 (file)
index 0000000..70dabf9
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+import IEffect;
+
+interface IVisualizerEffect extends IEffect {
+    enum CaptureSizeRange {
+        MAX = 1024,  // maximum capture size in samples
+        MIN = 128    // minimum capture size in samples
+    };
+
+    /*
+     * Sets the number PCM samples in the capture.
+     */
+    setCaptureSize(uint16_t captureSize) generates (Result retval);
+
+    /*
+     * Gets the number PCM samples in the capture.
+     */
+    getCaptureSize() generates (Result retval, uint16_t captureSize);
+
+    enum ScalingMode {
+        // Keep in sync with SCALING_MODE_... in
+        // frameworks/base/media/java/android/media/audiofx/Visualizer.java
+        NORMALIZED = 0,
+        AS_PLAYED = 1
+    };
+
+    /*
+     * Specifies the way the captured data is scaled.
+     */
+    setScalingMode(ScalingMode scalingMode) generates (Result retval);
+
+    /*
+     * Retrieves the way the captured data is scaled.
+     */
+    getScalingMode() generates (Result retval, ScalingMode scalingMode);
+
+    /*
+     * Informs the visualizer about the downstream latency.
+     */
+    setLatency(uint32_t latencyMs) generates (Result retval);
+
+    /*
+     * Gets the downstream latency.
+     */
+    getLatency() generates (Result retval, uint32_t latencyMs);
+
+    enum MeasurementMode {
+        // Keep in sync with MEASUREMENT_MODE_... in
+        // frameworks/base/media/java/android/media/audiofx/Visualizer.java
+        NONE = 0x0,
+        PEAK_RMS = 0x1
+    };
+
+    /*
+     * Specifies which measurements are to be made.
+     */
+    setMeasurementMode(MeasurementMode measurementMode)
+            generates (Result retval);
+
+    /*
+     * Retrieves which measurements are to be made.
+     */
+    getMeasurementMode() generates (
+            Result retval, MeasurementMode measurementMode);
+
+    /*
+     * Retrieves the latest PCM snapshot captured by the visualizer engine.  The
+     * number of samples to capture is specified by 'setCaptureSize' parameter.
+     *
+     * @return retval operation completion status.
+     * @return samples samples in 8 bit unsigned format (0 = 0x80)
+     */
+    capture() generates (Result retval, vec<uint8_t> samples);
+
+    struct Measurement {
+        MeasurementMode mode;    // discriminator
+        union Values {
+            struct PeakAndRms {
+                int32_t peakMb;  // millibels
+                int32_t rmsMb;   // millibels
+            } peakAndRms;
+        } value;
+    };
+    /*
+     * Retrieves the lastest measurements. The measurements to be made
+     * are specified by 'setMeasurementMode' parameter.
+     *
+     * @return retval operation completion status.
+     * @return result measurement.
+     */
+    measure() generates (Result retval, Measurement result);
+};
diff --git a/audio/effect/2.0/default/AcousticEchoCancelerEffect.cpp b/audio/effect/2.0/default/AcousticEchoCancelerEffect.cpp
new file mode 100644 (file)
index 0000000..c2f50f9
--- /dev/null
@@ -0,0 +1,184 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "AEC_Effect_HAL"
+#include <system/audio_effects/effect_aec.h>
+#include <utils/Log.h>
+
+#include "AcousticEchoCancelerEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+AcousticEchoCancelerEffect::AcousticEchoCancelerEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+AcousticEchoCancelerEffect::~AcousticEchoCancelerEffect() {}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> AcousticEchoCancelerEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> AcousticEchoCancelerEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> AcousticEchoCancelerEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> AcousticEchoCancelerEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> AcousticEchoCancelerEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> AcousticEchoCancelerEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> AcousticEchoCancelerEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> AcousticEchoCancelerEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> AcousticEchoCancelerEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> AcousticEchoCancelerEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> AcousticEchoCancelerEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> AcousticEchoCancelerEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> AcousticEchoCancelerEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> AcousticEchoCancelerEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> AcousticEchoCancelerEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> AcousticEchoCancelerEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> AcousticEchoCancelerEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> AcousticEchoCancelerEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> AcousticEchoCancelerEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IAcousticEchoCancelerEffect follow.
+Return<Result> AcousticEchoCancelerEffect::setEchoDelay(uint32_t echoDelayMs)  {
+    return mEffect->setParam(AEC_PARAM_ECHO_DELAY, echoDelayMs);
+}
+
+Return<void> AcousticEchoCancelerEffect::getEchoDelay(getEchoDelay_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(AEC_PARAM_ECHO_DELAY, _hidl_cb);
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/AcousticEchoCancelerEffect.h b/audio/effect/2.0/default/AcousticEchoCancelerEffect.h
new file mode 100644 (file)
index 0000000..cebc2d4
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_AcousticEchoCancelerEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_AcousticEchoCancelerEffect_H_
+
+#include <android/hardware/audio/effect/2.0/IAcousticEchoCancelerEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::effect::V2_0::IAcousticEchoCancelerEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct AcousticEchoCancelerEffect : public IAcousticEchoCancelerEffect {
+    explicit AcousticEchoCancelerEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IAcousticEchoCancelerEffect follow.
+    Return<Result> setEchoDelay(uint32_t echoDelayMs)  override;
+    Return<void> getEchoDelay(getEchoDelay_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~AcousticEchoCancelerEffect();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_AcousticEchoCancelerEffect_H_
diff --git a/audio/effect/2.0/default/Android.mk b/audio/effect/2.0/default/Android.mk
new file mode 100644 (file)
index 0000000..50c4bd6
--- /dev/null
@@ -0,0 +1,32 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.audio.effect@2.0-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    AcousticEchoCancelerEffect.cpp \
+    AutomaticGainControlEffect.cpp \
+    BassBoostEffect.cpp \
+    Conversions.cpp \
+    DownmixEffect.cpp \
+    Effect.cpp \
+    EffectsFactory.cpp \
+    EnvironmentalReverbEffect.cpp \
+    EqualizerEffect.cpp \
+    LoudnessEnhancerEffect.cpp \
+    NoiseSuppressionEffect.cpp \
+    PresetReverbEffect.cpp \
+    VirtualizerEffect.cpp \
+    VisualizerEffect.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    libhidl \
+    libhwbinder \
+    libutils \
+    libeffects \
+    liblog \
+    android.hardware.audio.common@2.0 \
+    android.hardware.audio.common@2.0-util \
+    android.hardware.audio.effect@2.0 \
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/audio/effect/2.0/default/AutomaticGainControlEffect.cpp b/audio/effect/2.0/default/AutomaticGainControlEffect.cpp
new file mode 100644 (file)
index 0000000..34cbe97
--- /dev/null
@@ -0,0 +1,230 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "AGC_Effect_HAL"
+#include <utils/Log.h>
+
+#include "AutomaticGainControlEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+AutomaticGainControlEffect::AutomaticGainControlEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+AutomaticGainControlEffect::~AutomaticGainControlEffect() {}
+
+void AutomaticGainControlEffect::propertiesFromHal(
+        const t_agc_settings& halProperties,
+        IAutomaticGainControlEffect::AllProperties* properties) {
+    properties->targetLevelMb = halProperties.targetLevel;
+    properties->compGainMb = halProperties.compGain;
+    properties->limiterEnabled = halProperties.limiterEnabled;
+}
+
+void AutomaticGainControlEffect::propertiesToHal(
+        const IAutomaticGainControlEffect::AllProperties& properties,
+        t_agc_settings* halProperties) {
+    halProperties->targetLevel = properties.targetLevelMb;
+    halProperties->compGain = properties.compGainMb;
+    halProperties->limiterEnabled = properties.limiterEnabled;
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> AutomaticGainControlEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> AutomaticGainControlEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> AutomaticGainControlEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> AutomaticGainControlEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> AutomaticGainControlEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> AutomaticGainControlEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> AutomaticGainControlEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> AutomaticGainControlEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> AutomaticGainControlEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> AutomaticGainControlEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> AutomaticGainControlEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> AutomaticGainControlEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> AutomaticGainControlEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> AutomaticGainControlEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> AutomaticGainControlEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> AutomaticGainControlEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> AutomaticGainControlEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> AutomaticGainControlEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> AutomaticGainControlEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IAutomaticGainControlEffect follow.
+Return<Result> AutomaticGainControlEffect::setTargetLevel(int16_t targetLevelMb)  {
+    return mEffect->setParam(AGC_PARAM_TARGET_LEVEL, targetLevelMb);
+}
+
+Return<void> AutomaticGainControlEffect::getTargetLevel(getTargetLevel_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(AGC_PARAM_TARGET_LEVEL, _hidl_cb);
+}
+
+Return<Result> AutomaticGainControlEffect::setCompGain(int16_t compGainMb)  {
+    return mEffect->setParam(AGC_PARAM_COMP_GAIN, compGainMb);
+}
+
+Return<void> AutomaticGainControlEffect::getCompGain(getCompGain_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(AGC_PARAM_COMP_GAIN, _hidl_cb);
+}
+
+Return<Result> AutomaticGainControlEffect::setLimiterEnabled(bool enabled)  {
+    return mEffect->setParam(AGC_PARAM_LIMITER_ENA, enabled);
+}
+
+Return<void> AutomaticGainControlEffect::isLimiterEnabled(isLimiterEnabled_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(AGC_PARAM_LIMITER_ENA, _hidl_cb);
+}
+
+Return<Result> AutomaticGainControlEffect::setAllProperties(const IAutomaticGainControlEffect::AllProperties& properties)  {
+    t_agc_settings halProperties;
+    propertiesToHal(properties, &halProperties);
+    return mEffect->setParam(AGC_PARAM_PROPERTIES, halProperties);
+}
+
+Return<void> AutomaticGainControlEffect::getAllProperties(getAllProperties_cb _hidl_cb)  {
+    t_agc_settings halProperties;
+    Result retval = mEffect->getParam(AGC_PARAM_PROPERTIES, halProperties);
+    AllProperties properties;
+    propertiesFromHal(halProperties, &properties);
+    _hidl_cb(retval, properties);
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/AutomaticGainControlEffect.h b/audio/effect/2.0/default/AutomaticGainControlEffect.h
new file mode 100644 (file)
index 0000000..f4b228c
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_AutomaticGainControlEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_AutomaticGainControlEffect_H_
+
+#include <system/audio_effects/effect_agc.h>
+
+#include <android/hardware/audio/effect/2.0/IAutomaticGainControlEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::effect::V2_0::IAutomaticGainControlEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct AutomaticGainControlEffect : public IAutomaticGainControlEffect {
+    explicit AutomaticGainControlEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IAutomaticGainControlEffect follow.
+    Return<Result> setTargetLevel(int16_t targetLevelMb)  override;
+    Return<void> getTargetLevel(getTargetLevel_cb _hidl_cb)  override;
+    Return<Result> setCompGain(int16_t compGainMb)  override;
+    Return<void> getCompGain(getCompGain_cb _hidl_cb)  override;
+    Return<Result> setLimiterEnabled(bool enabled)  override;
+    Return<void> isLimiterEnabled(isLimiterEnabled_cb _hidl_cb)  override;
+    Return<Result> setAllProperties(
+            const IAutomaticGainControlEffect::AllProperties& properties)  override;
+    Return<void> getAllProperties(getAllProperties_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~AutomaticGainControlEffect();
+
+    void propertiesFromHal(
+            const t_agc_settings& halProperties,
+            IAutomaticGainControlEffect::AllProperties* properties);
+    void propertiesToHal(
+            const IAutomaticGainControlEffect::AllProperties& properties,
+            t_agc_settings* halProperties);
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_AutomaticGainControlEffect_H_
diff --git a/audio/effect/2.0/default/BassBoostEffect.cpp b/audio/effect/2.0/default/BassBoostEffect.cpp
new file mode 100644 (file)
index 0000000..1b12f76
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "BassBoost_HAL"
+#include <system/audio_effects/effect_bassboost.h>
+#include <utils/Log.h>
+
+#include "BassBoostEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+BassBoostEffect::BassBoostEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+BassBoostEffect::~BassBoostEffect() {}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> BassBoostEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> BassBoostEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> BassBoostEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> BassBoostEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> BassBoostEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> BassBoostEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> BassBoostEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> BassBoostEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> BassBoostEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> BassBoostEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> BassBoostEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> BassBoostEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> BassBoostEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> BassBoostEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> BassBoostEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> BassBoostEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> BassBoostEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> BassBoostEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> BassBoostEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> BassBoostEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> BassBoostEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> BassBoostEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> BassBoostEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> BassBoostEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> BassBoostEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> BassBoostEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IBassBoostEffect follow.
+Return<void> BassBoostEffect::isStrengthSupported(isStrengthSupported_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(BASSBOOST_PARAM_STRENGTH_SUPPORTED, _hidl_cb);
+}
+
+Return<Result> BassBoostEffect::setStrength(uint16_t strength)  {
+    return mEffect->setParam(BASSBOOST_PARAM_STRENGTH, strength);
+}
+
+Return<void> BassBoostEffect::getStrength(getStrength_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(BASSBOOST_PARAM_STRENGTH, _hidl_cb);
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/BassBoostEffect.h b/audio/effect/2.0/default/BassBoostEffect.h
new file mode 100644 (file)
index 0000000..23377e1
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_BassBoostEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_BassBoostEffect_H_
+
+#include <android/hardware/audio/effect/2.0/IBassBoostEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::effect::V2_0::IBassBoostEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct BassBoostEffect : public IBassBoostEffect {
+    explicit BassBoostEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IBassBoostEffect follow.
+    Return<void> isStrengthSupported(isStrengthSupported_cb _hidl_cb)  override;
+    Return<Result> setStrength(uint16_t strength)  override;
+    Return<void> getStrength(getStrength_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~BassBoostEffect();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_BassBoostEffect_H_
diff --git a/audio/effect/2.0/default/Conversions.cpp b/audio/effect/2.0/default/Conversions.cpp
new file mode 100644 (file)
index 0000000..ef2374c
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+
+#include <memory.h>
+#include <stdio.h>
+
+#include "Conversions.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+void effectDescriptorFromHal(
+        const effect_descriptor_t& halDescriptor, EffectDescriptor* descriptor) {
+    uuidFromHal(halDescriptor.type, &descriptor->type);
+    uuidFromHal(halDescriptor.uuid, &descriptor->uuid);
+    descriptor->flags = EffectFlags(halDescriptor.flags);
+    descriptor->cpuLoad = halDescriptor.cpuLoad;
+    descriptor->memoryUsage = halDescriptor.memoryUsage;
+    memcpy(descriptor->name.data(), halDescriptor.name, descriptor->name.size());
+    memcpy(descriptor->implementor.data(),
+            halDescriptor.implementor, descriptor->implementor.size());
+}
+
+void uuidFromHal(const effect_uuid_t& halUuid, Uuid* uuid) {
+    uuid->timeLow = halUuid.timeLow;
+    uuid->timeMid = halUuid.timeMid;
+    uuid->versionAndTimeHigh = halUuid.timeHiAndVersion;
+    uuid->variantAndClockSeqHigh = halUuid.clockSeq;
+    memcpy(uuid->node.data(), halUuid.node, uuid->node.size());
+}
+
+void uuidToHal(const Uuid& uuid, effect_uuid_t* halUuid) {
+    halUuid->timeLow = uuid.timeLow;
+    halUuid->timeMid = uuid.timeMid;
+    halUuid->timeHiAndVersion = uuid.versionAndTimeHigh;
+    halUuid->clockSeq = uuid.variantAndClockSeqHigh;
+    memcpy(halUuid->node, uuid.node.data(), uuid.node.size());
+}
+
+std::string uuidToString(const effect_uuid_t& halUuid) {
+    char str[64];
+    snprintf(str, sizeof(str), "%08x-%04x-%04x-%04x-%02x%02x%02x%02x%02x%02x",
+            halUuid.timeLow,
+            halUuid.timeMid,
+            halUuid.timeHiAndVersion,
+            halUuid.clockSeq,
+            halUuid.node[0],
+            halUuid.node[1],
+            halUuid.node[2],
+            halUuid.node[3],
+            halUuid.node[4],
+            halUuid.node[5]);
+    return str;
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/Conversions.h b/audio/effect/2.0/default/Conversions.h
new file mode 100644 (file)
index 0000000..5348ae6
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_audio_effect_V2_0_Conversions_H_
+#define android_hardware_audio_effect_V2_0_Conversions_H_
+
+#include <string>
+
+#include <android/hardware/audio/effect/2.0/types.h>
+#include <system/audio_effect.h>
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::Uuid;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+
+void effectDescriptorFromHal(
+        const effect_descriptor_t& halDescriptor, EffectDescriptor* descriptor);
+void uuidFromHal(const effect_uuid_t& halUuid, Uuid* uuid);
+void uuidToHal(const Uuid& uuid, effect_uuid_t* halUuid);
+std::string uuidToString(const effect_uuid_t& halUuid);
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // android_hardware_audio_effect_V2_0_Conversions_H_
diff --git a/audio/effect/2.0/default/DownmixEffect.cpp b/audio/effect/2.0/default/DownmixEffect.cpp
new file mode 100644 (file)
index 0000000..4c0a0bf
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "Downmix_HAL"
+#include <system/audio_effects/effect_downmix.h>
+#include <utils/Log.h>
+
+#include "DownmixEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+DownmixEffect::DownmixEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+DownmixEffect::~DownmixEffect() {}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> DownmixEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> DownmixEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> DownmixEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> DownmixEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> DownmixEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> DownmixEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> DownmixEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> DownmixEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> DownmixEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> DownmixEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> DownmixEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> DownmixEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> DownmixEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> DownmixEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> DownmixEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> DownmixEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> DownmixEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> DownmixEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> DownmixEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> DownmixEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> DownmixEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> DownmixEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> DownmixEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> DownmixEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> DownmixEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> DownmixEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IDownmixEffect follow.
+Return<Result> DownmixEffect::setType(IDownmixEffect::Type preset)  {
+    return mEffect->setParam(DOWNMIX_PARAM_TYPE, static_cast<downmix_type_t>(preset));
+}
+
+Return<void> DownmixEffect::getType(getType_cb _hidl_cb)  {
+    downmix_type_t halPreset = DOWNMIX_TYPE_INVALID;
+    Result retval = mEffect->getParam(DOWNMIX_PARAM_TYPE, halPreset);
+    _hidl_cb(retval, Type(halPreset));
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/DownmixEffect.h b/audio/effect/2.0/default/DownmixEffect.h
new file mode 100644 (file)
index 0000000..5ed4ffd
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_DownmixEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_DownmixEffect_H_
+
+#include <android/hardware/audio/effect/2.0/IDownmixEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::effect::V2_0::IDownmixEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct DownmixEffect : public IDownmixEffect {
+    explicit DownmixEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IDownmixEffect follow.
+    Return<Result> setType(IDownmixEffect::Type preset)  override;
+    Return<void> getType(getType_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~DownmixEffect();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_DownmixEffect_H_
diff --git a/audio/effect/2.0/default/Effect.cpp b/audio/effect/2.0/default/Effect.cpp
new file mode 100644 (file)
index 0000000..82d0292
--- /dev/null
@@ -0,0 +1,615 @@
+/*
+ * 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.
+ */
+
+#include <memory>
+#include <memory.h>
+
+#define LOG_TAG "EffectHAL"
+#include <media/EffectsFactoryApi.h>
+#include <utils/Log.h>
+
+#include "Conversions.h"
+#include "Effect.h"
+#include "EffectMap.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioChannelMask;
+using ::android::hardware::audio::common::V2_0::AudioFormat;
+
+// static
+const char *Effect::sContextResultOfCommand = "returned status";
+const char *Effect::sContextCallToCommand = "error";
+const char *Effect::sContextCallFunction = sContextCallToCommand;
+
+Effect::Effect(effect_handle_t handle) : mHandle(handle) {
+}
+
+Effect::~Effect() {
+    int status = EffectRelease(mHandle);
+    ALOGW_IF(status, "Error releasing effect %p: %s", mHandle, strerror(-status));
+    EffectMap::getInstance().remove(mHandle);
+    mHandle = 0;
+}
+
+// static
+template<typename T> size_t Effect::alignedSizeIn(size_t s) {
+    return (s + sizeof(T) - 1) / sizeof(T);
+}
+
+// static
+template<typename T> void Effect::hidlVecToHal(
+        const hidl_vec<T>& vec, uint32_t* halDataSize, void** halData) {
+    *halDataSize = static_cast<T>(vec.size() * sizeof(T));
+    *halData = static_cast<void*>(const_cast<T*>(&vec[0]));
+}
+
+// static
+void Effect::effectAuxChannelsConfigFromHal(
+        const channel_config_t& halConfig, EffectAuxChannelsConfig* config) {
+    config->mainChannels = AudioChannelMask(halConfig.main_channels);
+    config->auxChannels = AudioChannelMask(halConfig.aux_channels);
+}
+
+// static
+void Effect::effectAuxChannelsConfigToHal(
+        const EffectAuxChannelsConfig& config, channel_config_t* halConfig) {
+    halConfig->main_channels = static_cast<audio_channel_mask_t>(config.mainChannels);
+    halConfig->aux_channels = static_cast<audio_channel_mask_t>(config.auxChannels);
+}
+
+// static
+void Effect::effectBufferConfigFromHal(
+        const buffer_config_t& halConfig, EffectBufferConfig* config) {
+    // TODO(mnaganov): Use FMQ instead of AudioBuffer.
+    (void)halConfig.buffer.frameCount;
+    (void)halConfig.buffer.raw;
+    config->samplingRateHz = halConfig.samplingRate;
+    config->channels = AudioChannelMask(halConfig.channels);
+    config->format = AudioFormat(halConfig.format);
+    config->accessMode = EffectBufferAccess(halConfig.accessMode);
+    config->mask = EffectConfigParameters(halConfig.mask);
+}
+
+// static
+void Effect::effectBufferConfigToHal(const EffectBufferConfig& config, buffer_config_t* halConfig) {
+    // TODO(mnaganov): Use FMQ instead of AudioBuffer.
+    halConfig->buffer.frameCount = 0;
+    halConfig->buffer.raw = NULL;
+    halConfig->samplingRate = config.samplingRateHz;
+    halConfig->channels = static_cast<uint32_t>(config.channels);
+    // TODO(mnaganov): As the calling code does not use BP for now, implement later.
+    halConfig->bufferProvider.cookie = NULL;
+    halConfig->bufferProvider.getBuffer = NULL;
+    halConfig->bufferProvider.releaseBuffer = NULL;
+    halConfig->format = static_cast<uint8_t>(config.format);
+    halConfig->accessMode = static_cast<uint8_t>(config.accessMode);
+    halConfig->mask = static_cast<uint8_t>(config.mask);
+}
+
+// static
+void Effect::effectConfigFromHal(const effect_config_t& halConfig, EffectConfig* config) {
+    effectBufferConfigFromHal(halConfig.inputCfg, &config->inputCfg);
+    effectBufferConfigFromHal(halConfig.outputCfg, &config->outputCfg);
+}
+
+// static
+void Effect::effectConfigToHal(const EffectConfig& config, effect_config_t* halConfig) {
+    effectBufferConfigToHal(config.inputCfg, &halConfig->inputCfg);
+    effectBufferConfigToHal(config.outputCfg, &halConfig->outputCfg);
+}
+
+// static
+void Effect::effectOffloadParamToHal(
+        const EffectOffloadParameter& offload, effect_offload_param_t* halOffload) {
+    halOffload->isOffload = offload.isOffload;
+    halOffload->ioHandle = offload.ioHandle;
+}
+
+// static
+std::vector<uint8_t> Effect::parameterToHal(
+        uint32_t paramSize,
+        const void* paramData,
+        uint32_t valueSize,
+        const void** valueData) {
+    size_t valueOffsetFromData = alignedSizeIn<uint32_t>(paramSize) * sizeof(uint32_t);
+    size_t halParamBufferSize = sizeof(effect_param_t) + valueOffsetFromData + valueSize;
+    std::vector<uint8_t> halParamBuffer(halParamBufferSize, 0);
+    effect_param_t *halParam = reinterpret_cast<effect_param_t*>(&halParamBuffer[0]);
+    halParam->psize = paramSize;
+    halParam->vsize = valueSize;
+    memcpy(halParam->data, paramData, paramSize);
+    if (valueData) {
+        if (*valueData) {
+            // Value data is provided.
+            memcpy(halParam->data + valueOffsetFromData, *valueData, valueSize);
+        } else {
+            // The caller needs the pointer to the value data location.
+            *valueData = halParam->data + valueOffsetFromData;
+        }
+    }
+    return halParamBuffer;
+}
+
+Result Effect::analyzeCommandStatus(const char* commandName, const char* context, status_t status) {
+    return analyzeStatus("command", commandName, context, status);
+}
+
+Result Effect::analyzeStatus(
+        const char* funcName,
+        const char* subFuncName,
+        const char* contextDescription,
+        status_t status) {
+    if (status != OK) {
+        ALOGW("Effect %p %s %s %s: %s",
+                mHandle, funcName, subFuncName, contextDescription, strerror(-status));
+    }
+    switch (status) {
+        case OK: return Result::OK;
+        case -EINVAL: return Result::INVALID_ARGUMENTS;
+        case -ENODATA: return Result::INVALID_STATE;
+        case -ENODEV: return Result::NOT_INITIALIZED;
+        case -ENOMEM: return Result::RESULT_TOO_BIG;
+        case -ENOSYS: return Result::NOT_SUPPORTED;
+        default: return Result::INVALID_STATE;
+    }
+}
+
+void Effect::getConfigImpl(int commandCode, const char* commandName, GetConfigCallback cb) {
+    uint32_t halResultSize = sizeof(effect_config_t);
+    effect_config_t halConfig;
+    status_t status = (*mHandle)->command(
+            mHandle, commandCode, 0, NULL, &halResultSize, &halConfig);
+    EffectConfig config;
+    if (status == OK) {
+        effectConfigFromHal(halConfig, &config);
+    }
+    cb(analyzeCommandStatus(commandName, sContextCallToCommand, status), config);
+}
+
+Result Effect::getCurrentConfigImpl(
+        uint32_t featureId, uint32_t configSize, GetCurrentConfigSuccessCallback onSuccess) {
+    uint32_t halCmd = featureId;
+    uint32_t halResult[alignedSizeIn<uint32_t>(sizeof(uint32_t) + configSize)];
+    memset(halResult, 0, sizeof(halResult));
+    uint32_t halResultSize = 0;
+    return sendCommandReturningStatusAndData(
+            EFFECT_CMD_GET_FEATURE_CONFIG, "GET_FEATURE_CONFIG",
+            sizeof(uint32_t), &halCmd,
+            &halResultSize, halResult,
+            sizeof(uint32_t),
+            [&]{ onSuccess(&halResult[1]); });
+}
+
+Result Effect::getParameterImpl(
+        uint32_t paramSize,
+        const void* paramData,
+        uint32_t valueSize,
+        GetParameterSuccessCallback onSuccess) {
+    // As it is unknown what method HAL uses for copying the provided parameter data,
+    // it is safer to make sure that input and output buffers do not overlap.
+    std::vector<uint8_t> halCmdBuffer =
+            parameterToHal(paramSize, paramData, valueSize, nullptr);
+    const void *valueData = nullptr;
+    std::vector<uint8_t> halParamBuffer =
+            parameterToHal(paramSize, paramData, valueSize, &valueData);
+    uint32_t halParamBufferSize = halParamBuffer.size();
+
+    return sendCommandReturningStatusAndData(
+            EFFECT_CMD_GET_PARAM, "GET_PARAM",
+            halCmdBuffer.size(), &halCmdBuffer[0],
+            &halParamBufferSize, &halParamBuffer[0],
+            sizeof(effect_param_t),
+            [&]{
+                effect_param_t *halParam = reinterpret_cast<effect_param_t*>(&halParamBuffer[0]);
+                onSuccess(halParam->vsize, valueData);
+            });
+}
+
+Result Effect::getSupportedConfigsImpl(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        GetSupportedConfigsSuccessCallback onSuccess) {
+    uint32_t halCmd[2] = { featureId, maxConfigs };
+    uint32_t halResultSize = 2 * sizeof(uint32_t) + maxConfigs * sizeof(configSize);
+    uint8_t halResult[halResultSize];
+    memset(&halResult[0], 0, halResultSize);
+    return sendCommandReturningStatusAndData(
+            EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS, "GET_FEATURE_SUPPORTED_CONFIGS",
+            sizeof(halCmd), halCmd,
+            &halResultSize, &halResult[0],
+            2 * sizeof(uint32_t),
+            [&]{
+                uint32_t *halResult32 = reinterpret_cast<uint32_t*>(&halResult[0]);
+                uint32_t supportedConfigs = *(++halResult32); // skip status field
+                if (supportedConfigs > maxConfigs) supportedConfigs = maxConfigs;
+                onSuccess(supportedConfigs, ++halResult32);
+            });
+}
+
+void Effect::processImpl(
+        ProcessFunction process,
+        const char* funcName,
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        ProcessCallback cb) {
+    audio_buffer_t halInBuffer;
+    halInBuffer.frameCount = inBuffer.frameCount;
+    halInBuffer.u8 = const_cast<uint8_t*>(&inBuffer.data[0]);
+    audio_buffer_t halOutBuffer;
+    halOutBuffer.frameCount = halInBuffer.frameCount;
+    // TODO(mnaganov): Consider stashing the buffer to avoid reallocating it every time.
+    std::unique_ptr<uint8_t[]> halOutBufferData(
+            new uint8_t[halOutBuffer.frameCount * outFrameSize]);
+    halOutBuffer.u8 = &halOutBufferData[0];
+    status_t status = process(mHandle, &halInBuffer, &halOutBuffer);
+    Result retval = analyzeStatus(funcName, "", sContextCallFunction, status);
+    AudioBuffer outBuffer;
+    if (status == OK) {
+        outBuffer.frameCount = halOutBuffer.frameCount;
+        outBuffer.data.setToExternal(halOutBuffer.u8, halOutBuffer.frameCount * outFrameSize);
+    } else {
+        outBuffer.frameCount = 0;
+    }
+    cb(retval, outBuffer);
+}
+
+Result Effect::sendCommand(int commandCode, const char* commandName) {
+    return sendCommand(commandCode, commandName, 0, NULL);
+}
+
+Result Effect::sendCommand(
+        int commandCode, const char* commandName, uint32_t size, void* data) {
+    status_t status = (*mHandle)->command(mHandle, commandCode, size, data, 0, NULL);
+    return analyzeCommandStatus(commandName, sContextCallToCommand, status);
+}
+
+Result Effect::sendCommandReturningData(
+        int commandCode, const char* commandName,
+        uint32_t* replySize, void* replyData) {
+    return sendCommandReturningData(commandCode, commandName, 0, NULL, replySize, replyData);
+}
+
+Result Effect::sendCommandReturningData(
+        int commandCode, const char* commandName,
+        uint32_t size, void* data,
+        uint32_t* replySize, void* replyData) {
+    uint32_t expectedReplySize = *replySize;
+    status_t status = (*mHandle)->command(mHandle, commandCode, size, data, replySize, replyData);
+    if (status == OK && *replySize != expectedReplySize) {
+        status = -ENODATA;
+    }
+    return analyzeCommandStatus(commandName, sContextCallToCommand, status);
+}
+
+Result Effect::sendCommandReturningStatus(int commandCode, const char* commandName) {
+    return sendCommandReturningStatus(commandCode, commandName, 0, NULL);
+}
+
+Result Effect::sendCommandReturningStatus(
+        int commandCode, const char* commandName, uint32_t size, void* data) {
+    uint32_t replyCmdStatus;
+    uint32_t replySize = sizeof(uint32_t);
+    return sendCommandReturningStatusAndData(
+            commandCode, commandName, size, data, &replySize, &replyCmdStatus, replySize, []{});
+}
+
+Result Effect::sendCommandReturningStatusAndData(
+        int commandCode, const char* commandName,
+        uint32_t size, void* data,
+        uint32_t* replySize, void* replyData,
+        uint32_t minReplySize,
+        CommandSuccessCallback onSuccess) {
+    status_t status =
+            (*mHandle)->command(mHandle, commandCode, size, data, replySize, replyData);
+    Result retval;
+    if (status == OK && minReplySize >= sizeof(uint32_t) && *replySize >= minReplySize) {
+        uint32_t commandStatus = *reinterpret_cast<uint32_t*>(replyData);
+        retval = analyzeCommandStatus(commandName, sContextResultOfCommand, commandStatus);
+        if (commandStatus == OK) {
+            onSuccess();
+        }
+    } else {
+        retval = analyzeCommandStatus(commandName, sContextCallToCommand, status);
+    }
+    return retval;
+}
+
+Result Effect::setConfigImpl(
+        int commandCode, const char* commandName,
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    effect_config_t halConfig;
+    effectConfigToHal(config, &halConfig);
+    if (inputBufferProvider != 0) {
+        LOG_FATAL("Using input buffer provider is not supported");
+    }
+    if (outputBufferProvider != 0) {
+        LOG_FATAL("Using output buffer provider is not supported");
+    }
+    return sendCommandReturningStatus(
+            commandCode, commandName, sizeof(effect_config_t), &halConfig);
+}
+
+
+Result Effect::setParameterImpl(
+        uint32_t paramSize, const void* paramData, uint32_t valueSize, const void* valueData) {
+    std::vector<uint8_t> halParamBuffer = parameterToHal(
+            paramSize, paramData, valueSize, &valueData);
+    return sendCommandReturningStatus(
+            EFFECT_CMD_SET_PARAM, "SET_PARAM", halParamBuffer.size(), &halParamBuffer[0]);
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> Effect::init()  {
+    return sendCommandReturningStatus(EFFECT_CMD_INIT, "INIT");
+}
+
+Return<Result> Effect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider)  {
+    return setConfigImpl(
+            EFFECT_CMD_SET_CONFIG, "SET_CONFIG", config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> Effect::reset()  {
+    return sendCommand(EFFECT_CMD_RESET, "RESET");
+}
+
+Return<Result> Effect::enable()  {
+    return sendCommandReturningStatus(EFFECT_CMD_ENABLE, "ENABLE");
+}
+
+Return<Result> Effect::disable()  {
+    return sendCommandReturningStatus(EFFECT_CMD_DISABLE, "DISABLE");
+}
+
+Return<Result> Effect::setDevice(AudioDevice device)  {
+    uint32_t halDevice = static_cast<uint32_t>(device);
+    return sendCommand(EFFECT_CMD_SET_DEVICE, "SET_DEVICE", sizeof(uint32_t), &halDevice);
+}
+
+Return<void> Effect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  {
+    uint32_t halDataSize;
+    void *halData;
+    hidlVecToHal(volumes, &halDataSize, &halData);
+    uint32_t halResultSize = halDataSize;
+    uint32_t halResult[volumes.size()];
+    Result retval = sendCommandReturningData(
+            EFFECT_CMD_SET_VOLUME, "SET_VOLUME", halDataSize, halData, &halResultSize, halResult);
+    hidl_vec<uint32_t> result;
+    if (retval == Result::OK) {
+        result.setToExternal(&halResult[0], halResultSize);
+    }
+    _hidl_cb(retval, result);
+    return Void();
+}
+
+Return<Result> Effect::setAudioMode(AudioMode mode)  {
+    uint32_t halMode = static_cast<uint32_t>(mode);
+    return sendCommand(
+            EFFECT_CMD_SET_AUDIO_MODE, "SET_AUDIO_MODE", sizeof(uint32_t), &halMode);
+}
+
+Return<Result> Effect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider)  {
+    return setConfigImpl(EFFECT_CMD_SET_CONFIG_REVERSE, "SET_CONFIG_REVERSE",
+            config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> Effect::setInputDevice(AudioDevice device)  {
+    uint32_t halDevice = static_cast<uint32_t>(device);
+    return sendCommand(
+            EFFECT_CMD_SET_INPUT_DEVICE, "SET_INPUT_DEVICE", sizeof(uint32_t), &halDevice);
+}
+
+Return<void> Effect::getConfig(getConfig_cb _hidl_cb)  {
+    getConfigImpl(EFFECT_CMD_GET_CONFIG, "GET_CONFIG", _hidl_cb);
+    return Void();
+}
+
+Return<void> Effect::getConfigReverse(getConfigReverse_cb _hidl_cb)  {
+    getConfigImpl(EFFECT_CMD_GET_CONFIG_REVERSE, "GET_CONFIG_REVERSE", _hidl_cb);
+    return Void();
+}
+
+Return<void> Effect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  {
+    hidl_vec<EffectAuxChannelsConfig> result;
+    Result retval = getSupportedConfigsImpl(
+            EFFECT_FEATURE_AUX_CHANNELS,
+            maxConfigs,
+            sizeof(channel_config_t),
+            [&] (uint32_t supportedConfigs, void* configsData) {
+                result.resize(supportedConfigs);
+                channel_config_t *config = reinterpret_cast<channel_config_t*>(configsData);
+                for (size_t i = 0; i < result.size(); ++i) {
+                    effectAuxChannelsConfigFromHal(*config++, &result[i]);
+                }
+            });
+    _hidl_cb(retval, result);
+    return Void();
+}
+
+Return<void> Effect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  {
+    uint32_t halCmd = EFFECT_FEATURE_AUX_CHANNELS;
+    uint32_t halResult[alignedSizeIn<uint32_t>(sizeof(uint32_t) + sizeof(channel_config_t))];
+    memset(halResult, 0, sizeof(halResult));
+    uint32_t halResultSize = 0;
+    EffectAuxChannelsConfig result;
+    Result retval = getCurrentConfigImpl(
+            EFFECT_FEATURE_AUX_CHANNELS,
+            sizeof(channel_config_t),
+            [&] (void* configData) {
+                effectAuxChannelsConfigFromHal(
+                        *reinterpret_cast<channel_config_t*>(configData), &result);
+            });
+    _hidl_cb(retval, result);
+    return Void();
+}
+
+Return<Result> Effect::setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  {
+    uint32_t halCmd[alignedSizeIn<uint32_t>(sizeof(uint32_t) + sizeof(channel_config_t))];
+    halCmd[0] = EFFECT_FEATURE_AUX_CHANNELS;
+    effectAuxChannelsConfigToHal(config, reinterpret_cast<channel_config_t*>(&halCmd[1]));
+    return sendCommandReturningStatus(EFFECT_CMD_SET_FEATURE_CONFIG,
+            "SET_FEATURE_CONFIG AUX_CHANNELS", sizeof(halCmd), halCmd);
+}
+
+Return<Result> Effect::setAudioSource(AudioSource source)  {
+    uint32_t halSource = static_cast<uint32_t>(source);
+    return sendCommand(
+            EFFECT_CMD_SET_AUDIO_SOURCE, "SET_AUDIO_SOURCE", sizeof(uint32_t), &halSource);
+}
+
+Return<Result> Effect::offload(const EffectOffloadParameter& param)  {
+    effect_offload_param_t halParam;
+    effectOffloadParamToHal(param, &halParam);
+    return sendCommandReturningStatus(
+            EFFECT_CMD_OFFLOAD, "OFFLOAD", sizeof(effect_offload_param_t), &halParam);
+}
+
+Return<void> Effect::getDescriptor(getDescriptor_cb _hidl_cb)  {
+    effect_descriptor_t halDescriptor;
+    memset(&halDescriptor, 0, sizeof(effect_descriptor_t));
+    status_t status = (*mHandle)->get_descriptor(mHandle, &halDescriptor);
+    EffectDescriptor descriptor;
+    if (status == OK) {
+        effectDescriptorFromHal(halDescriptor, &descriptor);
+    }
+    _hidl_cb(analyzeStatus("get_descriptor", "", sContextCallFunction, status), descriptor);
+    return Void();
+}
+
+Return<void> Effect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  {
+    processImpl((*mHandle)->process, "process", inBuffer, outFrameSize, _hidl_cb);
+    return Void();
+}
+
+Return<void> Effect::processReverse(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, processReverse_cb _hidl_cb)  {
+    if ((*mHandle)->process_reverse != NULL) {
+        processImpl(
+                (*mHandle)->process_reverse, "process_reverse", inBuffer, outFrameSize, _hidl_cb);
+    } else {
+        _hidl_cb(Result::NOT_SUPPORTED, AudioBuffer());
+    }
+    return Void();
+}
+
+Return<void> Effect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb)  {
+    uint32_t halDataSize;
+    void *halData;
+    hidlVecToHal(data, &halDataSize, &halData);
+    uint32_t halResultSize = resultMaxSize;
+    std::unique_ptr<uint8_t[]> halResult(new uint8_t[halResultSize]);
+    memset(&halResult[0], 0, halResultSize);
+    status_t status = (*mHandle)->command(
+            mHandle, commandId, halDataSize, halData, &halResultSize, &halResult[0]);
+    hidl_vec<uint8_t> result;
+    if (status == OK) {
+        result.setToExternal(&halResult[0], halResultSize);
+    }
+    _hidl_cb(status, result);
+    return Void();
+}
+
+Return<Result> Effect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  {
+    return setParameterImpl(parameter.size(), &parameter[0], value.size(), &value[0]);
+}
+
+Return<void> Effect::getParameter(
+        const hidl_vec<uint8_t>& parameter, uint32_t valueMaxSize, getParameter_cb _hidl_cb)  {
+    hidl_vec<uint8_t> value;
+    Result retval = getParameterImpl(
+            parameter.size(),
+            &parameter[0],
+            valueMaxSize,
+            [&] (uint32_t valueSize, const void* valueData) {
+                value.setToExternal(
+                        reinterpret_cast<uint8_t*>(const_cast<void*>(valueData)), valueSize);
+            });
+    _hidl_cb(retval, value);
+    return Void();
+}
+
+Return<void> Effect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb)  {
+    uint32_t configCount = 0;
+    hidl_vec<uint8_t> result;
+    Result retval = getSupportedConfigsImpl(
+            featureId,
+            maxConfigs,
+            configSize,
+            [&] (uint32_t supportedConfigs, void* configsData) {
+                configCount = supportedConfigs;
+                result.resize(configCount * configSize);
+                memcpy(&result[0], configsData, result.size());
+            });
+    _hidl_cb(retval, configCount, result);
+    return Void();
+}
+
+Return<void> Effect::getCurrentConfigForFeature(
+        uint32_t featureId, uint32_t configSize, getCurrentConfigForFeature_cb _hidl_cb)  {
+    hidl_vec<uint8_t> result;
+    Result retval = getCurrentConfigImpl(
+            featureId,
+            configSize,
+            [&] (void* configData) {
+                result.resize(configSize);
+                memcpy(&result[0], configData, result.size());
+            });
+    _hidl_cb(retval, result);
+    return Void();
+}
+
+Return<Result> Effect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData)  {
+    uint32_t halCmd[alignedSizeIn<uint32_t>(sizeof(uint32_t) + configData.size())];
+    memset(halCmd, 0, sizeof(halCmd));
+    halCmd[0] = featureId;
+    memcpy(&halCmd[1], &configData[0], configData.size());
+    return sendCommandReturningStatus(
+            EFFECT_CMD_SET_FEATURE_CONFIG, "SET_FEATURE_CONFIG", sizeof(halCmd), halCmd);
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/Effect.h b/audio/effect/2.0/default/Effect.h
new file mode 100644 (file)
index 0000000..e27a7e4
--- /dev/null
@@ -0,0 +1,259 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_Effect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_Effect_H_
+
+#include <vector>
+
+#include <android/hardware/audio/effect/2.0/IEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include <hardware/audio_effect.h>
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::common::V2_0::Uuid;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectFeature;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Effect : public IEffect {
+    explicit Effect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Utility methods for extending interfaces.
+    template<typename T> Return<void> getIntegerParam(
+            uint32_t paramId, std::function<void(Result retval, T paramValue)> cb) {
+        T value;
+        Result retval = getParameterImpl(
+                sizeof(uint32_t), &paramId,
+                sizeof(T),
+                [&] (uint32_t valueSize, const void* valueData) {
+                    if (valueSize > sizeof(T)) valueSize = sizeof(T);
+                    memcpy(&value, valueData, valueSize);
+                });
+        cb(retval, value);
+        return Void();
+    }
+
+    template<typename T> Result getParam(uint32_t paramId, T& paramValue) {
+        return getParameterImpl(
+                sizeof(uint32_t), &paramId,
+                sizeof(T),
+                [&] (uint32_t valueSize, const void* valueData) {
+                    if (valueSize > sizeof(T)) valueSize = sizeof(T);
+                    memcpy(&paramValue, valueData, valueSize);
+                });
+    }
+
+    template<typename T> Result getParam(uint32_t paramId, uint32_t paramArg, T& paramValue) {
+        uint32_t params[2] = { paramId, paramArg };
+        return getParameterImpl(
+                sizeof(params), params,
+                sizeof(T),
+                [&] (uint32_t valueSize, const void* valueData) {
+                    if (valueSize > sizeof(T)) valueSize = sizeof(T);
+                    memcpy(&paramValue, valueData, valueSize);
+                });
+    }
+
+    template<typename T> Result setParam(uint32_t paramId, const T& paramValue) {
+        return setParameterImpl(sizeof(uint32_t), &paramId, sizeof(T), &paramValue);
+    }
+
+    template<typename T> Result setParam(uint32_t paramId, uint32_t paramArg, const T& paramValue) {
+        uint32_t params[2] = { paramId, paramArg };
+        return setParameterImpl(sizeof(params), params, sizeof(T), &paramValue);
+    }
+
+  private:
+    friend struct VirtualizerEffect;  // for getParameterImpl
+    friend struct VisualizerEffect;   // to allow executing commands
+
+    typedef int32_t (*ProcessFunction)(
+            effect_handle_t self, audio_buffer_t* inBuffer, audio_buffer_t* outBuffer);
+    using CommandSuccessCallback = std::function<void()>;
+    using GetConfigCallback = std::function<void(Result retval, const EffectConfig& config)>;
+    using GetCurrentConfigSuccessCallback = std::function<void(void* configData)>;
+    using GetParameterSuccessCallback =
+            std::function<void(uint32_t valueSize, const void* valueData)>;
+    using GetSupportedConfigsSuccessCallback =
+            std::function<void(uint32_t supportedConfigs, void* configsData)>;
+    using ProcessCallback = std::function<void(Result retval, const AudioBuffer& outBuffer)>;
+
+    static const char *sContextResultOfCommand;
+    static const char *sContextCallToCommand;
+    static const char *sContextCallFunction;
+
+    effect_handle_t mHandle;
+
+    virtual ~Effect();
+
+    template<typename T> static size_t alignedSizeIn(size_t s);
+    template<typename T> static void hidlVecToHal(
+            const hidl_vec<T>& vec, uint32_t* halDataSize, void** halData);
+    static void effectAuxChannelsConfigFromHal(
+            const channel_config_t& halConfig, EffectAuxChannelsConfig* config);
+    static void effectAuxChannelsConfigToHal(
+            const EffectAuxChannelsConfig& config, channel_config_t* halConfig);
+    static void effectBufferConfigFromHal(
+            const buffer_config_t& halConfig, EffectBufferConfig* config);
+    static void effectBufferConfigToHal(
+            const EffectBufferConfig& config, buffer_config_t* halConfig);
+    static void effectConfigFromHal(const effect_config_t& halConfig, EffectConfig* config);
+    static void effectConfigToHal(const EffectConfig& config, effect_config_t* halConfig);
+    static void effectOffloadParamToHal(
+            const EffectOffloadParameter& offload, effect_offload_param_t* halOffload);
+    static std::vector<uint8_t> parameterToHal(
+            uint32_t paramSize, const void* paramData, uint32_t valueSize, const void** valueData);
+
+    Result analyzeCommandStatus(
+            const char* commandName, const char* context, status_t status);
+    Result analyzeStatus(
+            const char* funcName,
+            const char* subFuncName,
+            const char* contextDescription,
+            status_t status);
+    void getConfigImpl(int commandCode, const char* commandName, GetConfigCallback cb);
+    Result getCurrentConfigImpl(
+            uint32_t featureId, uint32_t configSize, GetCurrentConfigSuccessCallback onSuccess);
+    Result getParameterImpl(
+            uint32_t paramSize,
+            const void* paramData,
+            uint32_t valueSize,
+            GetParameterSuccessCallback onSuccess);
+    Result getSupportedConfigsImpl(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            GetSupportedConfigsSuccessCallback onSuccess);
+    void processImpl(
+            ProcessFunction process,
+            const char* funcName,
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            ProcessCallback cb);
+    Result sendCommand(int commandCode, const char* commandName);
+    Result sendCommand(int commandCode, const char* commandName, uint32_t size, void* data);
+    Result sendCommandReturningData(
+            int commandCode, const char* commandName, uint32_t* replySize, void* replyData);
+    Result sendCommandReturningData(
+            int commandCode, const char* commandName,
+            uint32_t size, void* data,
+            uint32_t* replySize, void* replyData);
+    Result sendCommandReturningStatus(int commandCode, const char* commandName);
+    Result sendCommandReturningStatus(
+            int commandCode, const char* commandName, uint32_t size, void* data);
+    Result sendCommandReturningStatusAndData(
+            int commandCode, const char* commandName,
+            uint32_t size, void* data,
+            uint32_t* replySize, void* replyData,
+            uint32_t minReplySize,
+            CommandSuccessCallback onSuccess);
+    Result setConfigImpl(
+            int commandCode, const char* commandName,
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider);
+    Result setParameterImpl(
+            uint32_t paramSize, const void* paramData, uint32_t valueSize, const void* valueData);
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_Effect_H_
diff --git a/audio/effect/2.0/default/EffectsFactory.cpp b/audio/effect/2.0/default/EffectsFactory.cpp
new file mode 100644 (file)
index 0000000..30fcb26
--- /dev/null
@@ -0,0 +1,202 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "EffectFactoryHAL"
+#include <media/EffectsFactoryApi.h>
+#include <system/audio_effects/effect_aec.h>
+#include <system/audio_effects/effect_agc.h>
+#include <system/audio_effects/effect_bassboost.h>
+#include <system/audio_effects/effect_downmix.h>
+#include <system/audio_effects/effect_environmentalreverb.h>
+#include <system/audio_effects/effect_equalizer.h>
+#include <system/audio_effects/effect_loudnessenhancer.h>
+#include <system/audio_effects/effect_ns.h>
+#include <system/audio_effects/effect_presetreverb.h>
+#include <system/audio_effects/effect_virtualizer.h>
+#include <system/audio_effects/effect_visualizer.h>
+#include <utils/Log.h>
+
+#include "AcousticEchoCancelerEffect.h"
+#include "AutomaticGainControlEffect.h"
+#include "BassBoostEffect.h"
+#include "Conversions.h"
+#include "EffectsFactory.h"
+#include "DownmixEffect.h"
+#include "Effect.h"
+#include "EffectMap.h"
+#include "EnvironmentalReverbEffect.h"
+#include "EqualizerEffect.h"
+#include "LoudnessEnhancerEffect.h"
+#include "NoiseSuppressionEffect.h"
+#include "PresetReverbEffect.h"
+#include "VirtualizerEffect.h"
+#include "VisualizerEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+// static
+sp<IEffect> EffectsFactory::dispatchEffectInstanceCreation(
+        const effect_descriptor_t& halDescriptor, effect_handle_t handle) {
+    const effect_uuid_t *halUuid = &halDescriptor.type;
+    if (memcmp(halUuid, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) {
+        return new AcousticEchoCancelerEffect(handle);
+    } else if (memcmp(halUuid, FX_IID_AGC, sizeof(effect_uuid_t)) == 0) {
+        return new AutomaticGainControlEffect(handle);
+    } else if (memcmp(halUuid, SL_IID_BASSBOOST, sizeof(effect_uuid_t)) == 0) {
+        return new BassBoostEffect(handle);
+    } else if (memcmp(halUuid, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
+        return new DownmixEffect(handle);
+    } else if (memcmp(halUuid, SL_IID_ENVIRONMENTALREVERB, sizeof(effect_uuid_t)) == 0) {
+        return new EnvironmentalReverbEffect(handle);
+    } else if (memcmp(halUuid, SL_IID_EQUALIZER, sizeof(effect_uuid_t)) == 0) {
+        return new EqualizerEffect(handle);
+    } else if (memcmp(halUuid, FX_IID_LOUDNESS_ENHANCER, sizeof(effect_uuid_t)) == 0) {
+        return new LoudnessEnhancerEffect(handle);
+    } else if (memcmp(halUuid, FX_IID_NS, sizeof(effect_uuid_t)) == 0) {
+        return new NoiseSuppressionEffect(handle);
+    } else if (memcmp(halUuid, SL_IID_PRESETREVERB, sizeof(effect_uuid_t)) == 0) {
+        return new PresetReverbEffect(handle);
+    } else if (memcmp(halUuid, SL_IID_VIRTUALIZER, sizeof(effect_uuid_t)) == 0) {
+        return new VirtualizerEffect(handle);
+    } else if (memcmp(halUuid, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) {
+        return new VisualizerEffect(handle);
+    }
+    return new Effect(handle);
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffectsFactory follow.
+Return<void> EffectsFactory::getAllDescriptors(getAllDescriptors_cb _hidl_cb)  {
+    Result retval(Result::OK);
+    hidl_vec<EffectDescriptor> result;
+    uint32_t numEffects;
+    status_t status;
+
+restart:
+    numEffects = 0;
+    status = EffectQueryNumberEffects(&numEffects);
+    if (status != OK) {
+        retval = Result::NOT_INITIALIZED;
+        ALOGW("Error querying number of effects: %s", strerror(-status));
+        goto exit;
+    }
+    result.resize(numEffects);
+    for (uint32_t i = 0; i < numEffects; ++i) {
+        effect_descriptor_t halDescriptor;
+        status = EffectQueryEffect(i, &halDescriptor);
+        if (status == OK) {
+            effectDescriptorFromHal(halDescriptor, &result[i]);
+        } else {
+            ALOGW("Error querying effect at position %d / %d: %s",
+                    i, numEffects, strerror(-status));
+            switch (status) {
+                case -ENOSYS: {
+                    // Effect list has changed.
+                    goto restart;
+                }
+                case -ENOENT: {
+                    // No more effects available.
+                    result.resize(i);
+                }
+                default: {
+                    result.resize(0);
+                    retval = Result::NOT_INITIALIZED;
+                }
+            }
+            break;
+        }
+    }
+
+exit:
+    _hidl_cb(retval, result);
+    return Void();
+}
+
+Return<void> EffectsFactory::getDescriptor(const Uuid& uid, getDescriptor_cb _hidl_cb)  {
+    effect_uuid_t halUuid;
+    uuidToHal(uid, &halUuid);
+    effect_descriptor_t halDescriptor;
+    status_t status = EffectGetDescriptor(&halUuid, &halDescriptor);
+    EffectDescriptor descriptor;
+    effectDescriptorFromHal(halDescriptor, &descriptor);
+    Result retval(Result::OK);
+    if (status != OK) {
+        ALOGW("Error querying effect descriptor for %s: %s",
+                uuidToString(halUuid).c_str(), strerror(-status));
+        if (status == -ENOENT) {
+            retval = Result::INVALID_ARGUMENTS;
+        } else {
+            retval = Result::NOT_INITIALIZED;
+        }
+    }
+    _hidl_cb(retval, descriptor);
+    return Void();
+}
+
+Return<void> EffectsFactory::createEffect(
+        const Uuid& uid, int32_t session, int32_t ioHandle, createEffect_cb _hidl_cb)  {
+    effect_uuid_t halUuid;
+    uuidToHal(uid, &halUuid);
+    effect_handle_t handle;
+    Result retval(Result::OK);
+    status_t status = EffectCreate(&halUuid, session, ioHandle, &handle);
+    sp<IEffect> effect;
+    uint64_t effectId = EffectMap::INVALID_ID;
+    if (status == OK) {
+        effect_descriptor_t halDescriptor;
+        memset(&halDescriptor, 0, sizeof(effect_descriptor_t));
+        status = (*handle)->get_descriptor(handle, &halDescriptor);
+        if (status == OK) {
+            effect = dispatchEffectInstanceCreation(halDescriptor, handle);
+            effectId = EffectMap::getInstance().add(handle);
+        } else {
+            EffectRelease(handle);
+        }
+    }
+    if (status != OK) {
+        ALOGW("Error creating effect %s: %s", uuidToString(halUuid).c_str(), strerror(-status));
+        if (status == -ENOENT) {
+            retval = Result::INVALID_ARGUMENTS;
+        } else {
+            retval = Result::NOT_INITIALIZED;
+        }
+    }
+    _hidl_cb(retval, effect, effectId);
+    return Void();
+}
+
+Return<void> EffectsFactory::debugDump(const native_handle_t* fd)  {
+    if (fd->numFds == 1) {
+        EffectDumpEffects(fd->data[0]);
+    }
+    return Void();
+}
+
+
+IEffectsFactory* HIDL_FETCH_IEffectsFactory(const char* /* name */) {
+    return new EffectsFactory();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/EffectsFactory.h b/audio/effect/2.0/default/EffectsFactory.h
new file mode 100644 (file)
index 0000000..229356f
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_EffectsFactory_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_EffectsFactory_H_
+
+#include <system/audio_effect.h>
+
+#include <android/hardware/audio/effect/2.0/IEffectsFactory.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::Uuid;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectsFactory;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct EffectsFactory : public IEffectsFactory {
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffectsFactory follow.
+    Return<void> getAllDescriptors(getAllDescriptors_cb _hidl_cb)  override;
+    Return<void> getDescriptor(const Uuid& uid, getDescriptor_cb _hidl_cb)  override;
+    Return<void> createEffect(
+            const Uuid& uid, int32_t session, int32_t ioHandle, createEffect_cb _hidl_cb)  override;
+    Return<void> debugDump(const native_handle_t* fd)  override;
+
+  private:
+    static sp<IEffect> dispatchEffectInstanceCreation(
+            const effect_descriptor_t& halDescriptor, effect_handle_t handle);
+};
+
+extern "C" IEffectsFactory* HIDL_FETCH_IEffectsFactory(const char* name);
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_EffectsFactory_H_
diff --git a/audio/effect/2.0/default/EnvironmentalReverbEffect.cpp b/audio/effect/2.0/default/EnvironmentalReverbEffect.cpp
new file mode 100644 (file)
index 0000000..4485be4
--- /dev/null
@@ -0,0 +1,310 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "EnvReverb_HAL"
+#include <utils/Log.h>
+
+#include "EnvironmentalReverbEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+EnvironmentalReverbEffect::EnvironmentalReverbEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+EnvironmentalReverbEffect::~EnvironmentalReverbEffect() {}
+
+void EnvironmentalReverbEffect::propertiesFromHal(
+        const t_reverb_settings& halProperties,
+        IEnvironmentalReverbEffect::AllProperties* properties) {
+    properties->roomLevel = halProperties.roomLevel;
+    properties->roomHfLevel = halProperties.roomHFLevel;
+    properties->decayTime = halProperties.decayTime;
+    properties->decayHfRatio = halProperties.decayHFRatio;
+    properties->reflectionsLevel = halProperties.reflectionsLevel;
+    properties->reflectionsDelay = halProperties.reflectionsDelay;
+    properties->reverbLevel = halProperties.reverbLevel;
+    properties->reverbDelay = halProperties.reverbDelay;
+    properties->diffusion = halProperties.diffusion;
+    properties->density = halProperties.density;
+}
+
+void EnvironmentalReverbEffect::propertiesToHal(
+        const IEnvironmentalReverbEffect::AllProperties& properties,
+        t_reverb_settings* halProperties) {
+    halProperties->roomLevel = properties.roomLevel;
+    halProperties->roomHFLevel = properties.roomHfLevel;
+    halProperties->decayTime = properties.decayTime;
+    halProperties->decayHFRatio = properties.decayHfRatio;
+    halProperties->reflectionsLevel = properties.reflectionsLevel;
+    halProperties->reflectionsDelay = properties.reflectionsDelay;
+    halProperties->reverbLevel = properties.reverbLevel;
+    halProperties->reverbDelay = properties.reverbDelay;
+    halProperties->diffusion = properties.diffusion;
+    halProperties->density = properties.density;
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> EnvironmentalReverbEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> EnvironmentalReverbEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> EnvironmentalReverbEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> EnvironmentalReverbEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> EnvironmentalReverbEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> EnvironmentalReverbEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> EnvironmentalReverbEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> EnvironmentalReverbEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> EnvironmentalReverbEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> EnvironmentalReverbEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> EnvironmentalReverbEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> EnvironmentalReverbEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> EnvironmentalReverbEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> EnvironmentalReverbEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> EnvironmentalReverbEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEnvironmentalReverbEffect follow.
+Return<Result> EnvironmentalReverbEffect::setBypass(bool bypass)  {
+    return mEffect->setParam(REVERB_PARAM_BYPASS, bypass);
+}
+
+Return<void> EnvironmentalReverbEffect::getBypass(getBypass_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_BYPASS, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setRoomLevel(int16_t roomLevel)  {
+    return mEffect->setParam(REVERB_PARAM_ROOM_LEVEL, roomLevel);
+}
+
+Return<void> EnvironmentalReverbEffect::getRoomLevel(getRoomLevel_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_ROOM_LEVEL, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setRoomHfLevel(int16_t roomHfLevel)  {
+    return mEffect->setParam(REVERB_PARAM_ROOM_HF_LEVEL, roomHfLevel);
+}
+
+Return<void> EnvironmentalReverbEffect::getRoomHfLevel(getRoomHfLevel_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_ROOM_HF_LEVEL, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setDecayTime(uint32_t decayTime)  {
+    return mEffect->setParam(REVERB_PARAM_DECAY_TIME, decayTime);
+}
+
+Return<void> EnvironmentalReverbEffect::getDecayTime(getDecayTime_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_DECAY_TIME, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setDecayHfRatio(int16_t decayHfRatio)  {
+    return mEffect->setParam(REVERB_PARAM_DECAY_HF_RATIO, decayHfRatio);
+}
+
+Return<void> EnvironmentalReverbEffect::getDecayHfRatio(getDecayHfRatio_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_DECAY_HF_RATIO, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setReflectionsLevel(int16_t reflectionsLevel)  {
+    return mEffect->setParam(REVERB_PARAM_REFLECTIONS_LEVEL, reflectionsLevel);
+}
+
+Return<void> EnvironmentalReverbEffect::getReflectionsLevel(getReflectionsLevel_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_REFLECTIONS_LEVEL, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setReflectionsDelay(uint32_t reflectionsDelay)  {
+    return mEffect->setParam(REVERB_PARAM_REFLECTIONS_DELAY, reflectionsDelay);
+}
+
+Return<void> EnvironmentalReverbEffect::getReflectionsDelay(getReflectionsDelay_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_REFLECTIONS_DELAY, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setReverbLevel(int16_t reverbLevel)  {
+    return mEffect->setParam(REVERB_PARAM_REVERB_LEVEL, reverbLevel);
+}
+
+Return<void> EnvironmentalReverbEffect::getReverbLevel(getReverbLevel_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_REVERB_LEVEL, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setReverbDelay(uint32_t reverbDelay) {
+    return mEffect->setParam(REVERB_PARAM_REVERB_DELAY, reverbDelay);
+}
+
+Return<void> EnvironmentalReverbEffect::getReverbDelay(getReverbDelay_cb _hidl_cb) {
+    return mEffect->getIntegerParam(REVERB_PARAM_REVERB_DELAY, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setDiffusion(int16_t diffusion)  {
+    return mEffect->setParam(REVERB_PARAM_DIFFUSION, diffusion);
+}
+
+Return<void> EnvironmentalReverbEffect::getDiffusion(getDiffusion_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_DIFFUSION, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setDensity(int16_t density)  {
+    return mEffect->setParam(REVERB_PARAM_DENSITY, density);
+}
+
+Return<void> EnvironmentalReverbEffect::getDensity(getDensity_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(REVERB_PARAM_DENSITY, _hidl_cb);
+}
+
+Return<Result> EnvironmentalReverbEffect::setAllProperties(
+        const IEnvironmentalReverbEffect::AllProperties& properties)  {
+    t_reverb_settings halProperties;
+    propertiesToHal(properties, &halProperties);
+    return mEffect->setParam(REVERB_PARAM_PROPERTIES, halProperties);
+}
+
+Return<void> EnvironmentalReverbEffect::getAllProperties(getAllProperties_cb _hidl_cb)  {
+    t_reverb_settings halProperties;
+    Result retval = mEffect->getParam(REVERB_PARAM_PROPERTIES, halProperties);
+    AllProperties properties;
+    propertiesFromHal(halProperties, &properties);
+    _hidl_cb(retval, properties);
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/EnvironmentalReverbEffect.h b/audio/effect/2.0/default/EnvironmentalReverbEffect.h
new file mode 100644 (file)
index 0000000..c97c51c
--- /dev/null
@@ -0,0 +1,160 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_EnvironmentalReverbEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_EnvironmentalReverbEffect_H_
+
+#include <system/audio_effects/effect_environmentalreverb.h>
+
+#include <android/hardware/audio/effect/2.0/IEnvironmentalReverbEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::IEnvironmentalReverbEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct EnvironmentalReverbEffect : public IEnvironmentalReverbEffect {
+    explicit EnvironmentalReverbEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEnvironmentalReverbEffect follow.
+    Return<Result> setBypass(bool bypass)  override;
+    Return<void> getBypass(getBypass_cb _hidl_cb)  override;
+    Return<Result> setRoomLevel(int16_t roomLevel)  override;
+    Return<void> getRoomLevel(getRoomLevel_cb _hidl_cb)  override;
+    Return<Result> setRoomHfLevel(int16_t roomHfLevel)  override;
+    Return<void> getRoomHfLevel(getRoomHfLevel_cb _hidl_cb)  override;
+    Return<Result> setDecayTime(uint32_t decayTime)  override;
+    Return<void> getDecayTime(getDecayTime_cb _hidl_cb)  override;
+    Return<Result> setDecayHfRatio(int16_t decayHfRatio)  override;
+    Return<void> getDecayHfRatio(getDecayHfRatio_cb _hidl_cb)  override;
+    Return<Result> setReflectionsLevel(int16_t reflectionsLevel)  override;
+    Return<void> getReflectionsLevel(getReflectionsLevel_cb _hidl_cb)  override;
+    Return<Result> setReflectionsDelay(uint32_t reflectionsDelay)  override;
+    Return<void> getReflectionsDelay(getReflectionsDelay_cb _hidl_cb)  override;
+    Return<Result> setReverbLevel(int16_t reverbLevel)  override;
+    Return<void> getReverbLevel(getReverbLevel_cb _hidl_cb)  override;
+    Return<Result> setReverbDelay(uint32_t reverbDelay)  override;
+    Return<void> getReverbDelay(getReverbDelay_cb _hidl_cb)  override;
+    Return<Result> setDiffusion(int16_t diffusion)  override;
+    Return<void> getDiffusion(getDiffusion_cb _hidl_cb)  override;
+    Return<Result> setDensity(int16_t density)  override;
+    Return<void> getDensity(getDensity_cb _hidl_cb)  override;
+    Return<Result> setAllProperties(
+            const IEnvironmentalReverbEffect::AllProperties& properties)  override;
+    Return<void> getAllProperties(getAllProperties_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~EnvironmentalReverbEffect();
+
+    void propertiesFromHal(
+            const t_reverb_settings& halProperties,
+            IEnvironmentalReverbEffect::AllProperties* properties);
+    void propertiesToHal(
+            const IEnvironmentalReverbEffect::AllProperties& properties,
+            t_reverb_settings* halProperties);
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_EnvironmentalReverbEffect_H_
diff --git a/audio/effect/2.0/default/EqualizerEffect.cpp b/audio/effect/2.0/default/EqualizerEffect.cpp
new file mode 100644 (file)
index 0000000..9e20b8a
--- /dev/null
@@ -0,0 +1,286 @@
+/*
+ * 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.
+ */
+
+#include <memory.h>
+
+#define LOG_TAG "Equalizer_HAL"
+#include <utils/Log.h>
+
+#include "EqualizerEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+EqualizerEffect::EqualizerEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+EqualizerEffect::~EqualizerEffect() {}
+
+void EqualizerEffect::propertiesFromHal(
+        t_equalizer_settings& halProperties,
+        IEqualizerEffect::AllProperties* properties) {
+    properties->curPreset = halProperties.curPreset;
+    properties->bandLevels.setToExternal(&halProperties.bandLevels[0], halProperties.numBands);
+}
+
+std::vector<uint8_t> EqualizerEffect::propertiesToHal(
+        const IEqualizerEffect::AllProperties& properties,
+        t_equalizer_settings** halProperties) {
+    size_t bandsSize = properties.bandLevels.size() * sizeof(uint16_t);
+    std::vector<uint8_t> halBuffer(sizeof(t_equalizer_settings) + bandsSize, 0);
+    *halProperties = reinterpret_cast<t_equalizer_settings*>(&halBuffer[0]);
+    (*halProperties)->curPreset = properties.curPreset;
+    (*halProperties)->numBands = properties.bandLevels.size();
+    memcpy((*halProperties)->bandLevels, &properties.bandLevels[0], bandsSize);
+    return halBuffer;
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> EqualizerEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> EqualizerEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> EqualizerEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> EqualizerEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> EqualizerEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> EqualizerEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> EqualizerEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> EqualizerEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> EqualizerEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> EqualizerEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> EqualizerEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> EqualizerEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> EqualizerEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> EqualizerEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> EqualizerEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> EqualizerEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> EqualizerEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> EqualizerEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> EqualizerEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> EqualizerEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> EqualizerEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> EqualizerEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> EqualizerEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> EqualizerEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> EqualizerEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> EqualizerEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEqualizerEffect follow.
+Return<void> EqualizerEffect::getNumBands(getNumBands_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(EQ_PARAM_NUM_BANDS, _hidl_cb);
+}
+
+Return<void> EqualizerEffect::getLevelRange(getLevelRange_cb _hidl_cb)  {
+    uint16_t halLevels[2] = { 0, 0 };
+    Result retval = mEffect->getParam(EQ_PARAM_LEVEL_RANGE, halLevels);
+    _hidl_cb(retval, halLevels[0], halLevels[1]);
+    return Void();
+}
+
+Return<Result> EqualizerEffect::setBandLevel(uint16_t band, uint16_t level)  {
+    return mEffect->setParam(EQ_PARAM_BAND_LEVEL, band, level);
+}
+
+Return<void> EqualizerEffect::getBandLevel(uint16_t band, getBandLevel_cb _hidl_cb)  {
+    uint16_t halLevel = 0;
+    Result retval = mEffect->getParam(EQ_PARAM_BAND_LEVEL, band, halLevel);
+    _hidl_cb(retval, halLevel);
+    return Void();
+}
+
+Return<void> EqualizerEffect::getBandCenterFrequency(
+        uint16_t band, getBandCenterFrequency_cb _hidl_cb)  {
+    uint32_t halFreq = 0;
+    Result retval = mEffect->getParam(EQ_PARAM_CENTER_FREQ, band, halFreq);
+    _hidl_cb(retval, halFreq);
+    return Void();
+}
+
+Return<void> EqualizerEffect::getBandFrequencyRange(
+        uint16_t band, getBandFrequencyRange_cb _hidl_cb)  {
+    uint32_t halFreqs[2] = { 0, 0 };
+    Result retval = mEffect->getParam(EQ_PARAM_BAND_FREQ_RANGE, band, halFreqs);
+    _hidl_cb(retval, halFreqs[0], halFreqs[1]);
+    return Void();
+}
+
+Return<void> EqualizerEffect::getBandForFrequency(uint32_t freq, getBandForFrequency_cb _hidl_cb)  {
+    uint16_t halBand = 0;
+    Result retval = mEffect->getParam(EQ_PARAM_GET_BAND, freq, halBand);
+    _hidl_cb(retval, halBand);
+    return Void();
+}
+
+Return<void> EqualizerEffect::getPresetNames(getPresetNames_cb _hidl_cb)  {
+    uint16_t halPresetCount = 0;
+    Result retval = mEffect->getParam(EQ_PARAM_GET_NUM_OF_PRESETS, halPresetCount);
+    hidl_vec<hidl_string> presetNames;
+    if (retval == Result::OK) {
+        presetNames.resize(halPresetCount);
+        for (uint16_t i = 0; i < halPresetCount; ++i) {
+            char halPresetName[EFFECT_STRING_LEN_MAX];
+            retval = mEffect->getParam(EQ_PARAM_GET_PRESET_NAME, i, halPresetName);
+            if (retval == Result::OK) {
+                presetNames[i] = halPresetName;
+            } else {
+                presetNames.resize(i);
+            }
+        }
+    }
+    _hidl_cb(retval, presetNames);
+    return Void();
+}
+
+Return<Result> EqualizerEffect::setCurrentPreset(uint16_t preset)  {
+    return mEffect->setParam(EQ_PARAM_CUR_PRESET, preset);
+}
+
+Return<void> EqualizerEffect::getCurrentPreset(getCurrentPreset_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(EQ_PARAM_CUR_PRESET, _hidl_cb);
+}
+
+Return<Result> EqualizerEffect::setAllProperties(
+        const IEqualizerEffect::AllProperties& properties)  {
+    t_equalizer_settings *halPropertiesPtr = nullptr;
+    std::vector<uint8_t> halBuffer = propertiesToHal(properties, &halPropertiesPtr);
+    return mEffect->setParam(EQ_PARAM_PROPERTIES, *halPropertiesPtr);
+}
+
+Return<void> EqualizerEffect::getAllProperties(getAllProperties_cb _hidl_cb)  {
+    t_equalizer_settings halProperties;
+    Result retval = mEffect->getParam(EQ_PARAM_PROPERTIES, halProperties);
+    AllProperties properties;
+    propertiesFromHal(halProperties, &properties);
+    _hidl_cb(retval, properties);
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/EqualizerEffect.h b/audio/effect/2.0/default/EqualizerEffect.h
new file mode 100644 (file)
index 0000000..5665e9c
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_EqualizerEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_EqualizerEffect_H_
+
+#include <vector>
+
+#include <system/audio_effects/effect_equalizer.h>
+
+#include <android/hardware/audio/effect/2.0/IEqualizerEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::IEqualizerEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct EqualizerEffect : public IEqualizerEffect {
+    explicit EqualizerEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEqualizerEffect follow.
+    Return<void> getNumBands(getNumBands_cb _hidl_cb)  override;
+    Return<void> getLevelRange(getLevelRange_cb _hidl_cb)  override;
+    Return<Result> setBandLevel(uint16_t band, uint16_t level)  override;
+    Return<void> getBandLevel(uint16_t band, getBandLevel_cb _hidl_cb)  override;
+    Return<void> getBandCenterFrequency(
+            uint16_t band, getBandCenterFrequency_cb _hidl_cb)  override;
+    Return<void> getBandFrequencyRange(uint16_t band, getBandFrequencyRange_cb _hidl_cb)  override;
+    Return<void> getBandForFrequency(uint32_t freq, getBandForFrequency_cb _hidl_cb)  override;
+    Return<void> getPresetNames(getPresetNames_cb _hidl_cb)  override;
+    Return<Result> setCurrentPreset(uint16_t preset)  override;
+    Return<void> getCurrentPreset(getCurrentPreset_cb _hidl_cb)  override;
+    Return<Result> setAllProperties(const IEqualizerEffect::AllProperties& properties)  override;
+    Return<void> getAllProperties(getAllProperties_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~EqualizerEffect();
+
+    void propertiesFromHal(
+            t_equalizer_settings& halProperties,
+            IEqualizerEffect::AllProperties* properties);
+    std::vector<uint8_t> propertiesToHal(
+            const IEqualizerEffect::AllProperties& properties,
+            t_equalizer_settings** halProperties);
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_EqualizerEffect_H_
diff --git a/audio/effect/2.0/default/LoudnessEnhancerEffect.cpp b/audio/effect/2.0/default/LoudnessEnhancerEffect.cpp
new file mode 100644 (file)
index 0000000..1e724e0
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * 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.
+ */
+
+#include <system/audio_effects/effect_loudnessenhancer.h>
+
+#define LOG_TAG "LoudnessEnhancer_HAL"
+#include <system/audio_effects/effect_aec.h>
+#include <utils/Log.h>
+
+#include "LoudnessEnhancerEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+LoudnessEnhancerEffect::LoudnessEnhancerEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+LoudnessEnhancerEffect::~LoudnessEnhancerEffect() {}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> LoudnessEnhancerEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> LoudnessEnhancerEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> LoudnessEnhancerEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> LoudnessEnhancerEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> LoudnessEnhancerEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> LoudnessEnhancerEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> LoudnessEnhancerEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> LoudnessEnhancerEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> LoudnessEnhancerEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> LoudnessEnhancerEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> LoudnessEnhancerEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> LoudnessEnhancerEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> LoudnessEnhancerEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> LoudnessEnhancerEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> LoudnessEnhancerEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> LoudnessEnhancerEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> LoudnessEnhancerEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> LoudnessEnhancerEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> LoudnessEnhancerEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+
+// Methods from ::android::hardware::audio::effect::V2_0::ILoudnessEnhancerEffect follow.
+Return<Result> LoudnessEnhancerEffect::setTargetGain(int32_t targetGainMb)  {
+    return mEffect->setParam(LOUDNESS_ENHANCER_DEFAULT_TARGET_GAIN_MB, targetGainMb);
+}
+
+Return<void> LoudnessEnhancerEffect::getTargetGain(getTargetGain_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(LOUDNESS_ENHANCER_DEFAULT_TARGET_GAIN_MB, _hidl_cb);
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/LoudnessEnhancerEffect.h b/audio/effect/2.0/default/LoudnessEnhancerEffect.h
new file mode 100644 (file)
index 0000000..e68b038
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_LoudnessEnhancerEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_LoudnessEnhancerEffect_H_
+
+#include <android/hardware/audio/effect/2.0/ILoudnessEnhancerEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::ILoudnessEnhancerEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct LoudnessEnhancerEffect : public ILoudnessEnhancerEffect {
+    explicit LoudnessEnhancerEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::ILoudnessEnhancerEffect follow.
+    Return<Result> setTargetGain(int32_t targetGainMb)  override;
+    Return<void> getTargetGain(getTargetGain_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~LoudnessEnhancerEffect();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_LoudnessEnhancerEffect_H_
diff --git a/audio/effect/2.0/default/NoiseSuppressionEffect.cpp b/audio/effect/2.0/default/NoiseSuppressionEffect.cpp
new file mode 100644 (file)
index 0000000..5c392df
--- /dev/null
@@ -0,0 +1,228 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "NS_Effect_HAL"
+#include <utils/Log.h>
+
+#include "NoiseSuppressionEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+NoiseSuppressionEffect::NoiseSuppressionEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+NoiseSuppressionEffect::~NoiseSuppressionEffect() {}
+
+void NoiseSuppressionEffect::propertiesFromHal(
+        const t_ns_settings& halProperties,
+        INoiseSuppressionEffect::AllProperties* properties) {
+    properties->level = Level(halProperties.level);
+    properties->type = Type(halProperties.type);
+}
+
+void NoiseSuppressionEffect::propertiesToHal(
+        const INoiseSuppressionEffect::AllProperties& properties,
+        t_ns_settings* halProperties) {
+    halProperties->level = static_cast<uint32_t>(properties.level);
+    halProperties->type = static_cast<uint32_t>(properties.type);
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> NoiseSuppressionEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> NoiseSuppressionEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> NoiseSuppressionEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> NoiseSuppressionEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> NoiseSuppressionEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> NoiseSuppressionEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> NoiseSuppressionEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> NoiseSuppressionEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> NoiseSuppressionEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> NoiseSuppressionEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> NoiseSuppressionEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> NoiseSuppressionEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> NoiseSuppressionEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> NoiseSuppressionEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> NoiseSuppressionEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> NoiseSuppressionEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> NoiseSuppressionEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> NoiseSuppressionEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> NoiseSuppressionEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+
+// Methods from ::android::hardware::audio::effect::V2_0::INoiseSuppressionEffect follow.
+Return<Result> NoiseSuppressionEffect::setSuppressionLevel(INoiseSuppressionEffect::Level level)  {
+    return mEffect->setParam(NS_PARAM_LEVEL, static_cast<int32_t>(level));
+}
+
+Return<void> NoiseSuppressionEffect::getSuppressionLevel(getSuppressionLevel_cb _hidl_cb)  {
+    int32_t halLevel = 0;
+    Result retval = mEffect->getParam(NS_PARAM_LEVEL, halLevel);
+    _hidl_cb(retval, Level(halLevel));
+    return Void();
+}
+
+Return<Result> NoiseSuppressionEffect::setSuppressionType(INoiseSuppressionEffect::Type type)  {
+    return mEffect->setParam(NS_PARAM_TYPE, static_cast<int32_t>(type));
+}
+
+Return<void> NoiseSuppressionEffect::getSuppressionType(getSuppressionType_cb _hidl_cb)  {
+    int32_t halType = 0;
+    Result retval = mEffect->getParam(NS_PARAM_TYPE, halType);
+    _hidl_cb(retval, Type(halType));
+    return Void();
+}
+
+Return<Result> NoiseSuppressionEffect::setAllProperties(
+        const INoiseSuppressionEffect::AllProperties& properties)  {
+    t_ns_settings halProperties;
+    propertiesToHal(properties, &halProperties);
+    return mEffect->setParam(NS_PARAM_PROPERTIES, halProperties);
+}
+
+Return<void> NoiseSuppressionEffect::getAllProperties(getAllProperties_cb _hidl_cb)  {
+    t_ns_settings halProperties;
+    Result retval = mEffect->getParam(NS_PARAM_PROPERTIES, halProperties);
+    AllProperties properties;
+    propertiesFromHal(halProperties, &properties);
+    _hidl_cb(retval, properties);
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/NoiseSuppressionEffect.h b/audio/effect/2.0/default/NoiseSuppressionEffect.h
new file mode 100644 (file)
index 0000000..83e513e
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_NoiseSuppressionEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_NoiseSuppressionEffect_H_
+
+#include <system/audio_effects/effect_ns.h>
+
+#include <android/hardware/audio/effect/2.0/INoiseSuppressionEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::INoiseSuppressionEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct NoiseSuppressionEffect : public INoiseSuppressionEffect {
+    explicit NoiseSuppressionEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::INoiseSuppressionEffect follow.
+    Return<Result> setSuppressionLevel(INoiseSuppressionEffect::Level level)  override;
+    Return<void> getSuppressionLevel(getSuppressionLevel_cb _hidl_cb)  override;
+    Return<Result> setSuppressionType(INoiseSuppressionEffect::Type type)  override;
+    Return<void> getSuppressionType(getSuppressionType_cb _hidl_cb)  override;
+    Return<Result> setAllProperties(
+            const INoiseSuppressionEffect::AllProperties& properties)  override;
+    Return<void> getAllProperties(getAllProperties_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~NoiseSuppressionEffect();
+
+    void propertiesFromHal(
+            const t_ns_settings& halProperties,
+            INoiseSuppressionEffect::AllProperties* properties);
+    void propertiesToHal(
+            const INoiseSuppressionEffect::AllProperties& properties,
+            t_ns_settings* halProperties);
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_NoiseSuppressionEffect_H_
diff --git a/audio/effect/2.0/default/PresetReverbEffect.cpp b/audio/effect/2.0/default/PresetReverbEffect.cpp
new file mode 100644 (file)
index 0000000..988bc51
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "PresetReverb_HAL"
+#include <system/audio_effects/effect_presetreverb.h>
+#include <utils/Log.h>
+
+#include "PresetReverbEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+PresetReverbEffect::PresetReverbEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+PresetReverbEffect::~PresetReverbEffect() {}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> PresetReverbEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> PresetReverbEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> PresetReverbEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> PresetReverbEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> PresetReverbEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> PresetReverbEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> PresetReverbEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> PresetReverbEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> PresetReverbEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> PresetReverbEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> PresetReverbEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> PresetReverbEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> PresetReverbEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> PresetReverbEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> PresetReverbEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> PresetReverbEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> PresetReverbEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> PresetReverbEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> PresetReverbEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> PresetReverbEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> PresetReverbEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> PresetReverbEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> PresetReverbEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> PresetReverbEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> PresetReverbEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> PresetReverbEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+
+// Methods from ::android::hardware::audio::effect::V2_0::IPresetReverbEffect follow.
+Return<Result> PresetReverbEffect::setPreset(IPresetReverbEffect::Preset preset)  {
+    return mEffect->setParam(REVERB_PARAM_PRESET, static_cast<t_reverb_presets>(preset));
+}
+
+Return<void> PresetReverbEffect::getPreset(getPreset_cb _hidl_cb)  {
+    t_reverb_presets halPreset = REVERB_PRESET_NONE;
+    Result retval = mEffect->getParam(REVERB_PARAM_PRESET, halPreset);
+    _hidl_cb(retval, Preset(halPreset));
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/PresetReverbEffect.h b/audio/effect/2.0/default/PresetReverbEffect.h
new file mode 100644 (file)
index 0000000..3d98102
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_PresetReverbEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_PresetReverbEffect_H_
+
+#include <android/hardware/audio/effect/2.0/IPresetReverbEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::IPresetReverbEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct PresetReverbEffect : public IPresetReverbEffect {
+    explicit PresetReverbEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IPresetReverbEffect follow.
+    Return<Result> setPreset(IPresetReverbEffect::Preset preset)  override;
+    Return<void> getPreset(getPreset_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~PresetReverbEffect();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_PresetReverbEffect_H_
diff --git a/audio/effect/2.0/default/VirtualizerEffect.cpp b/audio/effect/2.0/default/VirtualizerEffect.cpp
new file mode 100644 (file)
index 0000000..af5252b
--- /dev/null
@@ -0,0 +1,242 @@
+/*
+ * 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.
+ */
+
+#include <memory.h>
+
+#define LOG_TAG "Virtualizer_HAL"
+#include <system/audio_effects/effect_virtualizer.h>
+#include <utils/Log.h>
+
+#include "VirtualizerEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+VirtualizerEffect::VirtualizerEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)) {
+}
+
+VirtualizerEffect::~VirtualizerEffect() {}
+
+void VirtualizerEffect::speakerAnglesFromHal(
+        const int32_t* halAngles, uint32_t channelCount, hidl_vec<SpeakerAngle>& speakerAngles) {
+    speakerAngles.resize(channelCount);
+    for (uint32_t i = 0; i < channelCount; ++i) {
+        speakerAngles[i].mask = AudioChannelMask(*halAngles++);
+        speakerAngles[i].azimuth = *halAngles++;
+        speakerAngles[i].elevation = *halAngles++;
+    }
+}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> VirtualizerEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> VirtualizerEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> VirtualizerEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> VirtualizerEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> VirtualizerEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> VirtualizerEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> VirtualizerEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> VirtualizerEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> VirtualizerEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> VirtualizerEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> VirtualizerEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> VirtualizerEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> VirtualizerEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> VirtualizerEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> VirtualizerEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> VirtualizerEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> VirtualizerEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> VirtualizerEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> VirtualizerEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> VirtualizerEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> VirtualizerEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> VirtualizerEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> VirtualizerEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> VirtualizerEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> VirtualizerEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> VirtualizerEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+
+// Methods from ::android::hardware::audio::effect::V2_0::IVirtualizerEffect follow.
+Return<bool> VirtualizerEffect::isStrengthSupported()  {
+    bool halSupported = false;
+    mEffect->getParam(VIRTUALIZER_PARAM_STRENGTH_SUPPORTED, halSupported);
+    return halSupported;
+}
+
+Return<Result> VirtualizerEffect::setStrength(uint16_t strength)  {
+    return mEffect->setParam(VIRTUALIZER_PARAM_STRENGTH, strength);
+}
+
+Return<void> VirtualizerEffect::getStrength(getStrength_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(VIRTUALIZER_PARAM_STRENGTH, _hidl_cb);
+}
+
+Return<void> VirtualizerEffect::getVirtualSpeakerAngles(
+        AudioChannelMask mask, AudioDevice device, getVirtualSpeakerAngles_cb _hidl_cb)  {
+    uint32_t channelCount = audio_channel_count_from_out_mask(
+            static_cast<audio_channel_mask_t>(mask));
+    size_t halSpeakerAnglesSize = sizeof(int32_t) * 3 * channelCount;
+    uint32_t halParam[3] = {
+        VIRTUALIZER_PARAM_VIRTUAL_SPEAKER_ANGLES,
+        static_cast<audio_channel_mask_t>(mask),
+        static_cast<audio_devices_t>(device)
+    };
+    hidl_vec<SpeakerAngle> speakerAngles;
+    Result retval = mEffect->getParameterImpl(
+            sizeof(halParam), halParam,
+            halSpeakerAnglesSize,
+            [&] (uint32_t valueSize, const void* valueData) {
+                if (valueSize > halSpeakerAnglesSize) {
+                    valueSize = halSpeakerAnglesSize;
+                } else if (valueSize < halSpeakerAnglesSize) {
+                    channelCount = valueSize / (sizeof(int32_t) * 3);
+                }
+                speakerAnglesFromHal(
+                        reinterpret_cast<const int32_t*>(valueData), channelCount, speakerAngles);
+            });
+    _hidl_cb(retval, speakerAngles);
+    return Void();
+}
+
+Return<Result> VirtualizerEffect::forceVirtualizationMode(AudioDevice device)  {
+    return mEffect->setParam(
+            VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE, static_cast<audio_devices_t>(device));
+}
+
+Return<void> VirtualizerEffect::getVirtualizationMode(getVirtualizationMode_cb _hidl_cb)  {
+    uint32_t halMode = 0;
+    Result retval = mEffect->getParam(VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE, halMode);
+    _hidl_cb(retval, AudioDevice(halMode));
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/VirtualizerEffect.h b/audio/effect/2.0/default/VirtualizerEffect.h
new file mode 100644 (file)
index 0000000..2731c4e
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_VirtualizerEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_VirtualizerEffect_H_
+
+#include <android/hardware/audio/effect/2.0/IVirtualizerEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioChannelMask;
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::IVirtualizerEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct VirtualizerEffect : public IVirtualizerEffect {
+    explicit VirtualizerEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IVirtualizerEffect follow.
+    Return<bool> isStrengthSupported()  override;
+    Return<Result> setStrength(uint16_t strength)  override;
+    Return<void> getStrength(getStrength_cb _hidl_cb)  override;
+    Return<void> getVirtualSpeakerAngles(
+            AudioChannelMask mask,
+            AudioDevice device,
+            getVirtualSpeakerAngles_cb _hidl_cb)  override;
+    Return<Result> forceVirtualizationMode(AudioDevice device)  override;
+    Return<void> getVirtualizationMode(getVirtualizationMode_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+
+    virtual ~VirtualizerEffect();
+
+    void speakerAnglesFromHal(
+            const int32_t* halAngles, uint32_t channelCount, hidl_vec<SpeakerAngle>& speakerAngles);
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_VirtualizerEffect_H_
diff --git a/audio/effect/2.0/default/VisualizerEffect.cpp b/audio/effect/2.0/default/VisualizerEffect.cpp
new file mode 100644 (file)
index 0000000..a1f92a6
--- /dev/null
@@ -0,0 +1,262 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "Visualizer_HAL"
+#include <system/audio_effects/effect_visualizer.h>
+#include <utils/Log.h>
+
+#include "VisualizerEffect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+VisualizerEffect::VisualizerEffect(effect_handle_t handle)
+        : mEffect(new Effect(handle)), mCaptureSize(0), mMeasurementMode(MeasurementMode::NONE) {
+}
+
+VisualizerEffect::~VisualizerEffect() {}
+
+// Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+Return<Result> VisualizerEffect::init() {
+    return mEffect->init();
+}
+
+Return<Result> VisualizerEffect::setConfig(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfig(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> VisualizerEffect::reset() {
+    return mEffect->reset();
+}
+
+Return<Result> VisualizerEffect::enable() {
+    return mEffect->enable();
+}
+
+Return<Result> VisualizerEffect::disable() {
+    return mEffect->disable();
+}
+
+Return<Result> VisualizerEffect::setDevice(AudioDevice device) {
+    return mEffect->setDevice(device);
+}
+
+Return<void> VisualizerEffect::setAndGetVolume(
+        const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb) {
+    return mEffect->setAndGetVolume(volumes, _hidl_cb);
+}
+
+Return<Result> VisualizerEffect::setAudioMode(AudioMode mode) {
+    return mEffect->setAudioMode(mode);
+}
+
+Return<Result> VisualizerEffect::setConfigReverse(
+        const EffectConfig& config,
+        const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+        const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
+    return mEffect->setConfigReverse(config, inputBufferProvider, outputBufferProvider);
+}
+
+Return<Result> VisualizerEffect::setInputDevice(AudioDevice device) {
+    return mEffect->setInputDevice(device);
+}
+
+Return<void> VisualizerEffect::getConfig(getConfig_cb _hidl_cb) {
+    return mEffect->getConfig(_hidl_cb);
+}
+
+Return<void> VisualizerEffect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
+    return mEffect->getConfigReverse(_hidl_cb);
+}
+
+Return<void> VisualizerEffect::getSupportedAuxChannelsConfigs(
+        uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb) {
+    return mEffect->getSupportedAuxChannelsConfigs(maxConfigs, _hidl_cb);
+}
+
+Return<void> VisualizerEffect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
+    return mEffect->getAuxChannelsConfig(_hidl_cb);
+}
+
+Return<Result> VisualizerEffect::setAuxChannelsConfig(
+        const EffectAuxChannelsConfig& config) {
+    return mEffect->setAuxChannelsConfig(config);
+}
+
+Return<Result> VisualizerEffect::setAudioSource(AudioSource source) {
+    return mEffect->setAudioSource(source);
+}
+
+Return<Result> VisualizerEffect::offload(const EffectOffloadParameter& param) {
+    return mEffect->offload(param);
+}
+
+Return<void> VisualizerEffect::getDescriptor(getDescriptor_cb _hidl_cb) {
+    return mEffect->getDescriptor(_hidl_cb);
+}
+
+Return<void> VisualizerEffect::process(
+        const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb) {
+    return mEffect->process(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> VisualizerEffect::processReverse(
+        const AudioBuffer& inBuffer,
+        uint32_t outFrameSize,
+        processReverse_cb _hidl_cb) {
+    return mEffect->processReverse(inBuffer, outFrameSize, _hidl_cb);
+}
+
+Return<void> VisualizerEffect::command(
+        uint32_t commandId,
+        const hidl_vec<uint8_t>& data,
+        uint32_t resultMaxSize,
+        command_cb _hidl_cb) {
+    return mEffect->command(commandId, data, resultMaxSize, _hidl_cb);
+}
+
+Return<Result> VisualizerEffect::setParameter(
+        const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value) {
+    return mEffect->setParameter(parameter, value);
+}
+
+Return<void> VisualizerEffect::getParameter(
+        const hidl_vec<uint8_t>& parameter,
+        uint32_t valueMaxSize,
+        getParameter_cb _hidl_cb) {
+    return mEffect->getParameter(parameter, valueMaxSize, _hidl_cb);
+}
+
+Return<void> VisualizerEffect::getSupportedConfigsForFeature(
+        uint32_t featureId,
+        uint32_t maxConfigs,
+        uint32_t configSize,
+        getSupportedConfigsForFeature_cb _hidl_cb) {
+    return mEffect->getSupportedConfigsForFeature(featureId, maxConfigs, configSize, _hidl_cb);
+}
+
+Return<void> VisualizerEffect::getCurrentConfigForFeature(
+        uint32_t featureId,
+        uint32_t configSize,
+        getCurrentConfigForFeature_cb _hidl_cb) {
+    return mEffect->getCurrentConfigForFeature(featureId, configSize, _hidl_cb);
+}
+
+Return<Result> VisualizerEffect::setCurrentConfigForFeature(
+        uint32_t featureId, const hidl_vec<uint8_t>& configData) {
+    return mEffect->setCurrentConfigForFeature(featureId, configData);
+}
+
+
+// Methods from ::android::hardware::audio::effect::V2_0::IVisualizerEffect follow.
+Return<Result> VisualizerEffect::setCaptureSize(uint16_t captureSize)  {
+    Result retval = mEffect->setParam(VISUALIZER_PARAM_CAPTURE_SIZE, captureSize);
+    if (retval == Result::OK) {
+        mCaptureSize = captureSize;
+    }
+    return retval;
+}
+
+Return<void> VisualizerEffect::getCaptureSize(getCaptureSize_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(VISUALIZER_PARAM_CAPTURE_SIZE, _hidl_cb);
+}
+
+Return<Result> VisualizerEffect::setScalingMode(IVisualizerEffect::ScalingMode scalingMode)  {
+    return mEffect->setParam(VISUALIZER_PARAM_SCALING_MODE, static_cast<int32_t>(scalingMode));
+}
+
+Return<void> VisualizerEffect::getScalingMode(getScalingMode_cb _hidl_cb)  {
+    int32_t halMode;
+    Result retval = mEffect->getParam(VISUALIZER_PARAM_SCALING_MODE, halMode);
+    _hidl_cb(retval, ScalingMode(halMode));
+    return Void();
+}
+
+Return<Result> VisualizerEffect::setLatency(uint32_t latencyMs)  {
+    return mEffect->setParam(VISUALIZER_PARAM_LATENCY, latencyMs);
+}
+
+Return<void> VisualizerEffect::getLatency(getLatency_cb _hidl_cb)  {
+    return mEffect->getIntegerParam(VISUALIZER_PARAM_LATENCY, _hidl_cb);
+}
+
+Return<Result> VisualizerEffect::setMeasurementMode(
+        IVisualizerEffect::MeasurementMode measurementMode)  {
+    Result retval = mEffect->setParam(
+            VISUALIZER_PARAM_MEASUREMENT_MODE, static_cast<int32_t>(measurementMode));
+    if (retval == Result::OK) {
+        mMeasurementMode = measurementMode;
+    }
+    return retval;
+}
+
+Return<void> VisualizerEffect::getMeasurementMode(getMeasurementMode_cb _hidl_cb)  {
+    int32_t halMode;
+    Result retval = mEffect->getParam(VISUALIZER_PARAM_MEASUREMENT_MODE, halMode);
+    _hidl_cb(retval, MeasurementMode(halMode));
+    return Void();
+}
+
+Return<void> VisualizerEffect::capture(capture_cb _hidl_cb)  {
+    if (mCaptureSize == 0) {
+        _hidl_cb(Result::NOT_INITIALIZED, hidl_vec<uint8_t>());
+        return Void();
+    }
+    uint32_t halCaptureSize = mCaptureSize;
+    uint8_t halCapture[mCaptureSize];
+    Result retval = mEffect->sendCommandReturningData(
+            VISUALIZER_CMD_CAPTURE, "VISUALIZER_CAPTURE", &halCaptureSize, halCapture);
+    hidl_vec<uint8_t> capture;
+    if (retval == Result::OK) {
+        capture.setToExternal(&halCapture[0], halCaptureSize);
+    }
+    _hidl_cb(retval, capture);
+    return Void();
+}
+
+Return<void> VisualizerEffect::measure(measure_cb _hidl_cb)  {
+    if (mMeasurementMode == MeasurementMode::NONE) {
+        _hidl_cb(Result::NOT_INITIALIZED, Measurement());
+        return Void();
+    }
+    int32_t halMeasurement[MEASUREMENT_COUNT];
+    uint32_t halMeasurementSize = sizeof(halMeasurement);
+    Result retval = mEffect->sendCommandReturningData(
+            VISUALIZER_CMD_MEASURE, "VISUALIZER_MEASURE", &halMeasurementSize, halMeasurement);
+    Measurement measurement = { .mode = MeasurementMode::PEAK_RMS };
+    measurement.value.peakAndRms.peakMb = 0;
+    measurement.value.peakAndRms.rmsMb = 0;
+    if (retval == Result::OK) {
+        measurement.value.peakAndRms.peakMb = halMeasurement[MEASUREMENT_IDX_PEAK];
+        measurement.value.peakAndRms.rmsMb = halMeasurement[MEASUREMENT_IDX_RMS];
+    }
+    _hidl_cb(retval, measurement);
+    return Void();
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
diff --git a/audio/effect/2.0/default/VisualizerEffect.h b/audio/effect/2.0/default/VisualizerEffect.h
new file mode 100644 (file)
index 0000000..505b16f
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_audio_effect_V2_0_VisualizerEffect_H_
+#define HIDL_GENERATED_android_hardware_audio_effect_V2_0_VisualizerEffect_H_
+
+#include <android/hardware/audio/effect/2.0/IVisualizerEffect.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+
+#include "Effect.h"
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::audio::common::V2_0::AudioMode;
+using ::android::hardware::audio::common::V2_0::AudioSource;
+using ::android::hardware::audio::effect::V2_0::AudioBuffer;
+using ::android::hardware::audio::effect::V2_0::EffectAuxChannelsConfig;
+using ::android::hardware::audio::effect::V2_0::EffectConfig;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::EffectOffloadParameter;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectBufferProviderCallback;
+using ::android::hardware::audio::effect::V2_0::IVisualizerEffect;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct VisualizerEffect : public IVisualizerEffect {
+    explicit VisualizerEffect(effect_handle_t handle);
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IEffect follow.
+    Return<Result> init()  override;
+    Return<Result> setConfig(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> reset()  override;
+    Return<Result> enable()  override;
+    Return<Result> disable()  override;
+    Return<Result> setDevice(AudioDevice device)  override;
+    Return<void> setAndGetVolume(
+            const hidl_vec<uint32_t>& volumes, setAndGetVolume_cb _hidl_cb)  override;
+    Return<Result> setAudioMode(AudioMode mode)  override;
+    Return<Result> setConfigReverse(
+            const EffectConfig& config,
+            const sp<IEffectBufferProviderCallback>& inputBufferProvider,
+            const sp<IEffectBufferProviderCallback>& outputBufferProvider)  override;
+    Return<Result> setInputDevice(AudioDevice device)  override;
+    Return<void> getConfig(getConfig_cb _hidl_cb)  override;
+    Return<void> getConfigReverse(getConfigReverse_cb _hidl_cb)  override;
+    Return<void> getSupportedAuxChannelsConfigs(
+            uint32_t maxConfigs, getSupportedAuxChannelsConfigs_cb _hidl_cb)  override;
+    Return<void> getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)  override;
+    Return<Result> setAuxChannelsConfig(const EffectAuxChannelsConfig& config)  override;
+    Return<Result> setAudioSource(AudioSource source)  override;
+    Return<Result> offload(const EffectOffloadParameter& param)  override;
+    Return<void> getDescriptor(getDescriptor_cb _hidl_cb)  override;
+    Return<void> process(
+            const AudioBuffer& inBuffer, uint32_t outFrameSize, process_cb _hidl_cb)  override;
+    Return<void> processReverse(
+            const AudioBuffer& inBuffer,
+            uint32_t outFrameSize,
+            processReverse_cb _hidl_cb)  override;
+    Return<void> command(
+            uint32_t commandId,
+            const hidl_vec<uint8_t>& data,
+            uint32_t resultMaxSize,
+            command_cb _hidl_cb)  override;
+    Return<Result> setParameter(
+            const hidl_vec<uint8_t>& parameter, const hidl_vec<uint8_t>& value)  override;
+    Return<void> getParameter(
+            const hidl_vec<uint8_t>& parameter,
+            uint32_t valueMaxSize,
+            getParameter_cb _hidl_cb)  override;
+    Return<void> getSupportedConfigsForFeature(
+            uint32_t featureId,
+            uint32_t maxConfigs,
+            uint32_t configSize,
+            getSupportedConfigsForFeature_cb _hidl_cb)  override;
+    Return<void> getCurrentConfigForFeature(
+            uint32_t featureId,
+            uint32_t configSize,
+            getCurrentConfigForFeature_cb _hidl_cb)  override;
+    Return<Result> setCurrentConfigForFeature(
+            uint32_t featureId, const hidl_vec<uint8_t>& configData)  override;
+
+    // Methods from ::android::hardware::audio::effect::V2_0::IVisualizerEffect follow.
+    Return<Result> setCaptureSize(uint16_t captureSize)  override;
+    Return<void> getCaptureSize(getCaptureSize_cb _hidl_cb)  override;
+    Return<Result> setScalingMode(IVisualizerEffect::ScalingMode scalingMode)  override;
+    Return<void> getScalingMode(getScalingMode_cb _hidl_cb)  override;
+    Return<Result> setLatency(uint32_t latencyMs)  override;
+    Return<void> getLatency(getLatency_cb _hidl_cb)  override;
+    Return<Result> setMeasurementMode(IVisualizerEffect::MeasurementMode measurementMode)  override;
+    Return<void> getMeasurementMode(getMeasurementMode_cb _hidl_cb)  override;
+    Return<void> capture(capture_cb _hidl_cb)  override;
+    Return<void> measure(measure_cb _hidl_cb)  override;
+
+  private:
+    sp<Effect> mEffect;
+    uint16_t mCaptureSize;
+    MeasurementMode mMeasurementMode;
+
+    virtual ~VisualizerEffect();
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_audio_effect_V2_0_VisualizerEffect_H_
diff --git a/audio/effect/2.0/types.hal b/audio/effect/2.0/types.hal
new file mode 100644 (file)
index 0000000..35015b2
--- /dev/null
@@ -0,0 +1,286 @@
+/*
+ * 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 android.hardware.audio.effect@2.0;
+
+import android.hardware.audio.common@2.0;
+
+enum Result {
+    OK,
+    NOT_INITIALIZED,
+    INVALID_ARGUMENTS,
+    INVALID_STATE,
+    NOT_SUPPORTED,
+    RESULT_TOO_BIG
+};
+
+/*
+ * Effect engine capabilities/requirements flags.
+ *
+ * Definitions for flags field of effect descriptor.
+ *
+ * +----------------+--------+--------------------------------------------------
+ * | description    | bits   | values
+ * +----------------+--------+--------------------------------------------------
+ * | connection     | 0..2   | 0 insert: after track process
+ * | mode           |        | 1 auxiliary: connect to track auxiliary
+ * |                |        |  output and use send level
+ * |                |        | 2 replace: replaces track process function;
+ * |                |        |   must implement SRC, volume and mono to stereo.
+ * |                |        | 3 pre processing: applied below audio HAL on in
+ * |                |        | 4 post processing: applied below audio HAL on out
+ * |                |        | 5 - 7 reserved
+ * +----------------+--------+--------------------------------------------------
+ * | insertion      | 3..5   | 0 none
+ * | preference     |        | 1 first of the chain
+ * |                |        | 2 last of the chain
+ * |                |        | 3 exclusive (only effect in the insert chain)
+ * |                |        | 4..7 reserved
+ * +----------------+--------+--------------------------------------------------
+ * | Volume         | 6..8   | 0 none
+ * | management     |        | 1 implements volume control
+ * |                |        | 2 requires volume indication
+ * |                |        | 4 reserved
+ * +----------------+--------+--------------------------------------------------
+ * | Device         | 9..11  | 0 none
+ * | indication     |        | 1 requires device updates
+ * |                |        | 2, 4 reserved
+ * +----------------+--------+--------------------------------------------------
+ * | Sample input   | 12..13 | 1 direct: process() function or
+ * | mode           |        |   EFFECT_CMD_SET_CONFIG command must specify
+ * |                |        |   a buffer descriptor
+ * |                |        | 2 provider: process() function uses the
+ * |                |        |   bufferProvider indicated by the
+ * |                |        |   EFFECT_CMD_SET_CONFIG command to request input.
+ * |                |        |   buffers.
+ * |                |        | 3 both: both input modes are supported
+ * +----------------+--------+--------------------------------------------------
+ * | Sample output  | 14..15 | 1 direct: process() function or
+ * | mode           |        |   EFFECT_CMD_SET_CONFIG command must specify
+ * |                |        |   a buffer descriptor
+ * |                |        | 2 provider: process() function uses the
+ * |                |        |   bufferProvider indicated by the
+ * |                |        |   EFFECT_CMD_SET_CONFIG command to request output
+ * |                |        |   buffers.
+ * |                |        | 3 both: both output modes are supported
+ * +----------------+--------+--------------------------------------------------
+ * | Hardware       | 16..17 | 0 No hardware acceleration
+ * | acceleration   |        | 1 non tunneled hw acceleration: the process()
+ * |                |        |   function reads the samples, send them to HW
+ * |                |        |   accelerated effect processor, reads back
+ * |                |        |   the processed samples and returns them
+ * |                |        |   to the output buffer.
+ * |                |        | 2 tunneled hw acceleration: the process()
+ * |                |        |   function is transparent. The effect interface
+ * |                |        |   is only used to control the effect engine.
+ * |                |        |   This mode is relevant for global effects
+ * |                |        |   actually applied by the audio hardware on
+ * |                |        |   the output stream.
+ * +----------------+--------+--------------------------------------------------
+ * | Audio Mode     | 18..19 | 0 none
+ * | indication     |        | 1 requires audio mode updates
+ * |                |        | 2..3 reserved
+ * +----------------+--------+--------------------------------------------------
+ * | Audio source   | 20..21 | 0 none
+ * | indication     |        | 1 requires audio source updates
+ * |                |        | 2..3 reserved
+ * +----------------+--------+--------------------------------------------------
+ * | Effect offload | 22     | 0 The effect cannot be offloaded to an audio DSP
+ * | supported      |        | 1 The effect can be offloaded to an audio DSP
+ * +----------------+--------+--------------------------------------------------
+ * | Process        | 23     | 0 The effect implements a process function.
+ * | function       |        | 1 The effect does not implement a process
+ * | not            |        |   function: enabling the effect has no impact
+ * | implemented    |        |   on latency or CPU load.
+ * |                |        |   Effect implementations setting this flag do not
+ * |                |        |   have to implement a process function.
+ * +----------------+--------+--------------------------------------------------
+ */
+@export(name="", value_prefix="EFFECT_FLAG_")
+enum EffectFlags {
+    // Insert mode
+    TYPE_SHIFT = 0,
+    TYPE_SIZE = 3,
+    TYPE_MASK = ((1 << TYPE_SIZE) -1) << TYPE_SHIFT,
+    TYPE_INSERT = 0 << TYPE_SHIFT,
+    TYPE_AUXILIARY = 1 << TYPE_SHIFT,
+    TYPE_REPLACE = 2 << TYPE_SHIFT,
+    TYPE_PRE_PROC = 3 << TYPE_SHIFT,
+    TYPE_POST_PROC = 4 << TYPE_SHIFT,
+
+    // Insert preference
+    INSERT_SHIFT = TYPE_SHIFT + TYPE_SIZE,
+    INSERT_SIZE = 3,
+    INSERT_MASK = ((1 << INSERT_SIZE) -1) << INSERT_SHIFT,
+    INSERT_ANY = 0 << INSERT_SHIFT,
+    INSERT_FIRST = 1 << INSERT_SHIFT,
+    INSERT_LAST = 2 << INSERT_SHIFT,
+    INSERT_EXCLUSIVE = 3 << INSERT_SHIFT,
+
+    // Volume control
+    VOLUME_SHIFT = INSERT_SHIFT + INSERT_SIZE,
+    VOLUME_SIZE = 3,
+    VOLUME_MASK = ((1 << VOLUME_SIZE) -1) << VOLUME_SHIFT,
+    VOLUME_CTRL = 1 << VOLUME_SHIFT,
+    VOLUME_IND = 2 << VOLUME_SHIFT,
+    VOLUME_NONE = 0 << VOLUME_SHIFT,
+
+    // Device indication
+    DEVICE_SHIFT = VOLUME_SHIFT + VOLUME_SIZE,
+    DEVICE_SIZE = 3,
+    DEVICE_MASK = ((1 << DEVICE_SIZE) -1) << DEVICE_SHIFT,
+    DEVICE_IND = 1 << DEVICE_SHIFT,
+    DEVICE_NONE = 0 << DEVICE_SHIFT,
+
+    // Sample input modes
+    INPUT_SHIFT = DEVICE_SHIFT + DEVICE_SIZE,
+    INPUT_SIZE = 2,
+    INPUT_MASK = ((1 << INPUT_SIZE) -1) << INPUT_SHIFT,
+    INPUT_DIRECT = 1 << INPUT_SHIFT,
+    INPUT_PROVIDER = 2 << INPUT_SHIFT,
+    INPUT_BOTH = 3 << INPUT_SHIFT,
+
+    // Sample output modes
+    OUTPUT_SHIFT = INPUT_SHIFT + INPUT_SIZE,
+    OUTPUT_SIZE = 2,
+    OUTPUT_MASK = ((1 << OUTPUT_SIZE) -1) << OUTPUT_SHIFT,
+    OUTPUT_DIRECT = 1 << OUTPUT_SHIFT,
+    OUTPUT_PROVIDER = 2 << OUTPUT_SHIFT,
+    OUTPUT_BOTH = 3 << OUTPUT_SHIFT,
+
+    // Hardware acceleration mode
+    HW_ACC_SHIFT = OUTPUT_SHIFT + OUTPUT_SIZE,
+    HW_ACC_SIZE = 2,
+    HW_ACC_MASK = ((1 << HW_ACC_SIZE) -1) << HW_ACC_SHIFT,
+    HW_ACC_SIMPLE = 1 << HW_ACC_SHIFT,
+    HW_ACC_TUNNEL = 2 << HW_ACC_SHIFT,
+
+    // Audio mode indication
+    AUDIO_MODE_SHIFT = HW_ACC_SHIFT + HW_ACC_SIZE,
+    AUDIO_MODE_SIZE = 2,
+    AUDIO_MODE_MASK = ((1 << AUDIO_MODE_SIZE) -1) << AUDIO_MODE_SHIFT,
+    AUDIO_MODE_IND = 1 << AUDIO_MODE_SHIFT,
+    AUDIO_MODE_NONE = 0 << AUDIO_MODE_SHIFT,
+
+    // Audio source indication
+    AUDIO_SOURCE_SHIFT = AUDIO_MODE_SHIFT + AUDIO_MODE_SIZE,
+    AUDIO_SOURCE_SIZE = 2,
+    AUDIO_SOURCE_MASK = ((1 << AUDIO_SOURCE_SIZE) -1) << AUDIO_SOURCE_SHIFT,
+    AUDIO_SOURCE_IND = 1 << AUDIO_SOURCE_SHIFT,
+    AUDIO_SOURCE_NONE = 0 << AUDIO_SOURCE_SHIFT,
+
+    // Effect offload indication
+    OFFLOAD_SHIFT = AUDIO_SOURCE_SHIFT + AUDIO_SOURCE_SIZE,
+    OFFLOAD_SIZE = 1,
+    OFFLOAD_MASK = ((1 << OFFLOAD_SIZE) -1) << OFFLOAD_SHIFT,
+    OFFLOAD_SUPPORTED = 1 << OFFLOAD_SHIFT,
+
+    // Effect has no process indication
+    NO_PROCESS_SHIFT = OFFLOAD_SHIFT + OFFLOAD_SIZE,
+    NO_PROCESS_SIZE = 1,
+    NO_PROCESS_MASK = ((1 << NO_PROCESS_SIZE) -1) << NO_PROCESS_SHIFT,
+    NO_PROCESS = 1 << NO_PROCESS_SHIFT
+};
+
+/*
+ * The effect descriptor contains necessary information to facilitate the
+ * enumeration of the effect engines present in a library.
+ */
+struct EffectDescriptor {
+    Uuid type;             // UUID of to the OpenSL ES interface implemented
+                           // by this effect
+    Uuid uuid;             // UUID for this particular implementation
+    EffectFlags flags;     // effect engine capabilities/requirements flags
+    uint16_t cpuLoad;      // CPU load indication expressed in 0.1 MIPS units
+                           // as estimated on an ARM9E core (ARMv5TE) with 0 WS
+    uint16_t memoryUsage;  // data memory usage expressed in KB and includes
+                           // only dynamically allocated memory
+    uint8_t[64] name;      // human readable effect name
+    uint8_t[64] implementor;  // human readable effect implementor name
+};
+
+/*
+ * A buffer is a chunk of audio data for processing.  Multi-channel audio is
+ * always interleaved. The channel order is from LSB to MSB with regard to the
+ * channel mask definition in audio.h, audio_channel_mask_t, e.g.:
+ * Stereo: L, R; 5.1: FL, FR, FC, LFE, BL, BR.
+ *
+ * The buffer size is expressed in frame count, a frame being composed of
+ * samples for all channels at a given time. Frame size for unspecified format
+ * (AUDIO_FORMAT_OTHER) is 8 bit by definition.
+ */
+// TODO(mnaganov): replace with FMQ version.
+struct AudioBuffer {
+    uint32_t frameCount;
+    vec<uint8_t> data;
+};
+
+@export(name="effect_buffer_access_e", value_prefix="EFFECT_BUFFER_")
+enum EffectBufferAccess {
+    ACCESS_WRITE,
+    ACCESS_READ,
+    ACCESS_ACCUMULATE
+};
+
+/*
+ * Determines what fields of EffectBufferConfig need to be considered.
+ */
+@export(name="", value_prefix="EFFECT_CONFIG_")
+enum EffectConfigParameters {
+    BUFFER = 0x0001,    // buffer field
+    SMP_RATE = 0x0002,  // samplingRate
+    CHANNELS = 0x0004,  // channels
+    FORMAT = 0x0008,    // format
+    ACC_MODE = 0x0010,  // accessMode
+    ALL = BUFFER | SMP_RATE | CHANNELS | FORMAT | ACC_MODE
+};
+
+/*
+ * The buffer config structure specifies the input or output audio format
+ * to be used by the effect engine.
+ */
+struct EffectBufferConfig {
+    AudioBuffer buffer;
+    uint32_t samplingRateHz;
+    AudioChannelMask channels;
+    AudioFormat format;
+    EffectBufferAccess accessMode;
+    EffectConfigParameters mask;
+};
+
+struct EffectConfig {
+    EffectBufferConfig inputCfg;
+    EffectBufferConfig outputCfg;
+};
+
+@export(name="effect_feature_e", value_prefix="EFFECT_FEATURE_")
+enum EffectFeature {
+    AUX_CHANNELS, // supports auxiliary channels
+                  // (e.g. dual mic noise suppressor)
+    CNT
+};
+
+struct EffectAuxChannelsConfig {
+    AudioChannelMask mainChannels;  // channel mask for main channels
+    AudioChannelMask auxChannels;   // channel mask for auxiliary channels
+};
+
+struct EffectOffloadParameter {
+    bool isOffload;          // true if the playback thread the effect
+                             // is attached to is offloaded
+    AudioIoHandle ioHandle;  // io handle of the playback thread
+                             // the effect is attached to
+};
diff --git a/audio/effect/2.0/vts/functional/Android.bp b/audio/effect/2.0/vts/functional/Android.bp
new file mode 100644 (file)
index 0000000..fc198e5
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// 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.
+//
+
+cc_test {
+    name: "audio_effect_hidl_hal_test",
+    gtest: true,
+    srcs: ["audio_effect_hidl_hal_test.cpp"],
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libcutils",
+        "libhidl",
+        "libhwbinder",
+        "libnativehelper",
+        "libutils",
+        "android.hardware.audio.effect@2.0",
+    ],
+    static_libs: ["libgtest"],
+    cflags: [
+        "-O0",
+        "-g",
+    ],
+}
diff --git a/audio/effect/2.0/vts/functional/audio_effect_hidl_hal_test.cpp b/audio/effect/2.0/vts/functional/audio_effect_hidl_hal_test.cpp
new file mode 100644 (file)
index 0000000..c7878d5
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "AudioEffectHidlHalTest"
+#include <android-base/logging.h>
+#include <cutils/native_handle.h>
+
+#include <android/hardware/audio/effect/2.0/IEffectsFactory.h>
+#include <android/hardware/audio/effect/2.0/types.h>
+
+#include <gtest/gtest.h>
+
+using ::android::hardware::audio::common::V2_0::Uuid;
+using ::android::hardware::audio::effect::V2_0::EffectDescriptor;
+using ::android::hardware::audio::effect::V2_0::IEffect;
+using ::android::hardware::audio::effect::V2_0::IEffectsFactory;
+using ::android::hardware::audio::effect::V2_0::Result;
+using ::android::hardware::Return;
+using ::android::hardware::Status;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::sp;
+
+// The main test class for Audio Effect HIDL HAL.
+class AudioEffectHidlTest : public ::testing::Test {
+ public:
+  virtual void SetUp() override {
+    // currently test passthrough mode only
+    effectsFactory = IEffectsFactory::getService("audio_effects_factory", true);
+    ASSERT_NE(effectsFactory, nullptr);
+  }
+
+  virtual void TearDown() override {}
+
+  sp<IEffectsFactory> effectsFactory;
+};
+
+// A class for test environment setup (kept since this file is a template).
+class AudioEffectHidlEnvironment : public ::testing::Environment {
+ public:
+  virtual void SetUp() {}
+  virtual void TearDown() {}
+
+ private:
+};
+
+TEST_F(AudioEffectHidlTest, EnumerateEffects) {
+  Result retval = Result::NOT_INITIALIZED;
+  size_t effectCount = 0;
+  Return<void> ret = effectsFactory->getAllDescriptors(
+      [&](Result r, const hidl_vec<EffectDescriptor>& result) {
+        retval = r;
+        effectCount = result.size();
+      });
+  EXPECT_EQ(ret.getStatus().exceptionCode(), Status::EX_NONE);
+  EXPECT_EQ(retval, Result::OK);
+  EXPECT_GT(effectCount, 0u);
+}
+
+TEST_F(AudioEffectHidlTest, CreateEffect) {
+  bool gotEffect = false;
+  Uuid effectUuid;
+  Return<void> ret = effectsFactory->getAllDescriptors(
+      [&](Result r, const hidl_vec<EffectDescriptor>& result) {
+        if (r == Result::OK && result.size() > 0) {
+          gotEffect = true;
+          effectUuid = result[0].uuid;
+        }
+      });
+  ASSERT_EQ(ret.getStatus().exceptionCode(), Status::EX_NONE);
+  ASSERT_TRUE(gotEffect);
+  Result retval = Result::NOT_INITIALIZED;
+  sp<IEffect> effect;
+  ret = effectsFactory->createEffect(
+      effectUuid, 1 /* session */, 1 /* ioHandle */,
+      [&](Result r, const sp<IEffect>& result, uint64_t /*effectId*/) {
+        retval = r;
+        if (r == Result::OK) {
+          effect = result;
+        }
+      });
+  EXPECT_EQ(ret.getStatus().exceptionCode(), Status::EX_NONE);
+  EXPECT_EQ(retval, Result::OK);
+  EXPECT_NE(effect, nullptr);
+}
+
+// See b/32834072 -- we should have those operator== generated by hidl-gen.
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace common {
+namespace V2_0 {
+
+static bool operator==(const Uuid& lhs, const Uuid& rhs) {
+  return lhs.timeLow == rhs.timeLow && lhs.timeMid == rhs.timeMid &&
+         lhs.versionAndTimeHigh == rhs.versionAndTimeHigh &&
+         lhs.variantAndClockSeqHigh == rhs.variantAndClockSeqHigh &&
+         memcmp(lhs.node.data(), rhs.node.data(), lhs.node.size()) == 0;
+}
+
+}  // namespace V2_0
+}  // namespace common
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+namespace android {
+namespace hardware {
+namespace audio {
+namespace effect {
+namespace V2_0 {
+
+static bool operator==(const EffectDescriptor& lhs,
+                       const EffectDescriptor& rhs) {
+  return lhs.type == rhs.type && lhs.uuid == rhs.uuid &&
+         lhs.flags == rhs.flags && lhs.cpuLoad == rhs.cpuLoad &&
+         lhs.memoryUsage == rhs.memoryUsage &&
+         memcmp(lhs.name.data(), rhs.name.data(), lhs.name.size()) == 0 &&
+         memcmp(lhs.implementor.data(), rhs.implementor.data(),
+                lhs.implementor.size()) == 0;
+}
+
+}  // namespace V2_0
+}  // namespace effect
+}  // namespace audio
+}  // namespace hardware
+}  // namespace android
+
+TEST_F(AudioEffectHidlTest, GetDescriptor) {
+  hidl_vec<EffectDescriptor> allDescriptors;
+  Return<void> ret = effectsFactory->getAllDescriptors(
+      [&](Result r, const hidl_vec<EffectDescriptor>& result) {
+        if (r == Result::OK) {
+          allDescriptors = result;
+        }
+      });
+  ASSERT_EQ(ret.getStatus().exceptionCode(), Status::EX_NONE);
+  ASSERT_GT(allDescriptors.size(), 0u);
+  for (size_t i = 0; i < allDescriptors.size(); ++i) {
+    ret = effectsFactory->getDescriptor(
+        allDescriptors[i].uuid, [&](Result r, const EffectDescriptor& result) {
+          EXPECT_EQ(r, Result::OK);
+          EXPECT_EQ(result, allDescriptors[i]);
+        });
+  }
+  EXPECT_EQ(ret.getStatus().exceptionCode(), Status::EX_NONE);
+}
+
+int main(int argc, char** argv) {
+  ::testing::AddGlobalTestEnvironment(new AudioEffectHidlEnvironment);
+  ::testing::InitGoogleTest(&argc, argv);
+  int status = RUN_ALL_TESTS();
+  ALOGI("Test result = %d", status);
+  return status;
+}
diff --git a/biometrics/Android.bp b/biometrics/Android.bp
new file mode 100644 (file)
index 0000000..eea4604
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "fingerprint/2.1",
+]
diff --git a/biometrics/fingerprint/2.1/Android.bp b/biometrics/fingerprint/2.1/Android.bp
new file mode 100644 (file)
index 0000000..9d2af44
--- /dev/null
@@ -0,0 +1,59 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.biometrics.fingerprint@2.1_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.biometrics.fingerprint@2.1",
+    srcs: [
+        "types.hal",
+        "IBiometricsFingerprint.hal",
+        "IBiometricsFingerprintClientCallback.hal",
+    ],
+    out: [
+        "android/hardware/biometrics/fingerprint/2.1/types.cpp",
+        "android/hardware/biometrics/fingerprint/2.1/BiometricsFingerprintAll.cpp",
+        "android/hardware/biometrics/fingerprint/2.1/BiometricsFingerprintClientCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.biometrics.fingerprint@2.1_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.biometrics.fingerprint@2.1",
+    srcs: [
+        "types.hal",
+        "IBiometricsFingerprint.hal",
+        "IBiometricsFingerprintClientCallback.hal",
+    ],
+    out: [
+        "android/hardware/biometrics/fingerprint/2.1/types.h",
+        "android/hardware/biometrics/fingerprint/2.1/IBiometricsFingerprint.h",
+        "android/hardware/biometrics/fingerprint/2.1/IHwBiometricsFingerprint.h",
+        "android/hardware/biometrics/fingerprint/2.1/BnBiometricsFingerprint.h",
+        "android/hardware/biometrics/fingerprint/2.1/BpBiometricsFingerprint.h",
+        "android/hardware/biometrics/fingerprint/2.1/BsBiometricsFingerprint.h",
+        "android/hardware/biometrics/fingerprint/2.1/IBiometricsFingerprintClientCallback.h",
+        "android/hardware/biometrics/fingerprint/2.1/IHwBiometricsFingerprintClientCallback.h",
+        "android/hardware/biometrics/fingerprint/2.1/BnBiometricsFingerprintClientCallback.h",
+        "android/hardware/biometrics/fingerprint/2.1/BpBiometricsFingerprintClientCallback.h",
+        "android/hardware/biometrics/fingerprint/2.1/BsBiometricsFingerprintClientCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.biometrics.fingerprint@2.1",
+    generated_sources: ["android.hardware.biometrics.fingerprint@2.1_genc++"],
+    generated_headers: ["android.hardware.biometrics.fingerprint@2.1_genc++_headers"],
+    export_generated_headers: ["android.hardware.biometrics.fingerprint@2.1_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/biometrics/fingerprint/2.1/IBiometricsFingerprint.hal b/biometrics/fingerprint/2.1/IBiometricsFingerprint.hal
new file mode 100644 (file)
index 0000000..3b24a2c
--- /dev/null
@@ -0,0 +1,164 @@
+/*
+ * 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 android.hardware.biometrics.fingerprint@2.1;
+
+import IBiometricsFingerprintClientCallback;
+
+interface IBiometricsFingerprint {
+  /*
+   * Set notification callback:
+   * Registers a user function that must receive notifications from the HAL
+   * This call must block if the HAL state machine is in busy state until HAL
+   * leaves the busy state.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   */
+  @callflow(next={"setActiveGroup"})
+  @entry
+  setNotify(IBiometricsFingerprintClientCallback clientCallback)
+      generates (RequestStatus debugErrno);
+
+  /*
+   * Fingerprint pre-enroll enroll request:
+   * Generates a unique token to upper layers to indicate the start of
+   * an enrollment transaction. pre-enroll and post-enroll specify
+   * a pin/password cleared time window where enrollment is allowed.
+   * Pre-enroll only generates a challenge, a full hardwareAuthToken is
+   * generated by trustzone after verifying a pin/password/swipe. This is to
+   * ensure adding a new fingerprint template was preceded by some kind of
+   * credential confirmation (e.g. device password).
+   *
+   * @return 0 if function failed, a uint64_t of challenge otherwise.
+   */
+  @callflow(next={"enroll", "postEnroll"})
+  preEnroll() generates (uint64_t authChallenge);
+
+  /*
+   * Fingerprint enroll request:
+   * Switches the HAL state machine to collect and store a new fingerprint
+   * template. Switches back as soon as enroll is complete, signalled by
+   * (fingerprintMsg.type == FINGERPRINT_TEMPLATE_ENROLLING &&
+   *  fingerprintMsg.data.enroll.samplesRemaining == 0)
+   * or after timeoutSec seconds.
+   * The fingerprint template must be assigned to the group gid.
+   *
+   * @param hat a valid Hardware Authentication Token (HAT), generated
+   * as a result of a preEnroll() call.
+   * @param gid a framework defined fingerprint set (group) id.
+   * @param timeoutSec a timeout in seconds.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   *
+   * A notify() function may be called with a more detailed error structure.
+   */
+  @callflow(next={"cancel", "enroll", "postEnroll", "remove"})
+  enroll(uint8_t[69] hat, uint32_t gid, uint32_t timeoutSec)
+      generates (RequestStatus debugErrno);
+
+  /*
+   * Finishes the enroll operation and invalidates the preEnroll() generated
+   * challenge. This must be called at the end of a multi-finger enrollment
+   * session to indicate that no more fingers may be added.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   */
+  @callflow(next={"authenticate", "setActiveGroup", "enumerate", "remove"})
+  postEnroll() generates (RequestStatus debugErrno);
+
+  /*
+   * getAuthenticatorId:
+   * Returns a token associated with the current fingerprint set. This value
+   * must change whenever a new fingerprint is enrolled, thus creating a new
+   * fingerprint set.
+   *
+   * @return getAuthenticatorIdRet current authenticator id, 0 if function
+   * failed.
+   */
+  @callflow(next={"authenticate"})
+  getAuthenticatorId() generates (uint64_t AuthenticatorId);
+
+  /*
+   * Cancel pending enroll or authenticate, sending FINGERPRINT_ERROR_CANCELED
+   * to all running clients. Switches the HAL state machine back to the idle
+   * state. Unlike enrollDone() doesn't invalidate the preEnroll() challenge.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   */
+  @callflow(next={"authenticate", "enroll", "enumerate", "remove",
+    "setActiveGroup"})
+  cancel() generates (RequestStatus debugErrno);
+
+  /*
+   * Enumerate all the fingerprint templates found in the directory set by
+   * setActiveGroup():
+   * For each template found a notify() must be called with:
+   * fingerprintMsg.type == FINGERPRINT_TEMPLATE_ENUMERATED
+   * fingerprintMsg.data.enumerated.finger indicating a template id
+   * fingerprintMsg.data.enumerated.remainingTemplates indicating how many more
+   * enumeration messages to expect.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   */
+  @callflow(next={"remove", "enroll", "authenticate", "setActiveGroup"})
+  enumerate() generates (RequestStatus debugErrno);
+
+  /*
+   * Fingerprint remove request:
+   * Deletes fingerprint template(s).
+   * Works only within the path set by setActiveGroup().
+   * For each template found a notify() must be called with:
+   * fingerprintMsg.type == FINGERPRINT_TEMPLATE_REMOVED
+   * fingerprintMsg.data.removed.finger indicating the template id deleted
+   * fingerprintMsg.data.removed.remainingTemplates indicating how many more
+   * templates must be deleted by this operation.
+   *
+   * @param gid group id must match the last group set by setActiveGroup().
+   * @param fid template id to delete or 0 to delete all templates within the
+   * current group.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   */
+  @callflow(next={"enumerate", "authenticate", "cancel", "getAuthenticatorId",
+    "setActiveGroup"})
+  remove(uint32_t gid, uint32_t fid) generates (RequestStatus debugErrno);
+
+  /*
+   * Restricts the HAL operation to a set of fingerprints belonging to a group
+   * provided. The caller must provide a path to a storage location within the
+   * user's data directory.
+   *
+   * @param gid the fingerprint group (set) id.
+   * @param storePath filesystem path to the template storage directory.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   */
+  @callflow(next={"authenticate", "preEnroll", "enumerate", "remove"})
+  setActiveGroup(uint32_t gid, string storePath)
+      generates (RequestStatus debugErrno);
+
+  /*
+   * Authenticates an operation identified by operationId
+   *
+   * @param operationId operation id.
+   * @param gid fingerprint group id.
+   *
+   * @return debugErrno is a value the framework logs in case it is not 0.
+   */
+  @callflow(next={"cancel", "preEnroll", "remove"})
+  authenticate(uint64_t operationId, uint32_t gid)
+      generates (RequestStatus debugErrno);
+};
diff --git a/biometrics/fingerprint/2.1/IBiometricsFingerprintClientCallback.hal b/biometrics/fingerprint/2.1/IBiometricsFingerprintClientCallback.hal
new file mode 100644 (file)
index 0000000..839bcd6
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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 android.hardware.biometrics.fingerprint@2.1;
+
+interface IBiometricsFingerprintClientCallback {
+    /* This function is the response channel for all messages
+     * coming from the fingerprint HAL to the framework
+     *
+     * @param msg a union of message structures identified by
+     * FingerprintMsg.type
+     */
+    oneway notify(FingerprintMsg msg);
+};
diff --git a/biometrics/fingerprint/2.1/default/Android.mk b/biometrics/fingerprint/2.1/default/Android.mk
new file mode 100644 (file)
index 0000000..be8bae6
--- /dev/null
@@ -0,0 +1,17 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.biometrics.fingerprint@2.1-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    BiometricsFingerprint.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libhidl \
+    libhardware \
+    libhwbinder \
+    libutils \
+    android.hardware.biometrics.fingerprint@2.1 \
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp b/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp
new file mode 100644 (file)
index 0000000..1316686
--- /dev/null
@@ -0,0 +1,168 @@
+/*
+ * 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.
+ */
+#define LOG_TAG "android.hardware.biometrics.fingerprint@2.1-impl"
+
+#include <hardware/hardware.h>
+#include <hardware/fingerprint.h>
+#include "BiometricsFingerprint.h"
+
+namespace android {
+namespace hardware {
+namespace biometrics {
+namespace fingerprint {
+namespace V2_1 {
+namespace implementation {
+
+using RequestStatus =
+        android::hardware::biometrics::fingerprint::V2_1::RequestStatus;
+
+sp<IBiometricsFingerprintClientCallback>
+    BiometricsFingerprint::mClientCallback = nullptr;
+
+BiometricsFingerprint::BiometricsFingerprint(fingerprint_device_t *device)
+    : mDevice(device) {}
+
+BiometricsFingerprint::~BiometricsFingerprint() {
+    ALOG(LOG_VERBOSE, LOG_TAG, "nativeCloseHal()\n");
+    if (mDevice == NULL) {
+        ALOGE("No valid device");
+        return;
+    }
+    int err;
+    if (0 != (err = mDevice->common.close(
+            reinterpret_cast<hw_device_t*>(mDevice)))) {
+        ALOGE("Can't close fingerprint module, error: %d", err);
+        return;
+    }
+    mDevice = NULL;
+}
+
+Return<RequestStatus> BiometricsFingerprint::ErrorFilter(int32_t error) {
+    switch(error) {
+        case 0: return RequestStatus::SYS_OK;
+        case -2: return RequestStatus::SYS_ENOENT;
+        case -4: return RequestStatus::SYS_EINTR;
+        case -5: return RequestStatus::SYS_EIO;
+        case -11: return RequestStatus::SYS_EAGAIN;
+        case -12: return RequestStatus::SYS_ENOMEM;
+        case -13: return RequestStatus::SYS_EACCES;
+        case -14: return RequestStatus::SYS_EFAULT;
+        case -16: return RequestStatus::SYS_EBUSY;
+        case -22: return RequestStatus::SYS_EINVAL;
+        case -28: return RequestStatus::SYS_ENOSPC;
+        case -110: return RequestStatus::SYS_ETIMEDOUT;
+        default:
+            ALOGE("An unknown error returned from fingerprint vendor library");
+            return RequestStatus::SYS_UNKNOWN;
+    }
+}
+
+Return<RequestStatus> BiometricsFingerprint::setNotify(
+        const sp<IBiometricsFingerprintClientCallback>& clientCallback) {
+    mClientCallback = clientCallback;
+    return RequestStatus::SYS_OK;
+}
+
+Return<uint64_t> BiometricsFingerprint::preEnroll()  {
+    return mDevice->pre_enroll(mDevice);
+}
+
+Return<RequestStatus> BiometricsFingerprint::enroll(const hidl_array<uint8_t, 69>& hat,
+        uint32_t gid, uint32_t timeoutSec) {
+    const hw_auth_token_t* authToken =
+        reinterpret_cast<const hw_auth_token_t*>(hat.data());
+    return ErrorFilter(mDevice->enroll(mDevice, authToken, gid, timeoutSec));
+}
+
+Return<RequestStatus> BiometricsFingerprint::postEnroll() {
+    return ErrorFilter(mDevice->post_enroll(mDevice));
+}
+
+Return<uint64_t> BiometricsFingerprint::getAuthenticatorId() {
+    return mDevice->get_authenticator_id(mDevice);
+}
+
+Return<RequestStatus> BiometricsFingerprint::cancel() {
+    return ErrorFilter(mDevice->cancel(mDevice));
+}
+
+Return<RequestStatus> BiometricsFingerprint::enumerate()  {
+    return ErrorFilter(mDevice->enumerate(mDevice));
+}
+
+Return<RequestStatus> BiometricsFingerprint::remove(uint32_t gid, uint32_t fid) {
+    return ErrorFilter(mDevice->remove(mDevice, gid, fid));
+}
+
+Return<RequestStatus> BiometricsFingerprint::setActiveGroup(uint32_t gid,
+        const hidl_string& storePath) {
+    if (storePath.size() >= PATH_MAX || storePath.size() <= 0) {
+        ALOGE("Bad path length: %zd", storePath.size());
+    }
+    return ErrorFilter(mDevice->set_active_group(mDevice, gid,
+                                                    storePath.c_str()));
+}
+
+Return<RequestStatus> BiometricsFingerprint::authenticate(uint64_t operationId,
+        uint32_t gid) {
+    return ErrorFilter(mDevice->authenticate(mDevice, operationId, gid));
+}
+
+IBiometricsFingerprint* HIDL_FETCH_IBiometricsFingerprint(const char*) {
+    int err;
+    const hw_module_t *hw_mdl = NULL;
+    ALOGE("Opening fingerprint hal library...");
+    if (0 != (err = hw_get_module(FINGERPRINT_HARDWARE_MODULE_ID, &hw_mdl))) {
+        ALOGE("Can't open fingerprint HW Module, error: %d", err);
+        return nullptr;
+    }
+    if (hw_mdl == NULL) {
+        ALOGE("No valid fingerprint module");
+        return nullptr;
+    }
+
+    fingerprint_module_t const *module =
+        reinterpret_cast<const fingerprint_module_t*>(hw_mdl);
+    if (module->common.methods->open == NULL) {
+        ALOGE("No valid open method");
+        return nullptr;
+    }
+
+    hw_device_t *device = NULL;
+
+    if (0 != (err = module->common.methods->open(hw_mdl, NULL, &device))) {
+        ALOGE("Can't open fingerprint methods, error: %d", err);
+        return nullptr;
+    }
+
+    fingerprint_device_t* fp_device =
+        reinterpret_cast<fingerprint_device_t*>(device);
+
+    if (0 != (err =
+            fp_device->set_notify(fp_device, BiometricsFingerprint::notify))) {
+        ALOGE("Can't register fingerprint module callback, error: %d", err);
+        return nullptr;
+    }
+
+    return new BiometricsFingerprint(fp_device);
+}
+
+} // namespace implementation
+}  // namespace V2_1
+}  // namespace fingerprint
+}  // namespace biometrics
+}  // namespace hardware
+}  // namespace android
diff --git a/biometrics/fingerprint/2.1/default/BiometricsFingerprint.h b/biometrics/fingerprint/2.1/default/BiometricsFingerprint.h
new file mode 100644 (file)
index 0000000..de8727b
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_HARDWARE_BIOMETRICS_FINGERPRINT_V2_1_BIOMETRICSFINGERPRINT_H
+#define ANDROID_HARDWARE_BIOMETRICS_FINGERPRINT_V2_1_BIOMETRICSFINGERPRINT_H
+
+#include <utils/Log.h>
+#include <hidl/MQDescriptor.h>
+#include <android/hardware/biometrics/fingerprint/2.1/IBiometricsFingerprint.h>
+#include <hidl/Status.h>
+
+namespace android {
+namespace hardware {
+namespace biometrics {
+namespace fingerprint {
+namespace V2_1 {
+namespace implementation {
+
+using ::android::hardware::biometrics::fingerprint::V2_1::IBiometricsFingerprint;
+using ::android::hardware::biometrics::fingerprint::V2_1::IBiometricsFingerprintClientCallback;
+using ::android::hardware::biometrics::fingerprint::V2_1::RequestStatus;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct BiometricsFingerprint : public IBiometricsFingerprint {
+public:
+    BiometricsFingerprint(fingerprint_device_t *device);
+    ~BiometricsFingerprint();
+    // Methods from ::android::hardware::biometrics::fingerprint::V2_1::IBiometricsFingerprint follow.
+    Return<RequestStatus> setNotify(const sp<IBiometricsFingerprintClientCallback>& clientCallback) override;
+    Return<uint64_t> preEnroll() override;
+    Return<RequestStatus> enroll(const hidl_array<uint8_t, 69>& hat, uint32_t gid, uint32_t timeoutSec) override;
+    Return<RequestStatus> postEnroll() override;
+    Return<uint64_t> getAuthenticatorId() override;
+    Return<RequestStatus> cancel() override;
+    Return<RequestStatus> enumerate() override;
+    Return<RequestStatus> remove(uint32_t gid, uint32_t fid) override;
+    Return<RequestStatus> setActiveGroup(uint32_t gid, const hidl_string& storePath) override;
+    Return<RequestStatus> authenticate(uint64_t operationId, uint32_t gid) override;
+    static void notify(const fingerprint_msg_t *notify_msg) {
+        if (mClientCallback == nullptr) {
+            ALOGE("Receiving callbacks before the client callback is registered.");
+            return;
+        }
+        FingerprintMsg msg = {};
+        memcpy(&msg, notify_msg, sizeof(msg));
+        mClientCallback->notify(msg);
+    }
+private:
+    Return<RequestStatus> ErrorFilter(int32_t error);
+    static sp<IBiometricsFingerprintClientCallback> mClientCallback;
+    fingerprint_device_t *mDevice;
+};
+
+extern "C" IBiometricsFingerprint* HIDL_FETCH_IBiometricsFingerprint(const char* name);
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace fingerprint
+}  // namespace biometrics
+}  // namespace hardware
+}  // namespace android
+
+#endif  // ANDROID_HARDWARE_BIOMETRICS_FINGERPRINT_V2_1_BIOMETRICSFINGERPRINT_H
diff --git a/biometrics/fingerprint/2.1/default/android.hardware.biometrics.fingerprint@2.1-service.rc b/biometrics/fingerprint/2.1/default/android.hardware.biometrics.fingerprint@2.1-service.rc
new file mode 100644 (file)
index 0000000..741024d
--- /dev/null
@@ -0,0 +1,4 @@
+service fingerprint@2.1 /system/bin/hw/android.hardware.biometrics.fingerprint@2.1-service
+    class hal
+    user system
+    group system
\ No newline at end of file
diff --git a/biometrics/fingerprint/2.1/default/service.cpp b/biometrics/fingerprint/2.1/default/service.cpp
new file mode 100644 (file)
index 0000000..9867039
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.biometrics.fingerprint@2.1-service"
+
+#include <android/hardware/biometrics/fingerprint/2.1/IBiometricsFingerprint.h>
+
+#include <hidl/LegacySupport.h>
+
+using android::hardware::biometrics::fingerprint::V2_1::IBiometricsFingerprint;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IBiometricsFingerprint>("fingerprint");
+}
diff --git a/biometrics/fingerprint/2.1/types.hal b/biometrics/fingerprint/2.1/types.hal
new file mode 100644 (file)
index 0000000..201ec7c
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * 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 android.hardware.biometrics.fingerprint@2.1;
+
+/*
+ * Request status indicates whether the request is accepted by the vendor
+ * implementation or not. These values are taken from the errno set,
+ * except for the SYS_UNKNOWN
+ */
+enum RequestStatus : int32_t {
+  SYS_UNKNOWN = 1,
+  SYS_OK = 0,
+  SYS_ENOENT = -2,
+  SYS_EINTR = -4,
+  SYS_EIO = -5,
+  SYS_EAGAIN = -11,
+  SYS_ENOMEM = -12,
+  SYS_EACCES = -13,
+  SYS_EFAULT = -14,
+  SYS_EBUSY = -16,
+  SYS_EINVAL = -22,
+  SYS_ENOSPC = -28,
+  SYS_ETIMEDOUT = -110,
+};
+
+/*
+ * Fingerprint errors are meant to tell the framework to terminate the current
+ * operation and ask for the user to correct the situation. These will almost
+ * always result in messaging and user interaction to correct the problem.
+ *
+ * For example, ERROR_CANCELED should follow any acquisition message that
+ * results in a situation where the current operation can't continue without
+ * user interaction. For example, if the sensor is dirty during enrollment and
+ * no further enrollment progress can be made, send ACQUIRED_IMAGER_DIRTY
+ * followed by ERROR_CANCELED.
+ */
+enum FingerprintError : int32_t {
+  /* The hardware has an error that can't be resolved. */
+  ERROR_HW_UNAVAILABLE = 1,
+  /* Bad data; operation can't continue */
+  ERROR_UNABLE_TO_PROCESS = 2,
+  /* The operation has timed out waiting for user input. */
+  ERROR_TIMEOUT = 3,
+  /* No space available to store a template */
+  ERROR_NO_SPACE = 4,
+  /* The current operation has been canceled */
+  ERROR_CANCELED = 5,
+  /* Unable to remove a template */
+  ERROR_UNABLE_TO_REMOVE = 6,
+};
+
+/*
+ * Fingerprint acquisition info is meant as feedback for the current operation.
+ * Anything but ACQUIRED_GOOD must be shown to the user as feedback on how to
+ * take action on the current operation. For example, ACQUIRED_IMAGER_DIRTY may
+ * be used to tell the user to clean the sensor if it is detected to be dirty.
+ * If this causes the current operation to fail, an additional ERROR_CANCELED
+ * must be sent to stop the operation in progress (e.g. enrollment).
+ * In general, these messages will result in a "Try again" message.
+ */
+enum FingerprintAcquiredInfo : int32_t {
+  ACQUIRED_GOOD = 0,
+  /* sensor needs more data, i.e. longer swipe. */
+  ACQUIRED_PARTIAL = 1,
+  /* image doesn't contain enough detail for recognition*/
+  ACQUIRED_INSUFFICIENT = 2,
+  /* sensor needs to be cleaned */
+  ACQUIRED_IMAGER_DIRTY = 3,
+  /* mostly swipe-type sensors; not enough data collected */
+  ACQUIRED_TOO_SLOW = 4,
+  /* vendor-specific acquisition messages start here */
+  ACQUIRED_TOO_FAST = 5,
+  ACQUIRED_VENDOR_BASE = 1000,
+};
+
+struct FingerprintFingerId {
+  /* Group ID */
+  uint32_t gid;
+  /* Fingerprint template ID */
+  uint32_t fid;
+};
+
+struct FingerprintEnroll {
+  /* Template ID */
+  FingerprintFingerId finger;
+  /* samplesRemaining goes from N (no data collected, but N scans needed)
+   * to 0 (no more data is needed to build a template). */
+  uint32_t samplesRemaining;
+  /* Vendor specific message. Used for user guidance */
+  uint64_t msg;
+};
+
+struct FingerprintIterator {
+  /* Template ID */
+  FingerprintFingerId finger;
+  /* How many templates remain to iterate through */
+  uint32_t remainingTemplates;
+};
+
+typedef FingerprintIterator FingerprintEnumerated;
+typedef FingerprintIterator FingerprintRemoved;
+
+struct FingerprintAcquired {
+  /* information about the image */
+  FingerprintAcquiredInfo acquiredInfo;
+};
+
+struct FingerprintAuthenticated {
+  /* Matched template ID */
+  FingerprintFingerId finger;
+  /* Authentication result from the keymaster */
+  uint8_t[69] hat;
+};
+
+/* Run time type identification for the notify() call payload. */
+enum FingerprintMsgType : int32_t {
+  ERROR = -1,
+  ACQUIRED = 1,
+  TEMPLATE_ENROLLING = 3,
+  TEMPLATE_REMOVED = 4,
+  AUTHENTICATED = 5,
+  TEMPLATE_ENUMERATING = 6,
+};
+
+struct FingerprintMsg {
+  /* Selects the payload below */
+  FingerprintMsgType type;
+  union Data {
+    FingerprintError error;
+    FingerprintEnroll enroll;
+    FingerprintEnumerated enumerated;
+    FingerprintRemoved removed;
+    FingerprintAcquired acquired;
+    FingerprintAuthenticated authenticated;
+  } data;
+};
diff --git a/boot/1.0/vts/Android.mk b/boot/1.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..16b92c1
--- /dev/null
@@ -0,0 +1,86 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for Boot Control v1.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_boot@1.0
+
+LOCAL_SRC_FILES := \
+  BootControl.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES := \
+  android.hardware.boot@1.0\
+  system/core/base/include \
+  system/core/include \
+
+LOCAL_SHARED_LIBRARIES += \
+  android.hardware.boot@1.0 \
+  libbase \
+  libutils \
+  libcutils \
+  liblog \
+  libhidl \
+  libhwbinder \
+  libprotobuf-cpp-full \
+  libvts_common \
+  libvts_datatype \
+  libvts_measurement \
+  libvts_multidevice_proto \
+
+LOCAL_CFLAGS += -DENABLE_TREBLE
+
+LOCAL_STATIC_LIBRARIES := \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for boot.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_boot@1.0
+
+LOCAL_SRC_FILES := \
+  BootControl.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.boot@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/boot/1.0/vts/BootControl.vts b/boot/1.0/vts/BootControl.vts
new file mode 100644 (file)
index 0000000..384ae50
--- /dev/null
@@ -0,0 +1,93 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "IBootControl"
+
+package: "android.hardware.boot"
+
+import: "android.hardware.boot@1.0::types"
+
+interface: {
+    api: {
+        name: "getNumberSlots"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+    api: {
+        name: "getCurrentSlot"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+    api: {
+        name: "markBootSuccessful"
+        return_type_hidl: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::boot::V1_0::CommandResult"
+        }
+    }
+
+    api: {
+        name: "setActiveBootSlot"
+        return_type_hidl: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::boot::V1_0::CommandResult"
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+    api: {
+        name: "setSlotAsUnbootable"
+        return_type_hidl: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::boot::V1_0::CommandResult"
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+    api: {
+        name: "isSlotBootable"
+        return_type_hidl: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::boot::V1_0::BoolResult"
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+    api: {
+        name: "isSlotMarkedSuccessful"
+        return_type_hidl: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::boot::V1_0::BoolResult"
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+    api: {
+        name: "getSuffix"
+        return_type_hidl: {
+            type: TYPE_STRING
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+}
diff --git a/boot/1.0/vts/types.vts b/boot/1.0/vts/types.vts
new file mode 100644 (file)
index 0000000..ebeaa60
--- /dev/null
@@ -0,0 +1,42 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "types"
+
+package: "android.hardware.boot"
+
+
+attribute: {
+    name: "::android::hardware::boot::V1_0::CommandResult"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "success"
+        type: TYPE_SCALAR
+        scalar_type: "bool_t"
+    }
+    struct_value: {
+        name: "errMsg"
+        type: TYPE_STRING
+    }
+}
+
+attribute: {
+    name: "::android::hardware::boot::V1_0::BoolResult"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "FALSE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "TRUE"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "INVALID_SLOT"
+        scalar_value: {
+            int32_t: -1
+        }
+    }
+}
+
diff --git a/broadcastradio/1.0/Android.bp b/broadcastradio/1.0/Android.bp
new file mode 100644 (file)
index 0000000..c337e08
--- /dev/null
@@ -0,0 +1,75 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.broadcastradio@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.broadcastradio@1.0",
+    srcs: [
+        "types.hal",
+        "IBroadcastRadio.hal",
+        "IBroadcastRadioFactory.hal",
+        "ITuner.hal",
+        "ITunerCallback.hal",
+    ],
+    out: [
+        "android/hardware/broadcastradio/1.0/types.cpp",
+        "android/hardware/broadcastradio/1.0/BroadcastRadioAll.cpp",
+        "android/hardware/broadcastradio/1.0/BroadcastRadioFactoryAll.cpp",
+        "android/hardware/broadcastradio/1.0/TunerAll.cpp",
+        "android/hardware/broadcastradio/1.0/TunerCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.broadcastradio@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.broadcastradio@1.0",
+    srcs: [
+        "types.hal",
+        "IBroadcastRadio.hal",
+        "IBroadcastRadioFactory.hal",
+        "ITuner.hal",
+        "ITunerCallback.hal",
+    ],
+    out: [
+        "android/hardware/broadcastradio/1.0/types.h",
+        "android/hardware/broadcastradio/1.0/IBroadcastRadio.h",
+        "android/hardware/broadcastradio/1.0/IHwBroadcastRadio.h",
+        "android/hardware/broadcastradio/1.0/BnBroadcastRadio.h",
+        "android/hardware/broadcastradio/1.0/BpBroadcastRadio.h",
+        "android/hardware/broadcastradio/1.0/BsBroadcastRadio.h",
+        "android/hardware/broadcastradio/1.0/IBroadcastRadioFactory.h",
+        "android/hardware/broadcastradio/1.0/IHwBroadcastRadioFactory.h",
+        "android/hardware/broadcastradio/1.0/BnBroadcastRadioFactory.h",
+        "android/hardware/broadcastradio/1.0/BpBroadcastRadioFactory.h",
+        "android/hardware/broadcastradio/1.0/BsBroadcastRadioFactory.h",
+        "android/hardware/broadcastradio/1.0/ITuner.h",
+        "android/hardware/broadcastradio/1.0/IHwTuner.h",
+        "android/hardware/broadcastradio/1.0/BnTuner.h",
+        "android/hardware/broadcastradio/1.0/BpTuner.h",
+        "android/hardware/broadcastradio/1.0/BsTuner.h",
+        "android/hardware/broadcastradio/1.0/ITunerCallback.h",
+        "android/hardware/broadcastradio/1.0/IHwTunerCallback.h",
+        "android/hardware/broadcastradio/1.0/BnTunerCallback.h",
+        "android/hardware/broadcastradio/1.0/BpTunerCallback.h",
+        "android/hardware/broadcastradio/1.0/BsTunerCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.broadcastradio@1.0",
+    generated_sources: ["android.hardware.broadcastradio@1.0_genc++"],
+    generated_headers: ["android.hardware.broadcastradio@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.broadcastradio@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/broadcastradio/1.0/IBroadcastRadio.hal b/broadcastradio/1.0/IBroadcastRadio.hal
new file mode 100644 (file)
index 0000000..c7fe62d
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * 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 android.hardware.broadcastradio@1.0;
+
+import ITunerCallback;
+import ITuner;
+
+interface IBroadcastRadio {
+
+    /*
+     * Retrieve implementation properties.
+     * @return result Operation completion status: OK in case of success,
+     *                NOT_INITIALIZED in case of initialization error.
+     * @return properties A Properties structure containing implementation
+     *                    description and capabilities.
+     */
+    getProperties() generates (Result result, Properties properties);
+
+    /*
+     * Open a tuner interface for the requested configuration.
+     * If no other tuner is opened, this will power on the radio hardware.
+     * The hardware must be powered down when all tuner interface are released.
+     * @param config A BandConfig struct containing the band configuration to apply
+     * @param audio True if this tuner must be used for live radio listening and
+     *              should be connected to the radio audio source.
+     * @param callback the callback interface
+     * @return result Operation completion status: OK in case of success,
+     *                INVALID_ARGUMENTS if configuration requested is invalid,
+     *                INVALID_STATE if called out of sequence
+     * @return tuner The interface to control the tuner
+     *
+     * Callback ITunerCallback.ConfigChanged MUST be called once the
+     * configuration is applied or a failure occurs or after a time out.
+     */
+    openTuner(BandConfig config, bool audio, ITunerCallback callback)
+                generates (Result result, ITuner tuner);
+};
diff --git a/broadcastradio/1.0/IBroadcastRadioFactory.hal b/broadcastradio/1.0/IBroadcastRadioFactory.hal
new file mode 100644 (file)
index 0000000..82a97c4
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * 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 android.hardware.broadcastradio@1.0;
+
+import IBroadcastRadio;
+
+interface IBroadcastRadioFactory {
+
+    /*
+     * Connects to a broadcast radio HAL module for a given class
+     * (AM/FM, Satellite, DAB).
+     *
+     * @param classId Class of the module to connect to .
+     * @return retval operation completion status. Returns INVALID_ARGUMENTS
+     *         if there is no corresponding hardware module found,
+     *         NOT_INITIALIZED if an error occurred while opening the hardware
+     *         module.
+     * @return result the interface for the created module.
+     */
+    connectModule(Class classId)
+      generates (Result retval, IBroadcastRadio result);
+};
diff --git a/broadcastradio/1.0/ITuner.hal b/broadcastradio/1.0/ITuner.hal
new file mode 100644 (file)
index 0000000..5e2bffe
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.broadcastradio@1.0;
+
+import ITunerCallback;
+
+interface ITuner {
+
+    /*
+     * Apply current radio band configuration (band, range, channel spacing...).
+     * Automatically cancels pending scan, step or tune.
+     * ITunerCallback.configChange() method MUST be called once the
+     * configuration is applied or a failure occurs or after a time out.
+     * @param config The band configuration to apply.
+     * @return result OK if configuration could be applied
+     *                NOT_INITIALIZED in case of initialization error.
+     *                INVALID_ARGUMENTS if configuration requested is invalid
+     *
+     */
+    setConfiguration(BandConfig config) generates(Result result);
+
+    /*
+     * Retrieve current radio band configuration.
+     * @return result OK if valid configuration is returned,
+     *                NOT_INITIALIZED in case of initialization error.
+     * @param config Current band configuration
+     */
+    getConfiguration() generates(Result result, BandConfig config);
+
+    /*
+     * Start scanning up to next valid station.
+     * Shall be called only when a valid configuration has been applied.
+     * Automatically cancels pending scan, step or tune.
+     * ITunerCallback.tuneComplete() MUST be called once locked on a station
+     * or after a time out or full band scan if no station found.
+     * The status should indicate if a valid station is tuned or not.
+     * @param direction UP or DOWN.
+     * @param skipSubChannel valid for HD radio or digital radios only:
+     *                       ignore sub channels (e.g SPS for HD radio).
+     * @return result OK if scan successfully started
+     *                INVALID_STATE if called out of sequence
+     *                NOT_INITIALIZED if another error occurs
+     */
+    scan(Direction direction, bool skipSubChannel) generates(Result result);
+
+    /*
+     * Move one channel spacing up or down.
+     * Must be called when a valid configuration has been applied.
+     * Automatically cancels pending scan, step or tune.
+     * ITunerCallback.tuneComplete() MUST be called once locked on a station
+     * or after a time out or full band scan if no station found.
+     * The status should indicate if a valid station is tuned or not.
+     * @param direction UP or DOWN.
+     * @param skipSubChannel valid for HD radio or digital radios only:
+     *                       ignore sub channels (e.g SPS for HD radio).
+     * @return result OK if scan successfully started
+     *                INVALID_STATE if called out of sequence
+     *                NOT_INITIALIZED if another error occurs
+     */
+    step(Direction direction, bool skipSubChannel) generates(Result result);
+
+    /*
+     * Tune to specified channel.
+     * Must be called when a valid configuration has been applied.
+     * Automatically cancels pending scan, step or tune.
+     * ITunerCallback.tuneComplete() MUST be called once locked on a station
+     * or after a time out or full band scan if no station found.
+     * The status should indicate if a valid station is tuned or not.
+     * @param channel Channel to tune to. A frequency in kHz for AM/FM/HD Radio
+     *                bands.
+     * @param subChannel Valid for HD radio or digital radios only
+     *                   (e.g SPS number for HD radio)..
+     * @return result OK if scan successfully started
+     *                INVALID_ARGUMENTS if invalid arguments are passed
+     *                INVALID_STATE if called out of sequence
+     *                NOT_INITIALIZED if another error occurs
+     */
+    tune(uint32_t channel, uint32_t subChannel) generates(Result result);
+
+    /*
+     * Cancel a scan, step or tune operation.
+     * Shall be called only while a scan, step or tune operation is pending.
+     * ITunerCallback.tuneComplete() MUST NOT be sent by the HAL.
+     * @return result OK if scan successfully started
+     *                INVALID_STATE if called out of sequence
+     *                NOT_INITIALIZED if another error occurs
+     */
+    cancel() generates(Result result);
+
+    /*
+     * Retrieve current station information.
+     * @param withMetadata True if Metadata should be returned, false otherwise.
+     * @return result OK if scan successfully started
+     *                NOT_INITIALIZED if another error occurs
+     * @return info Current program information.
+     */
+    getProgramInformation(bool withMetadata)
+            generates(Result result, ProgramInfo info);
+};
diff --git a/broadcastradio/1.0/ITunerCallback.hal b/broadcastradio/1.0/ITunerCallback.hal
new file mode 100644 (file)
index 0000000..f805472
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * 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 android.hardware.broadcastradio@1.0;
+
+
+interface ITunerCallback {
+
+    /*
+     * Method called by the HAL when a HW failure occurs.
+     * The framework MUST close the ITuner interface and open a new one.
+     */
+    oneway hardwareFailure();
+
+    /*
+     * Method called by the HAL when a new configuration is applied
+     * in response to IDevice.openTuner() or ITuner.setConfiguration().
+     * @param result OK if the configuration has been applied,
+     *               INVALID_ARGUMENTS if not or TIMEOUT in case of time out.
+     * @param config A BandConfig structure describing the new configuration
+     *               applied.
+     */
+    oneway configChange(Result result, BandConfig config);
+
+    /*
+     * Method called by the HAL when a tuning operation completes
+     * following a step(), scan() or tune() command.
+     * @param result OK if tune succeeded or TIMEOUT in case of time out.
+     * @param info A ProgramInfo structure describing the tuned station.
+     */
+    oneway tuneComplete(Result result, ProgramInfo info);
+
+    /*
+     * Method called by the HAL when a frequency switch occurs.
+     * @param info A ProgramInfo structure describing the new tuned station.
+     */
+    oneway afSwitch(ProgramInfo info);
+
+    /*
+     * Method called by the HAL when the antenna connection state changes.
+     * @param connected True if the antenna is connected, false otherwise.
+     */
+    oneway antennaStateChange(bool connected);
+
+    /*
+     * Method called by the HAL when a traffic announcement starts or
+     * stops.
+     * @param active True if the announcement starts, false if it stops.
+     */
+    oneway trafficAnnouncement(bool active);
+
+    /*
+     * Method called by the HAL when an emergency announcement starts
+     * or stops.
+     * @param active True if the announcement starts, false if it stops.
+     */
+    oneway emergencyAnnouncement(bool active);
+
+    /*
+     * Method called by the HAL when metadata for current station
+     * are updated.
+     * @param metadatas A list of all updated metada.
+     */
+    oneway newMetadata(vec<MetaData>  metadatas);
+};
\ No newline at end of file
diff --git a/broadcastradio/1.0/types.hal b/broadcastradio/1.0/types.hal
new file mode 100644 (file)
index 0000000..c5b4411
--- /dev/null
@@ -0,0 +1,216 @@
+/*
+ * Copyright 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 android.hardware.broadcastradio@1.0;
+
+enum Result {
+    OK,
+    NOT_INITIALIZED,
+    INVALID_ARGUMENTS,
+    INVALID_STATE,
+    TIMEOUT,
+};
+
+/*
+ * Radio hardware module class. A given radio hardware module HAL is of one
+ * class only. The platform can not have more than one hardware module of
+ * each class. Current version of the framework only supports RADIO_CLASS_AM_FM.
+ */
+enum Class : uint32_t {
+    /* FM (including HD radio) and AM */
+    AM_FM = 0,
+    /* Satellite Radio */
+    SAT   = 1,
+    /* Digital Radio (DAB) */
+    DT    = 2,
+};
+
+/* value for field "type" of radio band described in struct radio_hal_band_config */
+enum Band : uint32_t {
+    /* Amplitude Modulation band: LW, MW, SW */
+    AM     = 0,
+    /* Frequency Modulation band: FM */
+    FM     = 1,
+    /* FM HD Radio / DRM (IBOC) */
+    FM_HD  = 2,
+    /* AM HD Radio / DRM (IBOC) */
+    AM_HD  = 3,
+};
+
+/* RDS variant implemented. A struct FmBandConfig can list none or several. */
+enum Rds : uint32_t {
+    NONE   = 0,
+    WORLD  = (1<<0),
+    RDS_US = (1<<1),
+};
+
+
+/* FM deemphasis variant implemented.
+ * A struct FmBandConfig can list one or more. */
+enum Deemphasis : uint32_t {
+    D50   = (1<<0),
+    D75   = (1<<1),
+};
+
+/* Scanning direction for scan() and step() tuner APIs */
+enum Direction : uint32_t {
+    UP,
+    DOWN
+};
+
+/* Unique handle allocated to a radio module */
+typedef uint32_t Handle;
+
+
+/* Additional attributes for an FM band configuration */
+struct FmBandConfig {
+    /* deemphasis variant */
+    Deemphasis deemphasis;
+    /* stereo supported */
+    bool       stereo;
+    /* RDS variants supported */
+    Rds        rds;
+    /* Traffic Announcement supported */
+    bool       ta;
+    /* Alternate Frequency supported */
+    bool       af;
+    /* Emergency announcements supported */
+    bool       ea;
+};
+
+/* Additional attributes for an AM band configuration */
+struct AmBandConfig {
+    /* Stereo supported */
+    bool       stereo;
+};
+
+/* Radio band configuration. Describes a given band supported by the radio
+ * module. The HAL can expose only one band per type with the the maximum range
+ * supported and all options. The framework will derive the actual regions were
+ * this module can operate and expose separate band configurations for
+ * applications to chose from. */
+struct BandConfig {
+    Band type;
+    bool antennaConnected;
+    uint32_t lowerLimit;
+    uint32_t upperLimit;
+    vec<uint32_t> spacings;
+    union Ext {
+        FmBandConfig fm;
+        AmBandConfig am;
+    };
+};
+
+/* Exposes properties of a given hardware radio module.
+ * NOTE: current framework implementation supports only one audio source
+ * (num_audio_sources = 1). The source corresponds to AUDIO_DEVICE_IN_FM_TUNER.
+ * If more than one tuner is supported (num_tuners > 1), only one can be
+ * connected to the audio source. */
+struct Properties {
+    /* Class of this module. E.g AM_FM */
+    Class           classId;
+    /* implementor name */
+    string          implementor;
+    /* product name */
+    string          product;
+    /* product version */
+    string          version;
+    /* serial number (for subscription services) */
+    string          serial;
+    /* number of tuners controllable independently */
+    uint32_t        numTuners;
+    /* number of audio sources driven simultaneously */
+    uint32_t        numAudioSources;
+    /* the hardware supports capture of audio source from audio HAL */
+    bool            supportsCapture;
+    vec<BandConfig> bands; /* band descriptors */
+};
+
+enum MetadataType {
+    INVALID    = -1,
+    /* Signed 32 bit integer  */
+    INT        = 0,
+    /* String */
+    TEXT       = 1,
+    /* Raw binary data (icon or art)
+       This data must be transparent to the android framework */
+    RAW        = 2,
+    /* clock data, see MetaDataClock */
+    CLOCK      = 3,
+};
+
+enum MetadataKey {
+    INVALID      = -1,
+    /* RDS PI                 - string  */
+    RDS_PI       = 0,
+    /* RDS PS                 - string */
+    RDS_PS       = 1,
+    /* RDS PTY                - int32_t  */
+    RDS_PTY      = 2,
+    /* RBDS PTY               - int32_t  */
+    RBDS_PTY     = 3,
+    /* RDS RT                 - string  */
+    RDS_RT       = 4,
+    /* Song title             - string  */
+    TITLE        = 5,
+    /* Artist name            - string  */
+    ARTIST       = 6,
+    /* Album name             - string  */
+    ALBUM        = 7,
+    /* Musical genre          - string  */
+    GENRE        = 8,
+    /* Station icon           - raw  */
+    ICON         = 9,
+    /* Album art              - raw  */
+    ART          = 10,
+    /* Clock                  - MetaDataClock */
+    CLOCK        = 11,
+};
+
+struct MetaDataClock {
+     /* Seconds since epoch at GMT + 0. */
+    uint64_t utcSecondsSinceEpoch;
+    /* Minutes offset from the GMT. */
+    int32_t timezoneOffsetInMinutes;
+};
+
+struct MetaData {
+    MetadataType type;
+    MetadataKey key;
+    /* Value used for type MetadataType.INT */
+    int32_t intValue;
+    /* Value used for type MetadataType.CLOCK */
+    MetaDataClock  clockValue;
+    /* Value used for type MetadataType.TEXT */
+    string  stringValue;
+    /* Value used for type MetadataType.RAW */
+    vec<uint8_t> rawValue;
+};
+
+
+/* Radio program information. Returned by the HAL with event RADIO_EVENT_TUNED.
+ * Contains information on currently tuned channel.
+ */
+struct ProgramInfo {
+    uint32_t     channel;   /* current channel. (e.g kHz for band type AM_FM) */
+    uint32_t     subChannel; /* current sub channel. (FM_HD) */
+    bool         tuned;     /* tuned to a program or not */
+    bool         stereo;    /* program is stereo or not */
+    bool         digital;   /* digital program or not (e.g HD Radio program) */
+    uint32_t     signalStrength; /* signal strength from 0 to 100 */
+    vec<MetaData> metadata; /* non empty if meta data are present (e.g PTY, song title ...) */
+};
+
diff --git a/broadcastradio/Android.bp b/broadcastradio/Android.bp
new file mode 100644 (file)
index 0000000..bbb3e4b
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+]
diff --git a/contexthub/1.0/Android.bp b/contexthub/1.0/Android.bp
new file mode 100644 (file)
index 0000000..23c44de
--- /dev/null
@@ -0,0 +1,59 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.contexthub@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.contexthub@1.0",
+    srcs: [
+        "types.hal",
+        "IContexthub.hal",
+        "IContexthubCallback.hal",
+    ],
+    out: [
+        "android/hardware/contexthub/1.0/types.cpp",
+        "android/hardware/contexthub/1.0/ContexthubAll.cpp",
+        "android/hardware/contexthub/1.0/ContexthubCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.contexthub@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.contexthub@1.0",
+    srcs: [
+        "types.hal",
+        "IContexthub.hal",
+        "IContexthubCallback.hal",
+    ],
+    out: [
+        "android/hardware/contexthub/1.0/types.h",
+        "android/hardware/contexthub/1.0/IContexthub.h",
+        "android/hardware/contexthub/1.0/IHwContexthub.h",
+        "android/hardware/contexthub/1.0/BnContexthub.h",
+        "android/hardware/contexthub/1.0/BpContexthub.h",
+        "android/hardware/contexthub/1.0/BsContexthub.h",
+        "android/hardware/contexthub/1.0/IContexthubCallback.h",
+        "android/hardware/contexthub/1.0/IHwContexthubCallback.h",
+        "android/hardware/contexthub/1.0/BnContexthubCallback.h",
+        "android/hardware/contexthub/1.0/BpContexthubCallback.h",
+        "android/hardware/contexthub/1.0/BsContexthubCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.contexthub@1.0",
+    generated_sources: ["android.hardware.contexthub@1.0_genc++"],
+    generated_headers: ["android.hardware.contexthub@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.contexthub@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/contexthub/1.0/Android.mk b/contexthub/1.0/Android.mk
new file mode 100644 (file)
index 0000000..72291e6
--- /dev/null
@@ -0,0 +1,552 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.contexthub@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (AsyncEventType)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/AsyncEventType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.AsyncEventType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ContextHub)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/ContextHub.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.ContextHub
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ContextHubMsg)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/ContextHubMsg.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.ContextHubMsg
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HubAppInfo)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/HubAppInfo.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.HubAppInfo
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HubMemoryFlag)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/HubMemoryFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.HubMemoryFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HubMemoryType)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/HubMemoryType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.HubMemoryType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemRange)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/MemRange.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.MemRange
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (NanoAppBinary)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/NanoAppBinary.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.NanoAppBinary
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (NanoAppFlags)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/NanoAppFlags.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.NanoAppFlags
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PhysicalSensor)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/PhysicalSensor.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.PhysicalSensor
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Result)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/Result.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.Result
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SensorType)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/SensorType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.SensorType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (TransactionResult)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/TransactionResult.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.TransactionResult
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IContexthub.hal
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/IContexthub.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IContexthub.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/IContexthubCallback.hal
+$(GEN): $(LOCAL_PATH)/IContexthubCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::IContexthub
+
+$(GEN): $(LOCAL_PATH)/IContexthub.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IContexthubCallback.hal
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/IContexthubCallback.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IContexthubCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::IContexthubCallback
+
+$(GEN): $(LOCAL_PATH)/IContexthubCallback.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.contexthub@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (AsyncEventType)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/AsyncEventType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.AsyncEventType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ContextHub)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/ContextHub.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.ContextHub
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ContextHubMsg)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/ContextHubMsg.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.ContextHubMsg
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HubAppInfo)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/HubAppInfo.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.HubAppInfo
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HubMemoryFlag)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/HubMemoryFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.HubMemoryFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HubMemoryType)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/HubMemoryType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.HubMemoryType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemRange)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/MemRange.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.MemRange
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (NanoAppBinary)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/NanoAppBinary.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.NanoAppBinary
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (NanoAppFlags)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/NanoAppFlags.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.NanoAppFlags
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PhysicalSensor)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/PhysicalSensor.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.PhysicalSensor
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Result)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/Result.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.Result
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SensorType)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/SensorType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.SensorType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (TransactionResult)
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/TransactionResult.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::types.TransactionResult
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IContexthub.hal
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/IContexthub.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IContexthub.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/IContexthubCallback.hal
+$(GEN): $(LOCAL_PATH)/IContexthubCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::IContexthub
+
+$(GEN): $(LOCAL_PATH)/IContexthub.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IContexthubCallback.hal
+#
+GEN := $(intermediates)/android/hardware/contexthub/1.0/IContexthubCallback.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IContexthubCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.contexthub@1.0::IContexthubCallback
+
+$(GEN): $(LOCAL_PATH)/IContexthubCallback.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/contexthub/1.0/IContexthub.hal b/contexthub/1.0/IContexthub.hal
new file mode 100644 (file)
index 0000000..8d19aeb
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * 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 android.hardware.contexthub@1.0;
+
+import IContexthubCallback;
+
+interface IContexthub {
+    /*
+     * Enumerate all available context hubs on the system.
+     *
+     * @return hubs list of hubs on this system.
+     */
+    getHubs() generates (vec<ContextHub> hubs);
+
+    /*
+     * Register a callback for the HAL implementation to send asynchronous
+     * messages to the service from a context hub. There can be a maximum of
+     * one callback registered with the HAL. A call to this function when a
+     * callback has already been registered must override the previous
+     * registration.
+     *
+     * @param hubId    identifier for the hub
+     *        callback an implementation of the IContextHubCallbacks
+     *
+     * @return result OK on success
+     *                BAD_VALUE if parameters are not sane
+     *
+     */
+     registerCallback(uint32_t hubId, IContexthubCallback cb) generates (Result result);
+
+    /**
+     * Send a message to a hub
+     *
+     * @param hubId identifier for hub to send message to
+     *        msg   message to be sent
+     *
+     * @return result OK if successful, error code otherwise
+     *                BAD_VALUE if parameters are not sane
+     *                TRANSACTION_FAILED if message send failed
+     */
+    sendMessageToHub(uint32_t hubId, ContextHubMsg msg)
+            generates (Result result);
+
+    /**
+     * Loads a nanoApp. After loading, the nanoApp's init method must be called.
+     * After the init method for nanoApp returns success, this must be indicated
+     * to the service by an asynchronous call to handleTxnResult.
+     *
+     * @param hubId identifer of the contextHub
+     *        appBinary binary for the nanoApp
+     *        msg   message to be sent
+     *
+     * @return result OK if transation started
+     *                BAD_VALUE if parameters are not sane
+     *                TRANSACTION_PENDING if hub is busy with another
+     *                                    load/unload transaction
+     *                TRANSACTION_FAILED if load failed synchronously
+     *
+     */
+    loadNanoApp(uint32_t hubId, NanoAppBinary appBinary, uint32_t transactionId)
+            generates (Result result);
+
+    /**
+     * Unloads a nanoApp. Before the unload, the apps deinit method is called.
+     * After this, success must be indicated to the service through an
+     * asynchronous call to handleTxnResult.
+     *
+     * @param hubId identifer of the contextHub
+     *        appId appIdentifier returned by the HAL
+     *        msg   message to be sent
+     *
+     * @return result OK if transation started
+     *                BAD_VALUE if parameters are not sane
+     *                TRANSACTION_PENDING if hub is busy with another
+     *                                    load/unload transaction
+     *                TRANSACTION_FAILED if unload failed synchronously
+     *
+     */
+    unloadNanoApp(uint32_t hubId, uint64_t appId, uint32_t transactionId)
+            generates (Result result);
+
+    /**
+     * Enables a nanoApp. The app's init method is called.
+     * After this, success must be indicated to the service through an
+     * asynchronous message.
+     *
+     * @param hubId identifer of the contextHub
+     *        appId appIdentifier returned by the HAL
+     *        msg   message to be sent
+     *
+     * @return result OK if transation started
+     *                BAD_VALUE if parameters are not sane
+     *                TRANSACTION_PENDING if hub is busy with another
+     *                                    load/unload transaction
+     *                FAILED_TRANSACTION if load fails immediately
+     *
+     */
+    enableNanoApp(uint32_t hubId, uint64_t appId, uint32_t transactionId)
+            generates (Result result);
+
+    /**
+     * Disables a nanoApp. The app's deinit method is called.
+     * After this, success must be indicated to the service through an
+     * asynchronous message.
+     *
+     * @param hubId identifer of the contextHub
+     *        appId appIdentifier returned by the HAL
+     *        msg   message to be sent
+     *
+     * @return result OK if transation started
+     *                BAD_VALUE if parameters are not sane
+     *                TRANSACTION_PENDING if hub is busy with another
+     *                                    load/unload transaction
+     *                FAILED_TRANSACTION if load fails immediately
+     *
+     */
+    disableNanoApp(uint32_t hubId, uint64_t appId, uint32_t transactionId)
+            generates (Result result);
+
+    /**
+     * Queries for Loaded apps on the hub
+     *
+     * @param hubId identifer of the contextHub
+     *
+     * @return apps all nanoApps on the hub
+     *
+     */
+    queryApps(uint32_t hubId) generates (Result result);
+
+    /**
+     * Reboots context hub OS, restarts all the nanoApps.
+     * No reboot notification is sent to nanoApps; reboot happens immediately
+     * and unconditionally; all volatile contexthub state and any data is lost
+     * as a result.
+     *
+     * @param hubId identifer of the contextHub
+     *
+     * @return result OK on success
+     *                BAD_VALUE if parameters are not sane
+     *
+     */
+    reboot(uint32_t hubId) generates (Result result);
+};
diff --git a/contexthub/1.0/IContexthubCallback.hal b/contexthub/1.0/IContexthubCallback.hal
new file mode 100644 (file)
index 0000000..29c41ce
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * 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 android.hardware.contexthub@1.0;
+
+interface IContexthubCallback {
+    /*
+     * This callback is passed by the Contexthub service to the HAL
+     * implementation to allow the HAL to send asynchronous messages back
+     * to the service and registered clients of the ContextHub service.
+     *
+     * @params hubId : identifier of the hub calling callback
+     *         msg   : message
+     *
+     */
+     handleClientMsg(uint32_t hubId, ContextHubMsg msg);
+
+    /*
+     * This callback is passed by the Contexthub service to the HAL
+     * implementation to allow the HAL to send the response for a
+     * transaction.
+     *
+     * @params hubId : identifier of the hub calling callback
+     *         txnId : transaction id whose result is being sent
+     *                 passed in by the service at start of transacation.
+     *         result: result of transaction.
+     *
+     */
+     handleTxnResult(uint32_t hubId, uint32_t txnId,
+             TransactionResult result);
+
+    /*
+     * This callback is passed by the Contexthub service to the HAL
+     * implementation to allow the HAL to send an asynchronous event
+     * to the ContextHub service.
+     *
+     * @params hubId : identifier of the hub calling callback
+     *         msg   : message
+     *
+     */
+     handleHubEvent(uint32_t hubId, AsyncEventType evt);
+
+     /*
+      * This callback is passed by the Contexthub service to the HAL
+      * implementation to allow the HAL to send information about the
+      * currently loaded and active nanoapps on the hub.
+      */
+      handleAppsInfo(uint32_t hubId, vec<HubAppInfo> appInfo);
+};
diff --git a/contexthub/1.0/types.hal b/contexthub/1.0/types.hal
new file mode 100644 (file)
index 0000000..7d5a1ac
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+ * 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 android.hardware.contexthub@1.0;
+
+enum Result : uint32_t {
+    OK,                  // Success
+    BAD_PARAMS,          // Parameters not sane
+    NOT_INIT,            // not initialized
+    TRANSACTION_FAILED,  // transaction failed
+    TRANSACTION_PENDING, // Pending transaction, cannot accept a new request
+};
+
+
+enum NanoAppFlags : uint32_t {
+    SIGNED = (1<<0),   // Signed nanoapp
+    ENCRYPTED = (1<<1),// Encrypted nanoapp
+};
+
+struct NanoAppBinary {
+    uint32_t headerVersion;    // 0x1 for this version
+    uint32_t magic;            // "NANO"
+    uint64_t appId;            // App Id contains vendor id
+    uint32_t appVersion;       // Version of the app
+    uint32_t flags;            // mask of NanoAppFlags
+    uint64_t hwHubType;        // which hub type is this compiled for
+                               // a unique UUID for each h/w + toolchain
+                               // combination.
+    vec<uint8_t> customBinary; // start of custom binary data
+};
+
+enum SensorType : uint32_t {
+    RESERVED,
+    ACCELEROMETER,
+    GYROSCOPE,
+    MAGNETOMETER,
+    BAROMETER,
+    PROXIMITY_SENSOR,
+    AMBIENT_LIGHT_SENSOR,
+
+    GPS = 0x100,
+    // Reserving this space for variants on GPS
+
+    WIFI = 0x200,
+    // Reserving this space for variants on WIFI
+
+    AUDIO = 0x300,
+    // Reserving this space for variants on Audio
+
+    CAMERA = 0x400,
+    // Reserving this space for variants on Camera
+
+    BLE = 0x500,
+
+    PRIVATE_SENSOR_BASE = 0x10000,
+    // Sensor types beyond PRIVATE_SENSOR_BASE are custom types
+};
+
+struct PhysicalSensor{
+    SensorType sensorType;       // From the definitions above eg: 100
+    string type;                 // Type as a string. eg: "GPS"
+    string name;                 // Identifier eg: "Bosch BMI160"
+    string vendor;               // Vendor : eg "STM"
+    uint32_t version;            // Version : eg 0x1001
+    uint32_t fifoReservedCount;  // Batching possible in hardware. Please
+                                 // note that here hardware does not include
+                                 // the context hub itself. Thus, this
+                                 // definition may be different from say the
+                                 // number advertised in the sensors HAL
+                                 // which allows for batching in a hub.
+    uint32_t fifoMaxCount;       // maximum number of batchable events.
+    uint64_t minDelayMs;         // in milliseconds, corresponding to highest
+                                 // sampling freq.
+    uint64_t maxDelayMs;         // in milliseconds, corresponds to minimum
+                                 // sampling frequency
+    float peakPowerMw;           // At max frequency & no batching, power
+                                 // in milliwatts
+};
+
+struct ContextHub {
+    string name;                // descriptive name eg: "Awesome Hub #1"
+    string vendor;              // hub hardware vendor eg: "Qualcomm"
+    string toolchain;           // toolchain to make binaries eg: "gcc ARM"
+    uint32_t platformVersion;   // Version of the hardware : eg 0x20
+    uint32_t toolchainVersion;  // Version of the toolchain : eg: 0x484
+    uint32_t hubId;             // a device unique id for this hub
+
+    float peakMips;             // Peak MIPS platform can deliver
+    float stoppedPowerDrawMw;   // if stopped, retention power, milliwatts
+    float sleepPowerDrawMw;     // if sleeping, retention power, milliwatts
+    float peakPowerDrawMw;      // for a busy CPUm power in milliwatts
+
+    vec<PhysicalSensor> connectedSensors; // array of connected sensors
+
+    uint32_t maxSupportedMsgLen;// This is the maximum size of the message that can
+                                // be sent to the hub in one chunk (in bytes)
+};
+
+struct ContextHubMsg {
+    uint64_t appName; // intended recipient
+    uint32_t msgType; // identifier for message
+    vec<uint8_t> msg; // message body
+};
+
+enum HubMemoryType : uint32_t {
+    MAIN      = 0, // Main memory
+    SECONDARY = 1, // Secondary memory
+    TCM       = 2, // Tightly coupled memory
+};
+
+enum HubMemoryFlag : uint32_t {
+    READ  = (1<<0), // Readable
+    WRITE = (1<<1), // Writable
+    EXEC  = (1<<2), // Executable
+};
+
+struct MemRange {
+    uint32_t totalBytes; // total capacity in bytes
+    uint32_t freeBytes;  // free capacity in bytes
+    HubMemoryType type;  // type of memory, see HubMemoryType
+    uint32_t flags;      // mask of HubMemoryFlag
+};
+
+enum AsyncEventType : uint32_t {
+    RESTARTED = 1, // Hub restarted unexpectedly
+};
+
+enum TransactionResult {
+    SUCCESS,      // successful completion of transaction
+    FAILURE,      // failed transaction
+};
+
+struct HubAppInfo {
+    uint64_t appId;         // Identifier of the app
+    uint32_t version;       // version of the app
+    vec<MemRange> memUsage; // Memory used by this app
+};
+
diff --git a/contexthub/Android.bp b/contexthub/Android.bp
new file mode 100644 (file)
index 0000000..bbb3e4b
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+]
diff --git a/example/Android.bp b/example/Android.bp
new file mode 100644 (file)
index 0000000..ea6dbb5
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "extension/light/2.0",
+]
diff --git a/example/extension/light/2.0/Android.bp b/example/extension/light/2.0/Android.bp
new file mode 100644 (file)
index 0000000..2a4eddf
--- /dev/null
@@ -0,0 +1,53 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.example.extension.light@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.example.extension.light@2.0",
+    srcs: [
+        "types.hal",
+        "IExtLight.hal",
+    ],
+    out: [
+        "android/hardware/example/extension/light/2.0/types.cpp",
+        "android/hardware/example/extension/light/2.0/ExtLightAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.example.extension.light@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.example.extension.light@2.0",
+    srcs: [
+        "types.hal",
+        "IExtLight.hal",
+    ],
+    out: [
+        "android/hardware/example/extension/light/2.0/types.h",
+        "android/hardware/example/extension/light/2.0/IExtLight.h",
+        "android/hardware/example/extension/light/2.0/IHwExtLight.h",
+        "android/hardware/example/extension/light/2.0/BnExtLight.h",
+        "android/hardware/example/extension/light/2.0/BpExtLight.h",
+        "android/hardware/example/extension/light/2.0/BsExtLight.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.example.extension.light@2.0",
+    generated_sources: ["android.hardware.example.extension.light@2.0_genc++"],
+    generated_headers: ["android.hardware.example.extension.light@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.example.extension.light@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.light@2.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.light@2.0",
+    ],
+}
diff --git a/example/extension/light/2.0/Android.mk b/example/extension/light/2.0/Android.mk
new file mode 100644 (file)
index 0000000..75157a8
--- /dev/null
@@ -0,0 +1,178 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.example.extension.light@2.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+LOCAL_JAVA_LIBRARIES := \
+    android.hardware.light@2.0-java \
+
+
+#
+# Build types.hal (Default)
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/Default.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::types.Default
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ExtBrightness)
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/ExtBrightness.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::types.ExtBrightness
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ExtLightState)
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/ExtLightState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::types.ExtLightState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IExtLight.hal
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/IExtLight.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IExtLight.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::IExtLight
+
+$(GEN): $(LOCAL_PATH)/IExtLight.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.example.extension.light@2.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    android.hardware.light@2.0-java-static \
+
+
+#
+# Build types.hal (Default)
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/Default.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::types.Default
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ExtBrightness)
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/ExtBrightness.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::types.ExtBrightness
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ExtLightState)
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/ExtLightState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::types.ExtLightState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IExtLight.hal
+#
+GEN := $(intermediates)/android/hardware/example/extension/light/2.0/IExtLight.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IExtLight.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.example.extension.light@2.0::IExtLight
+
+$(GEN): $(LOCAL_PATH)/IExtLight.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/example/extension/light/2.0/IExtLight.hal b/example/extension/light/2.0/IExtLight.hal
new file mode 100644 (file)
index 0000000..f12a272
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+// Would normally be 'vendor.example.extension.light@2.0' however, this is
+// a google extension example. A vendor extension should also live in the
+// vendor partition.
+package android.hardware.example.extension.light@2.0;
+
+import android.hardware.light@2.0;
+
+interface IExtLight extends android.hardware.light@2.0::ILight {
+
+    /**
+     * Set the provided lights to the provided values.
+     *
+     * @param type logical light to set
+     * @param state describes what the light should look like.
+     * @return status result of applying state transformation.
+     */
+    setExtLight(Type type, ExtLightState state) generates (Status status);
+
+};
diff --git a/example/extension/light/2.0/default/Android.mk b/example/extension/light/2.0/default/Android.mk
new file mode 100644 (file)
index 0000000..fa68787
--- /dev/null
@@ -0,0 +1,17 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.example.extension.light@2.0-service
+LOCAL_INIT_RC := android.hardware.example.extension.light@2.0-service.rc
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    Light.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    libhidl \
+    libhwbinder \
+    libutils \
+    android.hardware.light@2.0 \
+    android.hardware.example.extension.light@2.0 \
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/example/extension/light/2.0/default/Light.cpp b/example/extension/light/2.0/default/Light.cpp
new file mode 100644 (file)
index 0000000..d738a6d
--- /dev/null
@@ -0,0 +1,56 @@
+#include "Light.h"
+
+namespace android {
+namespace hardware {
+namespace example {
+namespace extension {
+namespace light {
+namespace V2_0 {
+namespace implementation {
+
+// Methods from ::android::hardware::light::V2_0::ILight follow.
+Return<Status> Light::setLight(Type type, const LightState& state)  {
+    // Forward types for new methods.
+
+    ExtLightState extState {
+        .state = state,
+        .interpolationOmega =
+            static_cast<int32_t>(Default::INTERPOLATION_OMEGA),
+        .brightness = // ExtBrightness inherits from Brightness
+            static_cast<ExtBrightness>(state.brightnessMode)
+    };
+
+    return setExtLight(type, extState);
+}
+
+Return<void> Light::getSupportedTypes(getSupportedTypes_cb _hidl_cb)  {
+    // implement unchanged method as you would always
+    hidl_vec<Type> vec{};
+
+    // ******************************************************
+    // Note: awesome proprietary hardware implementation here
+    // ******************************************************
+
+    _hidl_cb(vec);
+
+    return Void();
+}
+
+// Methods from ::android::hardware::example::extension::light::V2_0::ILight follow.
+Return<Status> Light::setExtLight(Type /* type */,
+                                  const ExtLightState& /* state */)  {
+
+    // ******************************************************
+    // Note: awesome proprietary hardware implementation here
+    // ******************************************************
+
+    return Status::SUCCESS;
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace light
+}  // namespace extension
+}  // namespace example
+}  // namespace hardware
+}  // namespace android
diff --git a/example/extension/light/2.0/default/Light.h b/example/extension/light/2.0/default/Light.h
new file mode 100644 (file)
index 0000000..e09ec92
--- /dev/null
@@ -0,0 +1,46 @@
+#ifndef HIDL_GENERATED_android_hardware_example_extension_light_V2_0_Light_H_
+#define HIDL_GENERATED_android_hardware_example_extension_light_V2_0_Light_H_
+
+#include <android/hardware/example/extension/light/2.0/IExtLight.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+namespace android {
+namespace hardware {
+namespace example {
+namespace extension {
+namespace light {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::example::extension::light::V2_0::ExtLightState;
+using ::android::hardware::example::extension::light::V2_0::IExtLight;
+using ::android::hardware::light::V2_0::ILight;
+using ::android::hardware::light::V2_0::LightState;
+using ::android::hardware::light::V2_0::Status;
+using ::android::hardware::light::V2_0::Type;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Light : public IExtLight {
+    // Methods from ::android::hardware::light::V2_0::ILight follow.
+    Return<Status> setLight(Type type, const LightState& state)  override;
+    Return<void> getSupportedTypes(getSupportedTypes_cb _hidl_cb)  override;
+
+    // Methods from ::android::hardware::example::extension::light::V2_0::ILight follow.
+    Return<Status> setExtLight(Type type, const ExtLightState& state)  override;
+
+};
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace light
+}  // namespace extension
+}  // namespace example
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_example_extension_light_V2_0_Light_H_
diff --git a/example/extension/light/2.0/default/android.hardware.example.extension.light@2.0-service.rc b/example/extension/light/2.0/default/android.hardware.example.extension.light@2.0-service.rc
new file mode 100644 (file)
index 0000000..8a90d81
--- /dev/null
@@ -0,0 +1,4 @@
+service light-ext-2-0 /system/bin/hw/android.hardware.example.extension.light@2.0-service
+    class hal
+    user system
+    group system readproc
\ No newline at end of file
diff --git a/example/extension/light/2.0/default/service.cpp b/example/extension/light/2.0/default/service.cpp
new file mode 100644 (file)
index 0000000..d21afa6
--- /dev/null
@@ -0,0 +1,26 @@
+#define LOG_TAG "android.hardware.light@2.0-service"
+
+#include <utils/Log.h>
+
+#include "Light.h"
+
+using android::sp;
+
+// libhwbinder:
+using android::hardware::IPCThreadState;
+using android::hardware::ProcessState;
+
+// Generated HIDL files
+using android::hardware::light::V2_0::ILight;
+
+int main() {
+    const char instance[] = "light";
+
+    android::sp<ILight> service = new Light();
+
+    service->registerAsService(instance);
+
+    ProcessState::self()->setThreadPoolMaxThreadCount(0);
+    ProcessState::self()->startThreadPool();
+    IPCThreadState::self()->joinThreadPool();
+}
diff --git a/example/extension/light/2.0/types.hal b/example/extension/light/2.0/types.hal
new file mode 100644 (file)
index 0000000..5be41bb
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * 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 android.hardware.example.extension.light@2.0;
+
+import android.hardware.light@2.0;
+
+enum Default : int32_t {
+    // for calls to setLight from the framework that don't know about this
+    // extension or its requirements
+    INTERPOLATION_OMEGA = 2
+};
+
+/**
+ * One possibility is renaming an old type. Another possibility is taking
+ * advantages of the different namespaces.
+ */
+enum ExtBrightness : Brightness {
+    /**
+     * Say we're really going to use the phone as a heater.
+     */
+    EXTREME,
+
+    /**
+     * Sometimes at night, we need it to be day.
+     */
+     THE_SUN,
+};
+
+/**
+ * Structs can't inherit eachother in hidl. Use composition instead. In this
+ * case, I won't use inheritence because I want to replace Brightness with
+ * ExtBrightness.
+ */
+struct ExtLightState {
+    LightState state;
+
+    /**
+     * This is the secret sauce that will really make this extension shine.
+     * No other person has such a cool feature in their hals. Don't forget
+     * to describe all details of parameters. An interface is a contract, and
+     * specifying this contract to the letter is what allows that contracted
+     * to be maintained. :)
+     *
+     * So, this parameter represents the speed at which brightness is changed
+     * to the new value in the three dimensional space with coordinates RGB
+     * from the red, blue, and green.
+     */
+    int32_t interpolationOmega;
+
+    /**
+     * Include new values.
+     */
+    ExtBrightness brightness;
+};
diff --git a/gnss/1.0/Android.bp b/gnss/1.0/Android.bp
new file mode 100644 (file)
index 0000000..1f538ca
--- /dev/null
@@ -0,0 +1,179 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.gnss@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.gnss@1.0",
+    srcs: [
+        "types.hal",
+        "IAGnss.hal",
+        "IAGnssCallback.hal",
+        "IAGnssRil.hal",
+        "IAGnssRilCallback.hal",
+        "IGnss.hal",
+        "IGnssCallback.hal",
+        "IGnssDebug.hal",
+        "IGnssGeofenceCallback.hal",
+        "IGnssGeofencing.hal",
+        "IGnssMeasurement.hal",
+        "IGnssMeasurementCallback.hal",
+        "IGnssNavigationMessage.hal",
+        "IGnssNavigationMessageCallback.hal",
+        "IGnssNi.hal",
+        "IGnssNiCallback.hal",
+        "IGnssXtra.hal",
+        "IGnssXtraCallback.hal",
+    ],
+    out: [
+        "android/hardware/gnss/1.0/types.cpp",
+        "android/hardware/gnss/1.0/AGnssAll.cpp",
+        "android/hardware/gnss/1.0/AGnssCallbackAll.cpp",
+        "android/hardware/gnss/1.0/AGnssRilAll.cpp",
+        "android/hardware/gnss/1.0/AGnssRilCallbackAll.cpp",
+        "android/hardware/gnss/1.0/GnssAll.cpp",
+        "android/hardware/gnss/1.0/GnssCallbackAll.cpp",
+        "android/hardware/gnss/1.0/GnssDebugAll.cpp",
+        "android/hardware/gnss/1.0/GnssGeofenceCallbackAll.cpp",
+        "android/hardware/gnss/1.0/GnssGeofencingAll.cpp",
+        "android/hardware/gnss/1.0/GnssMeasurementAll.cpp",
+        "android/hardware/gnss/1.0/GnssMeasurementCallbackAll.cpp",
+        "android/hardware/gnss/1.0/GnssNavigationMessageAll.cpp",
+        "android/hardware/gnss/1.0/GnssNavigationMessageCallbackAll.cpp",
+        "android/hardware/gnss/1.0/GnssNiAll.cpp",
+        "android/hardware/gnss/1.0/GnssNiCallbackAll.cpp",
+        "android/hardware/gnss/1.0/GnssXtraAll.cpp",
+        "android/hardware/gnss/1.0/GnssXtraCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.gnss@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.gnss@1.0",
+    srcs: [
+        "types.hal",
+        "IAGnss.hal",
+        "IAGnssCallback.hal",
+        "IAGnssRil.hal",
+        "IAGnssRilCallback.hal",
+        "IGnss.hal",
+        "IGnssCallback.hal",
+        "IGnssDebug.hal",
+        "IGnssGeofenceCallback.hal",
+        "IGnssGeofencing.hal",
+        "IGnssMeasurement.hal",
+        "IGnssMeasurementCallback.hal",
+        "IGnssNavigationMessage.hal",
+        "IGnssNavigationMessageCallback.hal",
+        "IGnssNi.hal",
+        "IGnssNiCallback.hal",
+        "IGnssXtra.hal",
+        "IGnssXtraCallback.hal",
+    ],
+    out: [
+        "android/hardware/gnss/1.0/types.h",
+        "android/hardware/gnss/1.0/IAGnss.h",
+        "android/hardware/gnss/1.0/IHwAGnss.h",
+        "android/hardware/gnss/1.0/BnAGnss.h",
+        "android/hardware/gnss/1.0/BpAGnss.h",
+        "android/hardware/gnss/1.0/BsAGnss.h",
+        "android/hardware/gnss/1.0/IAGnssCallback.h",
+        "android/hardware/gnss/1.0/IHwAGnssCallback.h",
+        "android/hardware/gnss/1.0/BnAGnssCallback.h",
+        "android/hardware/gnss/1.0/BpAGnssCallback.h",
+        "android/hardware/gnss/1.0/BsAGnssCallback.h",
+        "android/hardware/gnss/1.0/IAGnssRil.h",
+        "android/hardware/gnss/1.0/IHwAGnssRil.h",
+        "android/hardware/gnss/1.0/BnAGnssRil.h",
+        "android/hardware/gnss/1.0/BpAGnssRil.h",
+        "android/hardware/gnss/1.0/BsAGnssRil.h",
+        "android/hardware/gnss/1.0/IAGnssRilCallback.h",
+        "android/hardware/gnss/1.0/IHwAGnssRilCallback.h",
+        "android/hardware/gnss/1.0/BnAGnssRilCallback.h",
+        "android/hardware/gnss/1.0/BpAGnssRilCallback.h",
+        "android/hardware/gnss/1.0/BsAGnssRilCallback.h",
+        "android/hardware/gnss/1.0/IGnss.h",
+        "android/hardware/gnss/1.0/IHwGnss.h",
+        "android/hardware/gnss/1.0/BnGnss.h",
+        "android/hardware/gnss/1.0/BpGnss.h",
+        "android/hardware/gnss/1.0/BsGnss.h",
+        "android/hardware/gnss/1.0/IGnssCallback.h",
+        "android/hardware/gnss/1.0/IHwGnssCallback.h",
+        "android/hardware/gnss/1.0/BnGnssCallback.h",
+        "android/hardware/gnss/1.0/BpGnssCallback.h",
+        "android/hardware/gnss/1.0/BsGnssCallback.h",
+        "android/hardware/gnss/1.0/IGnssDebug.h",
+        "android/hardware/gnss/1.0/IHwGnssDebug.h",
+        "android/hardware/gnss/1.0/BnGnssDebug.h",
+        "android/hardware/gnss/1.0/BpGnssDebug.h",
+        "android/hardware/gnss/1.0/BsGnssDebug.h",
+        "android/hardware/gnss/1.0/IGnssGeofenceCallback.h",
+        "android/hardware/gnss/1.0/IHwGnssGeofenceCallback.h",
+        "android/hardware/gnss/1.0/BnGnssGeofenceCallback.h",
+        "android/hardware/gnss/1.0/BpGnssGeofenceCallback.h",
+        "android/hardware/gnss/1.0/BsGnssGeofenceCallback.h",
+        "android/hardware/gnss/1.0/IGnssGeofencing.h",
+        "android/hardware/gnss/1.0/IHwGnssGeofencing.h",
+        "android/hardware/gnss/1.0/BnGnssGeofencing.h",
+        "android/hardware/gnss/1.0/BpGnssGeofencing.h",
+        "android/hardware/gnss/1.0/BsGnssGeofencing.h",
+        "android/hardware/gnss/1.0/IGnssMeasurement.h",
+        "android/hardware/gnss/1.0/IHwGnssMeasurement.h",
+        "android/hardware/gnss/1.0/BnGnssMeasurement.h",
+        "android/hardware/gnss/1.0/BpGnssMeasurement.h",
+        "android/hardware/gnss/1.0/BsGnssMeasurement.h",
+        "android/hardware/gnss/1.0/IGnssMeasurementCallback.h",
+        "android/hardware/gnss/1.0/IHwGnssMeasurementCallback.h",
+        "android/hardware/gnss/1.0/BnGnssMeasurementCallback.h",
+        "android/hardware/gnss/1.0/BpGnssMeasurementCallback.h",
+        "android/hardware/gnss/1.0/BsGnssMeasurementCallback.h",
+        "android/hardware/gnss/1.0/IGnssNavigationMessage.h",
+        "android/hardware/gnss/1.0/IHwGnssNavigationMessage.h",
+        "android/hardware/gnss/1.0/BnGnssNavigationMessage.h",
+        "android/hardware/gnss/1.0/BpGnssNavigationMessage.h",
+        "android/hardware/gnss/1.0/BsGnssNavigationMessage.h",
+        "android/hardware/gnss/1.0/IGnssNavigationMessageCallback.h",
+        "android/hardware/gnss/1.0/IHwGnssNavigationMessageCallback.h",
+        "android/hardware/gnss/1.0/BnGnssNavigationMessageCallback.h",
+        "android/hardware/gnss/1.0/BpGnssNavigationMessageCallback.h",
+        "android/hardware/gnss/1.0/BsGnssNavigationMessageCallback.h",
+        "android/hardware/gnss/1.0/IGnssNi.h",
+        "android/hardware/gnss/1.0/IHwGnssNi.h",
+        "android/hardware/gnss/1.0/BnGnssNi.h",
+        "android/hardware/gnss/1.0/BpGnssNi.h",
+        "android/hardware/gnss/1.0/BsGnssNi.h",
+        "android/hardware/gnss/1.0/IGnssNiCallback.h",
+        "android/hardware/gnss/1.0/IHwGnssNiCallback.h",
+        "android/hardware/gnss/1.0/BnGnssNiCallback.h",
+        "android/hardware/gnss/1.0/BpGnssNiCallback.h",
+        "android/hardware/gnss/1.0/BsGnssNiCallback.h",
+        "android/hardware/gnss/1.0/IGnssXtra.h",
+        "android/hardware/gnss/1.0/IHwGnssXtra.h",
+        "android/hardware/gnss/1.0/BnGnssXtra.h",
+        "android/hardware/gnss/1.0/BpGnssXtra.h",
+        "android/hardware/gnss/1.0/BsGnssXtra.h",
+        "android/hardware/gnss/1.0/IGnssXtraCallback.h",
+        "android/hardware/gnss/1.0/IHwGnssXtraCallback.h",
+        "android/hardware/gnss/1.0/BnGnssXtraCallback.h",
+        "android/hardware/gnss/1.0/BpGnssXtraCallback.h",
+        "android/hardware/gnss/1.0/BsGnssXtraCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.gnss@1.0",
+    generated_sources: ["android.hardware.gnss@1.0_genc++"],
+    generated_headers: ["android.hardware.gnss@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.gnss@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/gnss/1.0/IAGnss.hal b/gnss/1.0/IAGnss.hal
new file mode 100644 (file)
index 0000000..a3172f3
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+import IAGnssCallback;
+
+/*
+ * Extended interface for AGNSS support.
+ */
+interface IAGnss {
+    enum ApnIpType : uint16_t {
+        INVALID  = 0,
+        IPV4     = 1,
+        IPV6     = 2,
+        IPV4V6   = 3
+    };
+
+    /*
+     * Opens the AGNSS interface and provides the callback routines to the
+     * implementation of this interface.
+     *
+     * @param callback Handle to the AGNSS status callback interface.
+     */
+    setCallback(IAGnssCallback callback);
+
+    /*
+     * Notifies that the AGNSS data connection has been closed.
+     *
+     * @return success True if the operation is successful.
+     */
+    dataConnClosed() generates (bool success);
+
+    /*
+     * Notifies that a data connection is not available for AGNSS.
+     *
+     * @return success True if the operation is successful.
+     */
+    dataConnFailed() generates (bool success);
+
+    /*
+     * Sets the hostname and port for the AGNSS server.
+     *
+     * @param type Specifies if SUPL or C2K.
+     * @param hostname Hostname of the AGNSS server.
+     * @param port Port number associated with the server.
+     *
+     * @return success True if the operation is successful.
+     */
+    setServer(AGnssType type, string hostname, int32_t port)
+        generates (bool success);
+
+    /*
+     * Notifies that a data connection is available and sets the name of the
+     * APN, and its IP type, to be used for SUPL connections.
+     *
+     * @param apn Access Point Name(follows regular APN naming convention).
+     * @param apnIpType Specifies if SUPL or C2K.
+     *
+     * @return success True if the operation is successful.
+     */
+    dataConnOpenWithApnIpType(string apn, ApnIpType apnIpType)
+        generates (bool success);
+};
diff --git a/gnss/1.0/IAGnssCallback.hal b/gnss/1.0/IAGnssCallback.hal
new file mode 100644 (file)
index 0000000..46641be
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+/** Callback structure for the AGNSS interface. */
+interface IAGnssCallback {
+    /** AGNSS type **/
+    enum AGnssType : uint16_t {
+        TYPE_SUPL         = 1,
+        TYPE_C2K          = 2
+    };
+
+    enum AGnssStatusValue : uint16_t {
+        /** GNSS requests data connection for AGNSS. */
+        REQUEST_AGNSS_DATA_CONN  = 1,
+        /** GNSS releases the AGNSS data connection. */
+        RELEASE_AGNSS_DATA_CONN  = 2,
+        /** AGNSS data connection initiated */
+        AGNSS_DATA_CONNECTED     = 3,
+        /** AGNSS data connection completed */
+        AGNSS_DATA_CONN_DONE     = 4,
+        /** AGNSS data connection failed */
+        AGNSS_DATA_CONN_FAILED   = 5
+    };
+
+    /*
+     * Represents the status of AGNSS augmented to support IPv4.
+     */
+    struct AGnssStatusIpV4 {
+        AGnssType type;
+        AGnssStatusValue status;
+        /*
+         * 32-bit IPv4 address.
+         */
+        uint32_t ipV4Addr;
+    };
+
+    /*
+     * Represents the status of AGNSS augmented to support IPv6.
+     */
+    struct AGnssStatusIpV6 {
+        AGnssType type;
+        AGnssStatusValue status;
+        /*
+         * 128-bit IPv6 address.
+         */
+        uint8_t[16] ipV6Addr;
+    };
+
+    /*
+     * Callback with AGNSS(IpV4) status information.
+     *
+     * @param status Will be of type AGnssStatusIpV4.
+     */
+    agnssStatusIpV4Cb(AGnssStatusIpV4 status);
+
+    /*
+     * Callback with AGNSS(IpV6) status information.
+     *
+     * @param status Will be of type AGnssStatusIpV6.
+     */
+    agnssStatusIpV6Cb(AGnssStatusIpV6 status);
+
+};
diff --git a/gnss/1.0/IAGnssRil.hal b/gnss/1.0/IAGnssRil.hal
new file mode 100644 (file)
index 0000000..fb73498
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+import IAGnssRilCallback;
+
+/*
+ * Extended interface for AGNSS RIL support. An Assisted GNSS Radio Interface
+ * Layer interface allows the GNSS chipset to request radio interface layer
+ * information from Android platform. Examples of such information are reference
+ * location, unique subscriber ID, phone number string and network availability changes.
+ */
+interface IAGnssRil {
+    enum SetIDType : uint16_t {
+        NONE    = 0,
+        IMSI    = 1,
+        MSISDM  = 2
+    };
+
+    enum NetworkType : int32_t {
+        MOBILE  = 0,
+        WIFI    = 1,
+        MMS     = 2,
+        SUPL    = 3,
+        DUN     = 4,
+        HIPRI   = 5,
+        WIMAX   = 6,
+    };
+
+    enum AGnssRefLocationType {
+        GSM_CELLID   = 1,
+        UMTS_CELLID  = 2,
+        MAC          = 3,
+        LTE_CELLID   = 4,
+    };
+
+    /* CellID for 2G, 3G and LTE, used in AGNSS. */
+    struct AGnssRefLocationCellID {
+        AGnssRefLocationType type;
+
+        /* Mobile Country Code. */
+        uint16_t mcc;
+
+        /* Mobile Network Code .*/
+        uint16_t mnc;
+
+        /*
+         * Location Area Code in 2G, 3G and LTE. In 3G lac is discarded. In LTE,
+         * lac is populated with tac, to ensure that we don't break old clients that
+         * might rely in the old (wrong) behavior.
+         */
+        uint16_t lac;
+
+        /* Cell id in 2G. Utran Cell id in 3G. Cell Global Id EUTRA in LTE. */
+        uint32_t cid;
+
+        /* Tracking Area Code in LTE. */
+        uint16_t tac;
+
+        /* Physical Cell id in LTE (not used in 2G and 3G) */
+        uint16_t pcid;
+    };
+
+    struct AGnssRefLocationMac {
+        uint8_t[6] mac;
+    };
+
+    /* Represents ref locations */
+    struct AGnssRefLocation {
+        AGnssRefLocationType type;
+
+        union RefLoc {
+            AGnssRefLocationCellID cellID;
+            AGnssRefLocationMac mac;
+        };
+
+        RefLoc refLocVal;
+    };
+
+    /*
+     * Opens the AGNSS interface and provides the callback routines
+     * to the implementation of this interface.
+     *
+     * @param callback Interface for AGnssRil callbacks.
+     */
+    setCallback(IAGnssRilCallback callback);
+
+    /*
+     * Sets the reference location.
+     *
+     * @param agnssReflocation AGNSS reference location CellID/MAC.
+     */
+    setRefLocation(AGnssRefLocation agnssReflocation);
+
+    /*
+     * Sets the SET ID.
+     *
+     * @param type Must be populated with either IMSI or MSISDN or NONE.
+     * @param setid If type is IMSI then setid is populated with
+     * a string representing the unique Subscriber ID, for example, the IMSI for
+     * a GMS phone. If type is MSISDN, then setid must contain
+     * the phone number string for line 1. For example, the MSISDN for a GSM phone.
+     * If the type is NONE, then the string must be empty.
+     *
+     * @return success True if all parameters were valid and operation was
+     * successful.
+     */
+    setSetId(SetIDType type, string setid) generates (bool success);
+
+    /*
+     * Notify GNSS of network status changes.
+     *
+     * @param connected Indicates whether network connectivity exists and
+     * it is possible to establish connections and pass data.
+     * @param type Indicates the kind of network, for eg. mobile, wifi etc.
+     * @param roaming Indicates whether the device is currently roaming on
+     * this network.
+     *
+     * @return success True is all parameters were valid and operation was
+     * successful.
+     */
+    updateNetworkState(bool connected, NetworkType type, bool roaming)
+        generates (bool success);
+
+    /*
+     * Notify GNSS of network status changes.
+     *
+     * @param available Indicates whether network connectivity is available.
+     * @param apn String containing the Access Point Name.
+     *
+     * @return success True if all parameters were valid and the operation was
+     * successful.
+     * TODO(b/32022567): Add VTS test to validate the format of APN.
+     */
+    updateNetworkAvailability(bool available, string apn) generates (bool success);
+
+};
diff --git a/gnss/1.0/IAGnssRilCallback.hal b/gnss/1.0/IAGnssRilCallback.hal
new file mode 100644 (file)
index 0000000..6f29820
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+/*
+ * Callback for IAGnssRil interface. Used to request SET ID and
+ * Reference Location.
+ */
+interface IAGnssRilCallback {
+    /* Kinds of SET ID that can be requested */
+    enum ID : uint32_t {
+        IMSI    = 1 << 0L,
+        MSISDN  = 1 << 1L,
+    };
+
+    /* Kinds of reference location that can be requested. */
+    enum RefLoc : uint32_t {
+        CELLID = 1 << 0L,
+        MAC    = 1 << 1L
+    };
+
+    /*
+     * The Hal uses this API to request a SET ID.
+     *
+     * @param setIdflag Specifies the kind of SET ID that is required by the HAL.
+     */
+    requestSetIdCb(ID setIdflag);
+
+    /*
+     * The Hal uses this API to request a reference location.
+     *
+     * @param refLocflag Specifies the kind of reference location that is required
+     * by the HAL.
+     */
+    requestRefLocCb(RefLoc refLocflag);
+
+};
diff --git a/gnss/1.0/IGnss.hal b/gnss/1.0/IGnss.hal
new file mode 100644 (file)
index 0000000..bc19e78
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+import IAGnss;
+import IAGnssRil;
+import IGnssCallback;
+import IGnssDebug;
+import IGnssMeasurement;
+import IGnssNavigationMessage;
+import IGnssGeofencing;
+import IGnssNi;
+import IGnssXtra;
+
+/* Represents the standard GNSS interface. */
+interface IGnss {
+    /* Requested operational mode for GNSS operation. */
+    enum GnssPositionMode : uint32_t {
+        /** Mode for running GNSS standalone (no assistance). */
+        STANDALONE  = 0,
+        /** AGNSS MS-Based mode. */
+        MS_BASED    = 1,
+        /*
+         * AGNSS MS-Assisted mode. This mode is not maintained by the platform anymore.
+         * It is strongly recommended to use MS_BASED instead.
+         */
+        MS_ASSISTED = 2,
+    };
+
+    /* Requested recurrence mode for GNSS operation. */
+    enum GnssPositionRecurrence : uint32_t {
+        /** Receive GNSS fixes on a recurring basis at a specified period. */
+        RECURRENCE_PERIODIC  = 0,
+        /** Request a single shot GNSS fix. */
+        RECURRENCE_SINGLE    = 1
+    };
+
+    /*
+     * Flags used to specify which aiding data to delete when calling
+     * deleteAidingData().
+     */
+    enum GnssAidingData : uint16_t {
+        DELETE_EPHEMERIS    = 0x0001,
+        DELETE_ALMANAC      = 0x0002,
+        DELETE_POSITION     = 0x0004,
+        DELETE_TIME         = 0x0008,
+        DELETE_IONO         = 0x0010,
+        DELETE_UTC          = 0x0020,
+        DELETE_HEALTH       = 0x0040,
+        DELETE_SVDIR        = 0x0080,
+        DELETE_SVSTEER      = 0x0100,
+        DELETE_SADATA       = 0x0200,
+        DELETE_RTI          = 0x0400,
+        DELETE_CELLDB_INFO  = 0x8000,
+        DELETE_ALL          = 0xFFFF
+    };
+
+    /*
+     * Opens the interface and provides the callback routines
+     * to the implementation of this interface.
+     *
+     * @param callback Callback interface for IGnss.
+     *
+     * @return success Returns true on success.
+     */
+    setCallback(IGnssCallback callback) generates (bool success);
+
+    /*
+     * Starts navigating.
+     *
+     * @return success Returns true on success.
+     */
+    start() generates (bool success);
+
+    /*
+     * Stops navigating.
+     *
+     * @return success Returns true on success.
+     */
+    stop() generates (bool success);
+
+    /*
+     * Closes the interface.
+     */
+    cleanup();
+
+    /*
+     * Injects the current time.
+     *
+     * @param timeMs This is the UTC time received from the NTP server, its value
+     * is given in milliseconds since January 1, 1970.
+     * @param timeReferenceMs The corresponding value of
+     * SystemClock.elapsedRealtime() from the device when the NTP response was
+     * received in milliseconds.
+     * @param uncertaintyMs Uncertainty associated with the value represented by
+     * time. Represented in milliseconds.
+     *
+     * @return success Returns true if the operation is successful.
+     *
+    injectTime(GnssUtcTime timeMs, int64_t timeReferenceMs, int32_t uncertaintyMs)
+        generates (bool success);
+
+    /*
+     * Injects current location from another location provider (typically cell
+     * ID).
+     *
+     * @param latitudeDegrees Measured in Degrees.
+     * @param longitudeDegrees Measured in Degrees.
+     * @param accuracyMeters Measured in meters.
+     *
+     * @return success Returns true if successful.
+     */
+    injectLocation(double latitudeDegrees, double longitudeDegrees, float accuracyMeters)
+        generates (bool success);
+
+    /*
+     * Specifies that the next call to start will not use the
+     * information defined in the flags. GnssAidingData value of DELETE_ALL is
+     * passed for a cold start.
+     *
+     * @param aidingDataFlags Flags specifying the aiding data to be deleted.
+     */
+    deleteAidingData(GnssAidingData aidingDataFlags);
+
+    /*
+     * @param mode  Parameter must be one of MS_BASED or STANDALONE.
+     * It is allowed by the platform (and it is recommended) to fallback to
+     * MS_BASED if MS_ASSISTED is passed in, and MS_BASED is supported.
+     * @recurrence GNSS postion recurrence value, either periodic or single.
+     * @param minIntervalMs Represents the time between fixes in milliseconds.
+     * @param preferredAccuracyMeters Represents the requested fix accuracy in meters.
+     * @param preferredTimeMs Represents the requested time to first fix in milliseconds.
+
+     * @return success Returns true if successful.
+     */
+    setPositionMode(GnssPositionMode mode, GnssPositionRecurrence recurrence,
+                    uint32_t minIntervalMs, uint32_t preferredAccuracyMeters,
+                    uint32_t preferredTimeMs)
+        generates (bool success);
+
+    /*
+     * This method returns the IAGnssRil Interface.
+     *
+     * @return infc Handle to the IAGnssRil interface.
+     */
+    getExtensionAGnssRil() generates (IAGnssRil infc);
+
+    /*
+     * This method returns the IGnssGeofencing Interface.
+     *
+     * @return infc Handle to the IGnssGeofencing interface.
+     */
+    getExtensionGnssGeofencing() generates(IGnssGeofencing infc);
+
+    /*
+     * This method returns the IAGnss Interface.
+     *
+     * @return infc Handle to the IAGnss interface.
+     */
+    getExtensionAGnss() generates (IAGnss infc);
+
+    /*
+     * This method returns the IGnssNi interface.
+     *
+     * @return infc Handle to the IGnssNi interface.
+     */
+    getExtensionGnssNi() generates (IGnssNi infc);
+
+    /*
+     * This method returns the IGnssMeasurement interface.
+     *
+     * @return infc Handle to the IGnssMeasurement interface.
+     */
+    getExtensionGnssMeasurement() generates (IGnssMeasurement infc);
+
+    /*
+     * This method returns the IGnssNavigationMessage interface.
+     *
+     * @return infc Handle to the IGnssNavigationMessage interface.
+     */
+    getExtensionGnssNavigationMessage() generates (IGnssNavigationMessage infc);
+
+    /*
+     * This method returns the IGnssXtra interface.
+     *
+     * @return infc Handle to the IGnssXtra interface.
+     */
+    getExtensionXtra() generates (IGnssXtra infc);
+
+    /*
+     * This method returns the IGnssDebug interface.
+     *
+     * @return infc Handle to the IGnssDebug interface.
+     */
+    getExtensionGnssDebug() generates (IGnssDebug infc);
+};
diff --git a/gnss/1.0/IGnssCallback.hal b/gnss/1.0/IGnssCallback.hal
new file mode 100644 (file)
index 0000000..5234688
--- /dev/null
@@ -0,0 +1,222 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+/*
+ * The interface is required for the HAL to communicate certain information
+ * like status and location info back to the platform, the platform implements
+ * the interfaces and passes a handle to the HAL.
+ */
+interface IGnssCallback {
+    /* Flags for the gnssSetCapabilities callback. */
+    enum Capabilities : uint32_t {
+        /*
+         * GNSS HAL schedules fixes for RECURRENCE_PERIODIC mode.
+         * If this is not set, then the framework will use 1000ms for
+         * minInterval and will call start() and stop() to schedule the GNSS.
+         */
+        SCHEDULING     = 1 << 0,
+        /** GNSS supports MS-Based AGNSS mode */
+        MSB            = 1 << 1,
+        /** GNSS supports MS-Assisted AGNSS mode */
+        MSA            = 1 << 2,
+        /** GNSS supports single-shot fixes */
+        SINGLE_SHOT    = 1 << 3,
+        /** GNSS supports on demand time injection */
+        ON_DEMAND_TIME = 1 << 4,
+        /** GNSS supports Geofencing  */
+        GEOFENCING     = 1 << 5,
+        /** GNSS supports Measurements. */
+        MEASUREMENTS   = 1 << 6,
+        /** GNSS supports Navigation Messages */
+        NAV_MESSAGES   = 1 << 7,
+    };
+
+    /* GNSS status event values. */
+    enum GnssStatusValue : uint16_t {
+        /** GNSS status unknown. */
+        STATUS_NONE    = 0,
+        /** GNSS has begun navigating. */
+        SESSION_BEGIN  = 1,
+        /** GNSS has stopped navigating. */
+        SESSION_END    = 2,
+        /** GNSS has powered on but is not navigating. */
+        ENGINE_ON      = 3,
+        /** GNSS is powered off. */
+        ENGINE_OFF     = 4
+    };
+
+    /*
+     * Flags that indicate information about the satellite
+     */
+    enum GnssSvFlags : uint8_t {
+        FLAGS_NONE          = 0,
+        HAS_EPHEMERIS_DATA  = 1 << 0,
+        HAS_ALMANAC_DATA    = 1 << 1,
+        USED_IN_FIX         = 1 << 2
+    };
+
+    struct GnssSvInfo {
+        /*
+         * Pseudo-random number for the SV, or FCN/OSN number for Glonass. The
+         * distinction is made by looking at constellation field. Values must be
+         * in the range of:
+         *
+         * - GNSS:    1-32
+         * - SBAS:    120-151, 183-192
+         * - GLONASS: 1-24, the orbital slot number (OSN), if known.  Or, if not:
+         *            93-106, the frequency channel number (FCN) (-7 to +6) offset by
+         *            + 100
+         *            i.e. report an FCN of -7 as 93, FCN of 0 as 100, and FCN of +6
+         *            as 106.
+         * - QZSS:    193-200
+         * - Galileo: 1-36
+         * - Beidou:  1-37
+         */
+        int16_t svid;
+
+        /*
+         * Defines the constellation of the given SV.
+         */
+        GnssConstellationType constellation;
+
+        /*
+         * Carrier-to-noise density in dB-Hz, typically in the range [0, 63].
+         * It contains the measured C/N0 value for the signal at the antenna port.
+         *
+         * This is a mandatory value.
+         */
+        float cN0Dbhz;
+
+        /** Elevation of SV in degrees. */
+        float elevationDegrees;
+
+        /** Azimuth of SV in degrees. */
+        float azimuthDegrees;
+
+        /*
+         * Contains additional data about the given SV.
+         */
+        GnssSvFlags svFlag;
+    };
+
+    /*
+     * Represents SV status.
+     */
+    struct GnssSvStatus {
+        /*
+         * Number of GNSS SVs currently visible, refers to the SVs stored in sv_list
+         */
+        int32_t numSvs;
+
+        /*
+         * Pointer to an array of SVs information for all GNSS constellations,
+         * except GNSS, which is reported using svList
+         */
+        GnssSvInfo[ConstS32:GNSS_MAX_SVS] gnssSvList;
+
+    };
+
+    /*
+     * Called when a GNSS location is available.
+     *
+     * @param location Location information from HAL.
+     */
+    gnssLocationCb(GnssLocation location);
+
+    /*
+     * Called to communicate the status of the GNSS engine.
+     *
+     * @param status Status information from HAL.
+     */
+    gnssStatusCb(GnssStatusValue status);
+
+    /*
+     * @param svInfo SV status information from HAL.
+     */
+    gnssSvStatusCb(GnssSvStatus svInfo);
+
+    /*
+     * Called when NMEA data is available.
+     * Callback for reporting NMEA sentences.
+     *
+     * @param timestamp Marks the instance of reporting.
+     * @param nmea Follows standard NMEA 0183. Each sentence begins with a '$'
+     * and ends with a carriage return/line feed sequence and can be no longer
+     * than 80 characters of visible text (plus the line terminators). The data
+     * is contained within this single line with data items separated by commas.
+     * The data itself is just ascii text and may extend over multiple sentences
+     * in certain specialized instances but is normally fully contained in one
+     * variable length sentence. The data may vary in the amount of precision
+     * contained in the message. For example time might be indicated to decimal
+     * parts of a second or location may be shown with 3 or even 4 digits after
+     * the decimal point. Programs that read the data must only use the commas
+     * to determine the field boundaries and not depend on column positions.
+     * There is a provision for a checksum at the end of each sentence which may
+     * or may not be checked by the unit that reads the data. The checksum field
+     * consists of a '*' and two hex digits representing an 8 bit exclusive OR
+     * of all characters between, but not including, the '$' and '*'.
+     */
+    gnssNmeaCb(GnssUtcTime timestamp, string nmea);
+
+    /*
+     * Callback to inform framework of the GNSS engine's capabilities.
+     *
+     * @param capabilities Capability parameter is a bit field of
+     * the Capabilities enum.
+     */
+    gnssSetCapabilitesCb(uint32_t capabilities);
+
+    /*
+     * Callback utility for acquiring the GNSS wakelock. This can be used to prevent
+     * the CPU from suspending while handling GNSS events.
+     */
+    gnssAcquireWakelockCb();
+
+    /** Callback utility for releasing the GNSS wakelock. */
+    gnssReleaseWakelockCb();
+
+    /** Callback for requesting NTP time */
+    gnssRequestTimeCb();
+
+    /*
+     * Provides information about how new the underlying GPS/GNSS hardware and
+     * software is.
+     *
+     * This information will be available for Android Test Applications. If a GNSS
+     * HAL does not provide this information, it will be considered "2015 or
+     * earlier".
+     *
+     * If a GNSS HAL does provide this information, then newer years will need to
+     * meet newer CTS standards. E.g. if the date are 2016 or above, then N+ level
+     * GnssMeasurement support will be verified.
+     */
+    struct GnssSystemInfo{
+        /*
+         * year in which the last update was made to the underlying hardware/firmware
+         * used to capture GNSS signals, e.g. 2016
+         */
+        uint16_t yearOfHw;
+    };
+
+    /*
+     * Callback to inform framework of the engine's hardware version information.
+     *
+     * @param info GnssSystemInfo about the GPS/GNSS hardware.
+     */
+    gnssSetSystemInfoCb(GnssSystemInfo info);
+};
diff --git a/gnss/1.0/IGnssDebug.hal b/gnss/1.0/IGnssDebug.hal
new file mode 100644 (file)
index 0000000..b0ac69d
--- /dev/null
@@ -0,0 +1,122 @@
+package android.hardware.gnss@1.0;
+
+/* Extended interface for DEBUG support. */
+interface IGnssDebug {
+    enum SatelliteEphemerisType : uint32_t {
+        /* no information is known to the gnss hardware, about this satellite */
+        UNKNOWN,
+        /*  this satellite is known to exist */
+        KNOWN,
+        /*  this satellite is not known to exist */
+        NONEXISTENT,
+        /* Only Almanac (approximate) location known for this satellite */
+        ALMANAC_ONLY,
+        /* Ephemeris is known from demodulating the signal on device */
+        DEMODULATED,
+        /* Ephemeris has been provided by SUPL */
+        SUPL_PROVIDED,
+        /* Ephemeris has been provided by another server */
+        OTHER_SERVER_PROVIDED,
+        /*
+         * Predicted ephemeris has been provided by a server
+         * (e.g. Xtra, Extended Ephemeris, etc...)
+         */
+        SERVER_PREDICTED,
+        /*
+         * Predicted ephemeris in use, generated locally on the device (e.g. from prior
+         * ephemeris)
+         */
+        LOCALLY_PREDICTED
+    };
+
+    /*
+     * Provides the current best known position from any
+     * source (GNSS or injected assistance).
+     */
+    struct PositionDebug {
+        /*
+         * Validity of the data in this struct. False only if no
+         * latitude/longitude information is known.
+         * /
+        bool valid;
+        /* Latitude expressed in degrees */
+        double latitudeDegrees;
+        /* Longitude expressed in degrees */
+        double longitudeDegrees;
+        /* Altitude above ellipsoid expressed in meters */
+        float altitudeDegrees;
+        /*
+         * estimated horizontal accuracy of position expressed in meters, radial,
+         * 68% confidence.
+         */
+        double accuracyMeters;
+        /*
+         * Time duration before this report that this position information was
+         * valid.
+         */
+        float ageSeconds;
+    };
+
+    /*
+     * Provides the current best known UTC time estimate.
+     */
+    struct TimeDebug {
+        /*
+         * Validity of the data in the struct.
+         * False if current time is unknown.
+         */
+        bool valid;
+        /*
+         * UTC time estimate.
+         */
+        GnssUtcTime timeEstimate;
+        /* 68% error estimate in time. */
+        float timeUncertaintyNs;
+    };
+
+    /*
+     * Provides a single satellite info that has decoded navigation data.
+     */
+    struct SatelliteData {
+        /* Satellite vehicle ID number */
+        int16_t svid;
+        /* Defines the constellation type of the given SV. */
+        GnssConstellationType constellation;
+        /* Defines the ephemeris type of the satellite. */
+        SatelliteEphemerisType ephemerisType;
+        /*
+         * Time duration before this report, that the ephemeris source was last
+         * updated, e.g. latest demodulation, or latest server download.
+         * Set to 0 when ephemerisType is UNKNOWN.
+         */
+        float ephemerisAgeSeconds;
+    };
+
+    /*
+     * Provides a set of debug information that is filled by the GNSS chipset
+     * when the method getDebugData() is invoked.
+     */
+    struct DebugData {
+        /* Current best known position. */
+        PositionDebug position;
+        /* Current best know time estimate */
+        TimeDebug time;
+        /*
+         * Provides a list of the decoded satellite ephemeris.
+         * Should provide a complete list for all constellations device can track,
+         * including GnssConstellationType UNKNOWN.
+         */
+        vec<SatelliteData> satelliteDataArray;
+
+    };
+
+    /*
+     * This methods requests position, time and satellite ephemeris debug information
+     * from the HAL.
+     *
+     * @return ret debugData information from GNSS Hal that contains the current best
+     * known position, best known time estimate and a complete list of
+     * constellations that the device can track.
+     */
+    getDebugData() generates (DebugData debugData);
+};
diff --git a/gnss/1.0/IGnssGeofenceCallback.hal b/gnss/1.0/IGnssGeofenceCallback.hal
new file mode 100644 (file)
index 0000000..06eb62a
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+/*
+ * GNSS Geofence.
+ * There are 3 states associated with a Geofence: Inside, Outside, Unknown.
+ * There are 3 transitions: ENTERED, EXITED, UNCERTAIN.
+ *
+ * An example state diagram with confidence level: 95% and Unknown time limit
+ * set as 30 secs is shown below. (confidence level and Unknown time limit are
+ * explained latter).
+ *                         ____________________________
+ *                        |       Unknown (30 secs)   |
+ *                         """"""""""""""""""""""""""""
+ *                            ^ |                  |  ^
+ *                   UNCERTAIN| |ENTERED     EXITED|  |UNCERTAIN
+ *                            | v                  v  |
+ *                        ________    EXITED     _________
+ *                       | Inside | -----------> | Outside |
+ *                       |        | <----------- |         |
+ *                        """"""""    ENTERED    """""""""
+ *
+ * Inside state: We are 95% confident that the user is inside the geofence.
+ * Outside state: We are 95% confident that the user is outside the geofence
+ * Unknown state: Rest of the time.
+ *
+ * The Unknown state is better explained with an example:
+ *
+ *                            __________
+ *                           |         c|
+ *                           |  ___     |    _______
+ *                           |  |a|     |   |   b   |
+ *                           |  """     |    """""""
+ *                           |          |
+ *                            """"""""""
+ * In the diagram above, "a" and "b" are 2 geofences and "c" is the accuracy
+ * circle reported by the GNSS subsystem. Now with regard to "b", the system is
+ * confident that the user is outside. But with regard to "a" is not confident
+ * whether it is inside or outside the geofence. If the accuracy remains the
+ * same for a sufficient period of time, the UNCERTAIN transition must be
+ * triggered with the state set to Unknown. If the accuracy improves later, an
+ * appropriate transition must be triggered.  This "sufficient period of time"
+ * is defined by the parameter in the addGeofenceArea API.
+ * In other words, Unknown state can be interpreted as a state in which the
+ * GNSS subsystem isn't confident enough that the user is either inside or
+ * outside the Geofence. It moves to Unknown state only after the expiry of the
+ * timeout.
+ *
+ * The geofence callback needs to be triggered for the ENTERED and EXITED
+ * transitions, when the GNSS system is confident that the user has entered
+ * (Inside state) or exited (Outside state) the Geofence. An implementation
+ * which uses a value of 95% as the confidence is recommended. The callback
+ * must be triggered only for the transitions requested by the
+ * addGeofenceArea method.
+ *
+ * Even though the diagram and explanation talks about states and transitions,
+ * the callee is only interested in the transistions. The states are mentioned
+ * here for illustrative purposes.
+ *
+ * Startup Scenario: When the device boots up, if an application adds geofences,
+ * and then we get an accurate GNSS location fix, it needs to trigger the
+ * appropriate (ENTERED or EXITED) transition for every Geofence it knows about.
+ * By default, all the Geofences will be in the Unknown state.
+ *
+ * When the GNSS system is unavailable, gnssGeofenceStatusCb must be
+ * called to inform the upper layers of the same. Similarly, when it becomes
+ * available the callback must be called. This is a global state while the
+ * UNKNOWN transition described above is per geofence.
+ *
+ * An important aspect to note is that users of this API (framework), will use
+ * other subsystems like wifi, sensors, cell to handle Unknown case and
+ * hopefully provide a definitive state transition to the third party
+ * application. GNSS Geofence will just be a signal indicating what the GNSS
+ * subsystem knows about the Geofence.
+ *
+ */
+
+interface IGnssGeofenceCallback {
+    enum GeofenceTransition : int32_t {
+        ENTERED   = (1 << 0L),
+        EXITED    = (1 << 1L),
+        UNCERTAIN = (1 << 2L),
+    };
+
+    enum GeofenceAvailability : int32_t {
+        UNAVAILABLE = (1 << 0L),
+        AVAILABLE   = (1 << 1L),
+    };
+
+    enum GeofenceStatus : int32_t {
+        OPERATION_SUCCESS        = 0,
+        ERROR_TOO_MANY_GEOFENCES = -100,
+        ERROR_ID_EXISTS          = -101,
+        ERROR_ID_UNKNOWN         = -102,
+        ERROR_INVALID_TRANSITION = -103,
+        ERROR_GENERIC            = -149
+    };
+
+    /*
+     * The callback associated with the geofence transition.
+     * The callback must only be called when the caller is interested in that
+     * particular transition. For instance, if the caller is interested only in
+     * ENTERED transition, then the callback must not be called with the EXITED
+     * transition.
+     *
+     * IMPORTANT: If a transition is triggered resulting in this callback, the
+     * GNSS subsystem will wake up the application processor, if its in suspend
+     * state.
+     *
+     * @param geofenceId The id associated with the addGeofenceArea.
+     * @param location The current GNSS location.
+     * @param transition Can be one of ENTERED, EXITED or UNCERTAIN.
+     * @param timestamp Timestamp when the transition was detected.
+     *
+     */
+    gnssGeofenceTransitionCb(int32_t geofenceId, GnssLocation location,
+        GeofenceTransition transition, GnssUtcTime timestamp);
+
+    /*
+     * The callback associated with the availability of the GNSS system for
+     * geofencing monitoring. If the GNSS system determines that it cannot monitor
+     * geofences because of lack of reliability or unavailability of the GNSS
+     * signals, it will call this callback with UNAVAILABLE parameter.
+     *
+     * @param status - UNAVAILABLE or AVAILABLE.
+     * @param lastLocation - Last known location.
+     */
+    gnssGeofenceStatusCb(GeofenceAvailability status, GnssLocation lastLocation);
+
+    /*
+     * The callback associated with the addGeofence call.
+     *
+     * @param geofenceId Id of the geofence.
+     * @param status Will be OPERATION_SUCCESS if the geofence
+     * add was successful. Will be ERROR_TOO_MANY_GEOFENCES if the
+     * geofence limit has been reached.
+     * Will be ERROR_ID_EXISTS if geofence with id already exists.
+     * Will be ERROR_INVALID_TRANSITION if the monitorTransition contains an
+     * invalid transition.
+     * Will be ERROR_GENERIC for other errors.
+     */
+    gnssGeofenceAddCb(int32_t geofenceId, GeofenceStatus status);
+
+    /*
+     * The callback associated with the removeGeofence call.
+     *
+     * @param geofenceId Id of the geofence.
+     * @param status Will return OPERATION_SUCCESS if successful.
+     * Will be ERROR_ID_UNKNOWN for invalid id and
+     * ERROR_GENERIC for others.
+     */
+    gnssGeofenceRemoveCb(int32_t geofenceId, GeofenceStatus status);
+
+    /*
+     * The callback associated with the pauseGeofence call.
+     *
+     * @param geofenceId Id of the geofence.
+     * @param status Will be OPERATION_SUCCESS if success.
+     * Will be ERROR_ID_UNKNOWN for invalid id. Will be
+     * ERROR_INVALID_TRANSITION when monitorTransitions is invalid.
+     * Will be ERROR_GENERIC for other err errors.
+     */
+    gnssGeofencePauseCb(int32_t geofenceId, GeofenceStatus status);
+
+    /*
+     * The callback associated with the resumeGeofence call.
+     *
+     * @param geofenceId - Id of the geofence.
+     * @param status Will be OPERATION_SUCCESS if successful.
+     * Will be ERROR_ID_UNKNOWN for invalid id and ERROR_GENERIC for others.
+     */
+    gnssGeofenceResumeCb(int32_t geofenceId, GeofenceStatus status);
+};
diff --git a/gnss/1.0/IGnssGeofencing.hal b/gnss/1.0/IGnssGeofencing.hal
new file mode 100644 (file)
index 0000000..89301f4
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+import IGnssGeofenceCallback;
+
+/* Extended interface for GNSS Geofencing support */
+interface IGnssGeofencing {
+    /*
+     * Opens the geofence interface and provides the callback routines
+     * to the HAL.
+     *
+     * @param callback Handle to the IGnssGeofenceCallback interface.
+     */
+    setCallback(IGnssGeofenceCallback callback);
+
+    /*
+     * Add a geofence area. This api currently supports circular geofences.
+     *
+     * @param geofenceId The id for the geofence. If a geofence with this id
+     * already exists, an error value (ERROR_ID_EXISTS) must be returned.
+     * @param latitudeDegrees The latitude(in degrees) for the geofence lastTransition.
+     * @param longtitudeDegrees The longitude(in degrees) for the geofence lastTransition.
+     * @param radiusMeters The radius(in meters) for the geofence lastTransition.
+     * @param lastTransition The current state of the geofence. For example, if
+     * the system already knows that the user is inside the geofence, this will
+     * be set to ENTERED. In most cases, it will be UNCERTAIN.
+     * @param monitorTransitions - Which transitions to monitor. Bitwise OR of
+     * ENTERED, EXITED and UNCERTAIN.
+     * @param notificationResponsivenessMs - Defines the best-effort description
+     * of how soon must the callback be called when the transition associated
+     * with the Geofence is triggered. For instance, if set to 1000 millseconds
+     * with ENTERED, the callback must be called 1000 milliseconds within entering
+     * the geofence. This parameter is defined in milliseconds.
+     * NOTE: This is not to be confused with the rate that the GNSS is polled at.
+     * It is acceptable to dynamically vary the rate of sampling the GNSS for
+     * power-saving reasons; thus the rate of sampling may be faster or slower
+     * than this.
+     * @param unknownTimerMs - The time limit after which the UNCERTAIN transition
+     * must be triggered. This parameter is defined in milliseconds.
+     */
+    addGeofenceArea(int32_t geofenceId, double latitudeDegrees, double longitudeDegrees,
+        double radiusMeters, GeofenceTransition lastTransition,
+        int32_t monitorTransitions, uint32_t notificationResponsivenessMs,
+        uint32_t unknownTimerMs);
+
+    /*
+     * Pause monitoring a particular geofence.
+     *
+     * @param geofenceId The id for the geofence.
+     */
+    pauseGeofence(int32_t geofenceId);
+
+    /*
+     * Resume monitoring a particular geofence.
+     *
+     * @param geofenceId - The id for the geofence.
+     * @param monitorTransitions Specifies which transitions to monitor.
+     * It can be a bitwise OR of ENTERED, EXITED and
+     * UNCERTAIN. This supersedes the value associated
+     * provided in the addGeofenceArea call.
+     */
+    resumeGeofence(int32_t geofenceId, int32_t monitorTransitions);
+
+    /*
+     * Remove a geofence area. After the function returns, no notifications
+     * must be sent.
+     *
+     * @param geofenceId The id of the geofence.
+     */
+    removeGeofenceArea(int32_t geofenceId);
+};
diff --git a/gnss/1.0/IGnssMeasurement.hal b/gnss/1.0/IGnssMeasurement.hal
new file mode 100644 (file)
index 0000000..5156b32
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+import IGnssMeasurementCallback;
+
+/*
+ * Extended interface for GNSS Measurements support.
+ */
+interface IGnssMeasurement {
+    enum GnssMeasurementStatus : int32_t {
+        SUCCESS = 0,
+        ERROR_ALREADY_INIT = -100,
+        ERROR_GENERIC = -101
+    };
+
+    /*
+     * Initializes the interface and registers the callback routines with the HAL.
+     * After a successful call to 'setCallback' the HAL must begin to provide updates at
+     * an average output rate of 1Hz (occasional
+     * intra-measurement time offsets in the range from 0-2000msec can be
+     * tolerated.)
+     *
+     * @param callback Handle to GnssMeasurement callback interface.
+     *
+     * @return initRet Returns SUCCESS if successful.
+     * Returns ERROR_ALREADY_INIT if a callback has already been
+     * registered without a corresponding call to 'close'.
+     * Returns ERROR_GENERIC for any other error. The HAL must
+     * not generate any other updates upon returning this error code.
+     */
+    setCallback(IGnssMeasurementCallback callback) generates (int32_t initRet);
+
+    /*
+     * Stops updates from the HAL, and unregisters the callback routines.
+     * After a call to close(), the previously registered callbacks must be
+     * considered invalid by the HAL.
+     * If close() is invoked without a previous setCallback, this function must perform
+     * no work.
+     */
+    close();
+
+};
diff --git a/gnss/1.0/IGnssMeasurementCallback.hal b/gnss/1.0/IGnssMeasurementCallback.hal
new file mode 100644 (file)
index 0000000..3650892
--- /dev/null
@@ -0,0 +1,554 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+/* The callback interface to report measurements from the HAL. */
+interface IGnssMeasurementCallback {
+    /*
+     * Flags to indicate what fields in GnssClock are valid.
+     */
+    enum GnssClockFlags : uint16_t {
+        /** A valid 'leap second' is stored in the data structure. */
+        HAS_LEAP_SECOND        = 1 << 0,
+        /** A valid 'time uncertainty' is stored in the data structure. */
+        HAS_TIME_UNCERTAINTY   = 1 << 1,
+        /** A valid 'full bias' is stored in the data structure. */
+        HAS_FULL_BIAS          = 1 << 2,
+        /** A valid 'bias' is stored in the data structure. */
+        HAS_BIAS               = 1 << 3,
+        /** A valid 'bias uncertainty' is stored in the data structure. */
+        HAS_BIAS_UNCERTAINTY   = 1 << 4,
+        /** A valid 'drift' is stored in the data structure. */
+        HAS_DRIFT              = 1 << 5,
+        /** A valid 'drift uncertainty' is stored in the data structure. */
+        HAS_DRIFT_UNCERTAINTY  = 1 << 6
+    };
+
+    /*
+     * Flags to indicate what fields in GnssMeasurement are valid.
+     */
+    enum GnssMeasurementFlags : uint32_t {
+        /** A valid 'snr' is stored in the data structure. */
+        HAS_SNR                        = 1 << 0,
+        /** A valid 'carrier frequency' is stored in the data structure. */
+        HAS_CARRIER_FREQUENCY          = 1 << 9,
+        /** A valid 'carrier cycles' is stored in the data structure. */
+        HAS_CARRIER_CYCLES             = 1 << 10,
+        /** A valid 'carrier phase' is stored in the data structure. */
+        HAS_CARRIER_PHASE              = 1 << 11,
+        /** A valid 'carrier phase uncertainty' is stored in the data structure. */
+        HAS_CARRIER_PHASE_UNCERTAINTY  = 1 << 12
+    };
+
+    /*
+     * Enumeration of available values for the GNSS Measurement's multipath
+     * indicator.
+     */
+    enum GnssMultipathIndicator : uint8_t {
+        /** The indicator is not available or unknown. */
+        INDICATOR_UNKNOWN      = 0,
+        /** The measurement is indicated to be affected by multipath. */
+        INDICATOR_PRESENT      = 1,
+        /** The measurement is indicated to be not affected by multipath. */
+        INDICATIOR_NOT_PRESENT = 2
+    };
+
+    /*
+     * Flags indicating the GNSS measurement state.
+     *
+     * The expected behavior here is for GNSS HAL to set all the flags that applies.
+     * For example, if the state for a satellite is only C/A code locked and bit
+     * synchronized, and there is still millisecond ambiguity, the state must be
+     * set as:
+     *
+     * STATE_CODE_LOCK | STATE_BIT_SYNC |  STATE_MSEC_AMBIGUOUS
+     *
+     * If GNSS is still searching for a satellite, the corresponding state must be
+     * set to STATE_UNKNOWN(0).
+     */
+    enum GnssMeasurementState : uint32_t {
+        STATE_UNKNOWN                = 0,
+        STATE_CODE_LOCK              = 1 << 0,
+        STATE_BIT_SYNC               = 1 << 1,
+        STATE_SUBFRAME_SYNC          = 1 << 2,
+        STATE_TOW_DECODED            = 1 << 3,
+        STATE_MSEC_AMBIGUOUS         = 1 << 4,
+        STATE_SYMBOL_SYNC            = 1 << 5,
+        STATE_GLO_STRING_SYNC        = 1 << 6,
+        STATE_GLO_TOD_DECODED        = 1 << 7,
+        STATE_BDS_D2_BIT_SYNC        = 1 << 8,
+        STATE_BDS_D2_SUBFRAME_SYNC   = 1 << 9,
+        STATE_GAL_E1BC_CODE_LOCK     = 1 << 10,
+        STATE_GAL_E1C_2ND_CODE_LOCK  = 1 << 11,
+        STATE_GAL_E1B_PAGE_SYNC      = 1 << 12,
+        STATE_SBAS_SYNC              = 1 << 13
+    };
+
+    /*
+     * Flags indicating the Accumulated Delta Range's states.
+     */
+    enum GnssAccumulatedDeltaRangeState : uint16_t {
+        ADR_STATE_UNKNOWN    = 0,
+        ADR_STATE_VALID      = 1 << 0,
+        ADR_STATE_RESET      = 1 << 1,
+        ADR_STATE_CYCLE_SLIP = 1 << 2,
+    };
+
+    /*
+     * Represents an estimate of the GNSS clock time.
+     */
+    struct GnssClock {
+        /*
+         * A set of flags indicating the validity of the fields in this data
+         * structure.
+         */
+        GnssClockFlags gnssClockFlags;
+
+        /*
+         * Leap second data.
+         * The sign of the value is defined by the following equation:
+         *      utcTimeNs = timeNs - (fullBiasNs + biasNs) - leapSecond *
+         *      1,000,000,000
+         *
+         * If this data is available, gnssClockFlags must contain
+         * HAS_LEAP_SECOND.
+         */
+        int16_t leapSecond;
+
+        /*
+         * The GNSS receiver internal clock value. This is the local hardware clock
+         * value.
+         *
+         * For local hardware clock, this value is expected to be monotonically
+         * increasing while the hardware clock remains powered on. (For the case of a
+         * HW clock that is not continuously on, see the
+         * hwClockDiscontinuityCount field). The receiver's estimate of GNSS time
+         * can be derived by subtracting the sum of fullBiasNs and biasNs (when
+         * available) from this value.
+         *
+         * This GNSS time must be the best estimate of current GNSS time
+         * that GNSS receiver can achieve.
+         *
+         * Sub-nanosecond accuracy can be provided by means of the 'biasNs' field.
+         * The value contains the timeUncertaintyNs in it.
+         *
+         * This field is mandatory.
+         */
+        int64_t timeNs;
+
+        /*
+         * 1-Sigma uncertainty associated with the clock's time in nanoseconds.
+         * The uncertainty is represented as an absolute (single sided) value.
+         *
+         * If the data is available, gnssClockFlags must contain
+         * HAS_TIME_UNCERTAINTY. Ths value is ideally zero, as the time
+         * 'latched' by timeNs is defined as the reference clock vs. which all
+         * other times (and corresponding uncertainties) are measured.
+         */
+        double timeUncertaintyNs;
+
+        /*
+         * The difference between hardware clock ('time' field) inside GNSS receiver
+         * and the true GNSS time since 0000Z, January 6, 1980, in nanoseconds.
+         *
+         * The sign of the value is defined by the following equation:
+         *      local estimate of GNSS time = timeNs - (fullBiasNs + biasNs)
+         *
+         * This value is mandatory if the receiver has estimated GNSS time. If the
+         * computed time is for a non-GNSS constellation, the time offset of that
+         * constellation to GNSS has to be applied to fill this value. The error
+         * estimate for the sum of this and the biasNs is the biasUncertaintyNs,
+         * and the caller is responsible for using this uncertainty (it can be very
+         * large before the GNSS time has been solved for.) If the data is available
+         * gnssClockFlags must contain HAS_FULL_BIAS.
+         */
+        int64_t fullBiasNs;
+
+        /*
+         * Sub-nanosecond bias.
+         * The error estimate for the sum of this and the fullBiasNs is the
+         * biasUncertaintyNs.
+         *
+         * If the data is available gnssClockFlags must contain HAS_BIAS. If GNSS
+         * has computed a position fix. This value is mandatory if the receiver has
+         * estimated GNSS time.
+         */
+        double biasNs;
+
+        /*
+         * 1-Sigma uncertainty associated with the local estimate of GNSS time (clock
+         * bias) in nanoseconds. The uncertainty is represented as an absolute
+         * (single sided) value.
+         *
+         * If the data is available gnssClockFlags must contain
+         * HAS_BIAS_UNCERTAINTY. This value is mandatory if the receiver
+         * has estimated GNSS time.
+         */
+        double biasUncertaintyNs;
+
+        /*
+         * The clock's drift in nanoseconds (per second).
+         *
+         * A positive value means that the frequency is higher than the nominal
+         * frequency, and that the (fullBiasNs + biasNs) is growing more positive
+         * over time.
+         *
+         * The value contains the 'drift uncertainty' in it.
+         * If the data is available gnssClockFlags must contain HAS_DRIFT.
+         *
+         * This value is mandatory if the receiver has estimated GNSS time.
+         */
+        double driftNsps;
+
+        /*
+         * 1-Sigma uncertainty associated with the clock's drift in nanoseconds (per
+         * second).
+         * The uncertainty is represented as an absolute (single sided) value.
+         *
+         * If the data is available gnssClockFlags must contain
+         * HAS_DRIFT_UNCERTAINTY. If GNSS has computed a position fix this
+         * field is mandatory and must be populated.
+         */
+        double driftUncertaintyNsps;
+
+        /*
+         * When there are any discontinuities in the HW clock, this field is
+         * mandatory.
+         *
+         * A "discontinuity" is meant to cover the case of a switch from one source
+         * of clock to another.  A single free-running crystal oscillator (XO)
+         * will generally not have any discontinuities, and this can be set and
+         * left at 0.
+         *
+         * If, however, the timeNs value (HW clock) is derived from a composite of
+         * sources, that is not as smooth as a typical XO, or is otherwise stopped &
+         * restarted, then this value shall be incremented each time a discontinuity
+         * occurs.  (E.g. this value can start at zero at device boot-up and
+         * increment each time there is a change in clock continuity. In the
+         * unlikely event that this value reaches full scale, rollover (not
+         * clamping) is required, such that this value continues to change, during
+         * subsequent discontinuity events.)
+         *
+         * While this number stays the same, between GnssClock reports, it can be
+         * safely assumed that the timeNs value has been running continuously, e.g.
+         * derived from a single, high quality clock (XO like, or better, that is
+         * typically used during continuous GNSS signal sampling.)
+         *
+         * It is expected, esp. during periods where there are few GNSS signals
+         * available, that the HW clock be discontinuity-free as long as possible,
+         * as this avoids the need to use (waste) a GNSS measurement to fully
+         * re-solve for the GNSS clock bias and drift, when using the accompanying
+         * measurements, from consecutive GnssData reports.
+         */
+        uint32_t hwClockDiscontinuityCount;
+
+    };
+
+    /*
+     * Represents a GNSS Measurement, it contains raw and computed information.
+     *
+     * All signal measurement information (e.g. svTime,
+     * pseudorangeRate, multipathIndicator) reported in this struct must be
+     * based on GNSS signal measurements only. You must not synthesize measurements
+     * by calculating or reporting expected measurements based on known or estimated
+     * position, velocity, or time.
+     */
+    struct GnssMeasurement{
+        /*
+         * A set of flags indicating the validity of the fields in this data
+         * structure.
+         */
+        GnssMeasurementFlags flags;
+
+        /*
+         * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+         * This is a mandatory value.
+         */
+        int16_t svid;
+
+        /*
+         * Defines the constellation of the given SV.
+         */
+        GnssConstellationType constellation;
+
+        /*
+         * Time offset at which the measurement was taken in nanoseconds.
+         * The reference receiver's time is specified by GnssData::clock::timeNs.
+         *
+         * The sign of timeOffsetNs is given by the following equation:
+         *      measurement time = GnssClock::timeNs + timeOffsetNs
+         *
+         * It provides an individual time-stamp for the measurement, and allows
+         * sub-nanosecond accuracy.
+         * This is a mandatory value.
+         */
+        double timeOffsetNs;
+
+        /*
+         * Per satellite sync state. It represents the current sync state for the
+         * associated satellite.
+         * Based on the sync state, the 'received GNSS tow' field must be interpreted
+         * accordingly.
+         *
+         * This is a mandatory value.
+         */
+        GnssMeasurementState state;
+
+        /*
+         * The received GNSS Time-of-Week at the measurement time, in nanoseconds.
+         * For GNSS & QZSS, this is the received GNSS Time-of-Week at the
+         * measurement time, in nanoseconds. The value is relative to the
+         * beginning of the current GNSS week.
+         *
+         * Given the highest sync state that can be achieved, per each satellite,
+         * valid range for this field can be:
+         * Searching       : [ 0       ] : STATE_UNKNOWN
+         * C/A code lock   : [ 0 1ms   ] : STATE_CODE_LOCK set
+         * Bit sync        : [ 0 20ms  ] : STATE_BIT_SYNC set
+         * Subframe sync   : [ 0  6s   ] : STATE_SUBFRAME_SYNC set
+         * TOW decoded     : [ 0 1week ] : STATE_TOW_DECODED set
+         *
+         * Note: If there is any ambiguity in integer millisecond,
+         * GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS must be set accordingly, in the
+         * 'state' field.
+         *
+         * This value must be populated if 'state' != STATE_UNKNOWN.
+         *
+         * For Glonass, this is the received Glonass time of day, at the
+         * measurement time in nanoseconds.
+         *
+         * Given the highest sync state that can be achieved, per each satellite,
+         * valid range for this field can be:
+         * Searching       : [ 0       ] : STATE_UNKNOWN set
+         * C/A code lock   : [ 0   1ms ] : STATE_CODE_LOCK set
+         * Symbol sync     : [ 0  10ms ] : STATE_SYMBOL_SYNC set
+         * Bit sync        : [ 0  20ms ] : STATE_BIT_SYNC set
+         * String sync     : [ 0    2s ] : STATE_GLO_STRING_SYNC set
+         * Time of day     : [ 0  1day ] : STATE_GLO_TOW_DECODED set
+         *
+         * For Beidou, this is the received Beidou time of week,
+         * at the measurement time in nanoseconds.
+         *
+         * Given the highest sync state that can be achieved, per each satellite,
+         * valid range for this field can be:
+         * Searching    : [ 0       ] : STATE_UNKNOWN set.
+         * C/A code lock: [ 0   1ms ] : STATE_CODE_LOCK set.
+         * Bit sync (D2): [ 0   2ms ] : STATE_BDS_D2_BIT_SYNC set.
+         * Bit sync (D1): [ 0  20ms ] : STATE_BIT_SYNC set.
+         * Subframe (D2): [ 0  0.6s ] : STATE_BDS_D2_SUBFRAME_SYNC set.
+         * Subframe (D1): [ 0    6s ] : STATE_SUBFRAME_SYNC set.
+         * Time of week : [ 0 1week ] : STATE_TOW_DECODED set.
+         *
+         * For Galileo, this is the received Galileo time of week,
+         * at the measurement time in nanoseconds.
+         *
+         * E1BC code lock   : [ 0  4ms ] : STATE_GAL_E1BC_CODE_LOCK set.
+         * E1C 2nd code lock: [ 0 100ms] : STATE_GAL_E1C_2ND_CODE_LOCK set.
+         * E1B page         : [ 0   2s ] : STATE_GAL_E1B_PAGE_SYNC set.
+         * Time of week     : [ 0 1week] : STATE_TOW_DECODED is set.
+         *
+         * For SBAS, this is received SBAS time, at the measurement time in
+         * nanoseconds.
+         *
+         * Given the highest sync state that can be achieved, per each satellite,
+         * valid range for this field can be:
+         * Searching    : [ 0     ] : STATE_UNKNOWN
+         * C/A code lock: [ 0 1ms ] : STATE_CODE_LOCK is set
+         * Symbol sync  : [ 0 2ms ] : STATE_SYMBOL_SYNC is set
+         * Message      : [ 0  1s ] : STATE_SBAS_SYNC is set
+         */
+        int64_t receivedSvTimeInNs;
+
+        /*
+         * 1-Sigma uncertainty of the Received GNSS Time-of-Week in nanoseconds.
+         *
+         * This value must be populated if 'state' != STATE_UNKNOWN.
+         */
+        int64_t receivedSvTimeUncertaintyInNs;
+
+        /*
+         * Carrier-to-noise density in dB-Hz, typically in the range [0, 63].
+         * It contains the measured C/N0 value for the signal at the antenna port.
+         *
+         * This is a mandatory value.
+         */
+        double cN0DbHz;
+
+        /*
+         * Pseudorange rate at the timestamp in m/s. The correction of a given
+         * Pseudorange Rate value includes corrections for receiver and satellite
+         * clock frequency errors. Ensure that this field is independent (see
+         * comment at top of GnssMeasurement struct.)
+         *
+         * It is mandatory to provide the 'uncorrected' 'pseudorange rate', and
+         * provide GnssClock's 'drift' field as well. When providing the
+         * uncorrected pseudorange rate, do not apply the corrections described above.)
+         *
+         * The value includes the 'pseudorange rate uncertainty' in it.
+         * A positive 'uncorrected' value indicates that the SV is moving away from
+         * the receiver.
+         *
+         * The sign of the 'uncorrected' 'pseudorange rate' and its relation to the
+         * sign of 'doppler shift' is given by the equation:
+         *      pseudorange rate = -k * doppler shift   (where k is a constant)
+         *
+         * This must be the most accurate pseudorange rate available, based on
+         * fresh signal measurements from this channel.
+         *
+         * It is mandatory that this value be provided at typical carrier phase PRR
+         * quality (few cm/sec per second of uncertainty, or better) - when signals
+         * are sufficiently strong & stable, e.g. signals from a GNSS simulator at >=
+         * 35 dB-Hz.
+         */
+        double pseudorangeRateMps;
+
+        /*
+         * 1-Sigma uncertainty of the pseudorangeRateMps.
+         * The uncertainty is represented as an absolute (single sided) value.
+         *
+         * This is a mandatory value.
+         */
+        double pseudorangeRateUncertaintyMps;
+
+        /*
+         * Accumulated delta range's state. It indicates whether ADR is reset or
+         * there is a cycle slip(indicating loss of lock).
+         *
+         * This is a mandatory value.
+         */
+        GnssAccumulatedDeltaRangeState accumulatedDeltaRangeState;
+
+        /*
+         * Accumulated delta range since the last channel reset in meters.
+         * A positive value indicates that the SV is moving away from the receiver.
+         *
+         * The sign of the 'accumulated delta range' and its relation to the sign of
+         * 'carrier phase' is given by the equation:
+         * accumulated delta range = -k * carrier phase (where k is a constant)
+         *
+         * This value must be populated if 'accumulated delta range state' !=
+         * ADR_STATE_UNKNOWN.
+         * However, it is expected that the data is only accurate when:
+         *      'accumulated delta range state' == ADR_STATE_VALID.
+         */
+        double accumulatedDeltaRangeM;
+
+        /*
+         * 1-Sigma uncertainty of the accumulated delta range in meters.
+         * This value must be populated if 'accumulated delta range state' !=
+         * ADR_STATE_UNKNOWN.
+         */
+        double accumulatedDeltaRangeUncertaintyM;
+
+        /*
+         * Carrier frequency at which codes and messages are modulated, it can
+         * be L1 or L2. If the field is not set, the carrier frequency is
+         * assumed to be L1.
+         *
+         * If the data is available, gnssClockFlags must contain
+         * HAS_CARRIER_FREQUENCY.
+         */
+        float carrierFrequencyHz;
+
+        /*
+         * The number of full carrier cycles between the satellite and the
+         * receiver. The reference frequency is given by the field
+         * 'carrierFrequencyHz'. Indications of possible cycle slips and
+         * resets in the accumulation of this value can be inferred from the
+         * accumulatedDeltaRangeState flags.
+         *
+         * If the data is available, gnssClockFlags must contain
+         * HAS_CARRIER_CYCLES.
+         */
+        int64_t carrierCycles;
+
+        /*
+         * The RF phase detected by the receiver, in the range [0.0, 1.0].
+         * This is usually the fractional part of the complete carrier phase
+         * measurement.
+         *
+         * The reference frequency is given by the field 'carrierFrequencyHz'.
+         * The value contains the 'carrier-phase uncertainty' in it.
+         *
+         * If the data is available, gnssClockFlags must contain
+         * HAS_CARRIER_PHASE.
+         */
+        double carrierPhase;
+
+        /*
+         * 1-Sigma uncertainty of the carrier-phase.
+         * If the data is available, gnssClockFlags must contain
+         * HAS_CARRIER_PHASE_UNCERTAINTY.
+         */
+        double carrierPhaseUncertainty;
+
+        /*
+         * An enumeration that indicates the 'multipath' state of the event.
+         *
+         * The multipath Indicator is intended to report the presence of overlapping
+         * signals that manifest as distorted correlation peaks.
+         *
+         * - if there is a distorted correlation peak shape, report that multipath
+         *   is MULTIPATH_INDICATOR_PRESENT.
+         * - if there is no distorted correlation peak shape, report
+         *   MULTIPATH_INDICATOR_NOT_PRESENT
+         * - if signals are too weak to discern this information, report
+         *   MULTIPATH_INDICATOR_UNKNOWN
+         *
+         * Example: when doing the standardized overlapping Multipath Performance
+         * test (3GPP TS 34.171) the Multipath indicator must report
+         * MULTIPATH_INDICATOR_PRESENT for those signals that are tracked, and
+         * contain multipath, and MULTIPATH_INDICATOR_NOT_PRESENT for those
+         * signals that are tracked and do not contain multipath.
+         */
+        GnssMultipathIndicator multipathIndicator;
+
+        /*
+         * Signal-to-noise ratio at correlator output in dB.
+         * If the data is available, gnssClockFlags must contain MEASUREMENT_HAS_SNR.
+         * This is the power ratio of the "correlation peak height above the
+         * observed noise floor" to "the noise RMS".
+         */
+        double snrDb;
+    };
+
+    /*
+     * Represents a reading of GNSS measurements. For devices where GnssSystemInfo's
+     * yearOfHw is set to 2016+, it is mandatory that these be provided, on
+     * request, when the GNSS receiver is searching/tracking signals.
+     *
+     * - Reporting of GNSS constellation measurements is mandatory.
+     * - Reporting of all tracked constellations are encouraged.
+     */
+    struct GnssData {
+        /* Number of GnssMeasurement elements. */
+        uint32_t measurementCount;
+
+        /* The array of measurements. */
+        GnssMeasurement[ConstS32:GNSS_MAX_MEASUREMENT] measurements;
+
+        /** The GNSS clock time reading. */
+        GnssClock clock;
+    };
+
+    /*
+     * Callback for the hal to pass a GnssData structure back to the client.
+     *
+     * @param data Contains a reading of GNSS measurements.
+     */
+    GnssMeasurementCb(GnssData data);
+};
diff --git a/gnss/1.0/IGnssNavigationMessage.hal b/gnss/1.0/IGnssNavigationMessage.hal
new file mode 100644 (file)
index 0000000..d59b538
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+import IGnssNavigationMessageCallback;
+
+/*
+ * Extended interface for GNSS navigation message reporting support.
+ */
+interface IGnssNavigationMessage {
+    enum GnssNavigationMessageStatus : int32_t {
+        SUCCESS = 0,
+        ERROR_ALREADY_INIT = -100,
+        ERROR_GENERIC = -101
+    };
+
+    /*
+     * Initializes the interface and registers the callback routines with the HAL.
+     * After a successful call to 'setCallback' the HAL must begin to provide updates as
+     * they become available.
+     * @param callback handle to IGnssNavigationMessageCallack interface.
+     *
+     * @return initRet Returns SUCCESS if the operation
+     * is successful.
+     * Returns ERROR_ALREADY_INIT if a callback has
+     * already been registered without a corresponding call to close().
+     * Returns ERROR_GENERIC if any other error occurred. It is
+     * expected that the HAL will not generate any updates upon returning
+     * this error code.
+     */
+     setCallback(IGnssNavigationMessageCallback callback) generates (int32_t initRet);
+
+    /*
+     * Stops updates from the HAL, and unregisters the callback routines.
+     * After a call to close(), the previously registered callbacks must be
+     * considered invalid by the HAL.
+     * If close() is invoked without a previous setCallback, this function must perform
+     * no work.
+     */
+    close();
+};
diff --git a/gnss/1.0/IGnssNavigationMessageCallback.hal b/gnss/1.0/IGnssNavigationMessageCallback.hal
new file mode 100644 (file)
index 0000000..a714fd7
--- /dev/null
@@ -0,0 +1,166 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+/** Represents a GNSS navigation message (or a fragment of it). */
+interface IGnssNavigationMessageCallback {
+    /*
+     * Enumeration of available values to indicate the GNSS Navigation message
+     * types.
+     *
+     * For convenience, first byte is the GnssConstellationType on which that signal
+     * is typically transmitted.
+     */
+    enum GnssNavigationMessageType : int16_t {
+        TYPE_UNKNOWN    = 0,
+        /** GNSS L1 C/A message contained in the structure.  */
+        GNSS_L1CA       = 0x0101,
+        /** GNSS L2-CNAV message contained in the structure. */
+        GNSS_L2CNAV     = 0x0102,
+        /** GNSS L5-CNAV message contained in the structure. */
+        GNSS_L5CNAV     = 0x0103,
+        /** GNSS CNAV-2 message contained in the structure. */
+        GNSS_CNAV2      = 0x0104,
+        /** Glonass L1 CA message contained in the structure. */
+        GLO_L1CA        = 0x0301,
+        /** Beidou D1 message contained in the structure. */
+        BDS_D1          = 0x0501,
+        /** Beidou D2 message contained in the structure. */
+        BDS_D2          = 0x0502,
+        /** Galileo I/NAV message contained in the structure. */
+        GAL_I           = 0x0601,
+        /** Galileo F/NAV message contained in the structure. */
+        GAL_F           = 0x0602
+    };
+
+    /*
+     * Status of Navigation Message
+     * When a message is received properly without any parity error in its
+     * navigation words, the status must be set to PARITY_PASSED. But if a message is
+     * received with words that failed parity check, but GNSS is able to correct
+     * those words, the status must be set to PARITY_REBUILT.
+     * No need to send any navigation message that contains words with parity error
+     * and cannot be corrected.
+     */
+    enum NavigationMessageStatus : uint16_t {
+        PARITY_PASSED  = (1 << 0),
+        PARITY_REBUILT = (1 << 1),
+        STATUS_UNKOWN  = 0
+    };
+
+    struct GnssNavigationMessage {
+        /*
+         * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+         * This is a mandatory value.
+         */
+        int16_t svid;
+
+        /*
+         * The type of message contained in the structure.
+         * This is a mandatory value.
+         */
+        GnssNavigationMessageType type;
+
+        /*
+         * The status of the received navigation message.
+         * No need to send any navigation message that contains words with parity
+         * error and cannot be corrected.
+         */
+        NavigationMessageStatus status;
+
+        /*
+         * Message identifier. It provides an index so the complete Navigation
+         * Message can be assembled.
+         *
+         * - For GNSS L1 C/A subframe 4 and 5, this value corresponds to the 'frame
+         *   id' of the navigation message, in the range of 1-25 (Subframe 1, 2, 3
+         *   does not contain a 'frame id' and this value can be set to -1.)
+         *
+         * - For Glonass L1 C/A, this refers to the frame ID, in the range of 1-5.
+         *
+         * - For BeiDou D1, this refers to the frame number in the range of 1-24
+         *
+         * - For Beidou D2, this refers to the frame number, in the range of 1-120
+         *
+         * - For Galileo F/NAV nominal frame structure, this refers to the subframe
+         *   number, in the range of 1-12
+         *
+         * - For Galileo I/NAV nominal frame structure, this refers to the subframe
+         *   number in the range of 1-24
+         */
+        int16_t messageId;
+
+        /*
+         * Sub-message identifier. If required by the message 'type', this value
+         * contains a sub-index within the current message (or frame) that is being
+         * transmitted.
+         *
+         * - For GNSS L1 C/A, BeiDou D1 & BeiDou D2, the submessage id corresponds to
+         *   the subframe number of the navigation message, in the range of 1-5.
+         *
+         * - For Glonass L1 C/A, this refers to the String number, in the range from
+         *   1-15
+         *
+         * - For Galileo F/NAV, this refers to the page type in the range 1-6
+         *
+         * - For Galileo I/NAV, this refers to the word type in the range 1-10+
+         */
+        int16_t submessageId;
+
+        /*
+         * The data of the reported GNSS message. The bytes (or words) are specified
+         * using big endian format (MSB first). The data is stored and decoded
+         * in a server for research purposes.
+         *
+         * - For GNSS L1 C/A, Beidou D1 & Beidou D2, each subframe contains 10 30-bit
+         *   words. Each word (30 bits) must fit into the last 30 bits in a
+         *   4-byte word (skip B31 and B32), with MSB first, for a total of 40
+         *   bytes, covering a time period of 6, 6, and 0.6 seconds, respectively.
+         *   The standard followed is 1995 SPS Signal specification.
+         *
+         * - For Glonass L1 C/A, each string contains 85 data bits, including the
+         *   checksum.  These bits must fit into 11 bytes, with MSB first (skip
+         *   B86-B88), covering a time period of 2 seconds.
+         *   The standard followed is Glonass Interface Control Document Edition 5.1.
+         *
+         * - For Galileo F/NAV, each word consists of 238-bit (sync & tail symbols
+         *   excluded). Each word must fit into 30-bytes, with MSB first (skip
+         *   B239, B240), covering a time period of 10 seconds. The standard
+         *   followed is European GNSS(Galileo) Signal in Space Interface
+         *   Control Document Issue 1.2.
+         *
+         * - For Galileo I/NAV, each page contains 2 page parts, even and odd, with
+         *   a total of 2x114 = 228 bits, (sync & tail excluded) that must fit
+         *   into 29 bytes, with MSB first (skip B229-B232). The standard followed
+         *   is same as above.
+         *
+         * TODO(b/32022567): Describe this relationship with data to the VTS
+         * via custom annotations and plug in a VTS test to verify that the data
+         * correctly follows the standard.
+         *
+         */
+        vec<uint8_t> data;
+    };
+
+    /*
+     * The callback to report an available fragment of a GNSS navigation messages
+     * from the HAL.
+     *
+     * @param message - The GNSS navigation submessage/subframe representation.
+     */
+     gnssNavigationMessageCb(GnssNavigationMessage message);
+};
diff --git a/gnss/1.0/IGnssNi.hal b/gnss/1.0/IGnssNi.hal
new file mode 100644 (file)
index 0000000..c823bf0
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+import IGnssNiCallback;
+
+/*
+ * Extended interface for Network-initiated (NI) support. This interface is used
+ * to respond to NI notifications originating from the HAL.
+ */
+interface IGnssNi {
+    /*
+     * Registers the callbacks for HAL to use.
+     *
+     * @param callback handle to IGnssNiCallback interface.
+     */
+    setCallback(IGnssNiCallback callback);
+
+    /*
+     * Sends a response to HAL.
+     *
+     * @param notifId An ID generated by HAL to associate NI notifications and
+     * framework responses.
+     * @param userResponse A GNSS Ni response indicating if the notification was
+     * accepted, denied or not responded to.
+     */
+    respond(int32_t notifId, GnssUserResponseType userResponse);
+};
diff --git a/gnss/1.0/IGnssNiCallback.hal b/gnss/1.0/IGnssNiCallback.hal
new file mode 100644 (file)
index 0000000..c696a92
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+/* GNSS Network Initiated callback interface. */
+interface IGnssNiCallback {
+    /*
+     * GnssNiType constants
+     */
+    enum GnssNiType : uint32_t {
+        VOICE           = 1,
+        UMTS_SUPL       = 2,
+        UMTS_CTRL_PLANE = 3
+    };
+
+    /*
+     * GnssNiNotifyFlags constants
+     */
+    enum GnssNiNotifyFlags : uint32_t {
+        /** NI requires notification */
+        NEED_NOTIFY      = 0x0001,
+        /** NI requires verification */
+        NEED_VERIFY      = 0x0002,
+        /** NI requires privacy override, no notification/minimal trace */
+        PRIVACY_OVERRIDE = 0x0004,
+    };
+
+    /*
+     * GNSS NI responses, used to define the response in
+     * NI structures
+     */
+    enum GnssUserResponseType : int32_t {
+        RESPONSE_ACCEPT  = 1,
+        RESPONSE_DENY    = 2,
+        RESPONSE_NORESP  = 3,
+    };
+
+    /*
+     * NI data encoding scheme
+     */
+    enum GnssNiEncodingType : int32_t {
+        ENC_NONE              = 0,
+        ENC_SUPL_GSM_DEFAULT  = 1,
+        ENC_SUPL_UTF8         = 2,
+        ENC_SUPL_UCS2         = 3,
+        ENC_UNKNOWN           = -1,
+    };
+
+    /** Represents an NI request */
+    struct GnssNiNotification{
+        /*
+         * An ID generated by HAL to associate NI notifications and UI
+         * responses.
+         */
+        int32_t notificationId;
+
+        /*
+         * A type used to distinguish different categories of NI
+         * events, such as VOICE, UMTS_SUPL etc.
+         */
+        GnssNiType niType;
+
+        /*
+         * Notification/verification options, combinations of GnssNiNotifyFlags
+         * constants.
+         */
+        GnssNiNotifyFlags notifyFlags;
+
+        /*
+         * Timeout period to wait for user response.
+         * Set to 0 for no timeout limit. Specified in seconds.
+         */
+        uint32_t timeoutSec;
+
+        /*
+         * Default response when timeout.
+         */
+        GnssUserResponseType defaultResponse;
+
+        /*
+         * String representing the requester of the network inititated location
+         * request.
+         */
+        string requestorId;
+
+        /*
+         * Notification message. String representing the service(for eg. SUPL-service)
+         * who sent the network initiated location request.
+         */
+        string notificationMessage;
+
+        /*
+         * requestorId decoding scheme.
+         */
+        GnssNiEncodingType requestorIdEncoding;
+
+        /*
+         * notificationId decoding scheme
+         */
+        GnssNiEncodingType notificationIdEncoding;
+    };
+
+    /*
+     * Callback with a network initiated request.
+     *
+     * @param notification network initiated request.
+     */
+    niNotifyCb(GnssNiNotification notification);
+};
diff --git a/gnss/1.0/IGnssXtra.hal b/gnss/1.0/IGnssXtra.hal
new file mode 100644 (file)
index 0000000..5222fde
--- /dev/null
@@ -0,0 +1,27 @@
+package android.hardware.gnss@1.0;
+import IGnssXtraCallback;
+
+/*
+ * This interface is used by the GNSS HAL to request the framework
+ * to download XTRA data.
+ */
+interface IGnssXtra {
+    /*
+     * Opens the XTRA interface and provides the callback routines
+     * to the implementation of this interface.
+     *
+     * @param callback Handle to the IGnssXtraCallback interface.
+     *
+     * @return success True if the operation is successful.
+     */
+    setCallback(IGnssXtraCallback callback) generates (bool success);
+
+    /*
+     * Inject the downloaded XTRA data into the GNSS receiver.
+     *
+     * @param xtraData GNSS XTRA data.
+     *
+     * @return success True if the operation is successful.
+     */
+    injectXtraData(string xtraData) generates (bool success);
+};
diff --git a/gnss/1.0/IGnssXtraCallback.hal b/gnss/1.0/IGnssXtraCallback.hal
new file mode 100644 (file)
index 0000000..42df082
--- /dev/null
@@ -0,0 +1,12 @@
+package android.hardware.gnss@1.0;
+
+/*
+ * This interface is used by the GNSS HAL to request download of XTRA data.
+ */
+interface IGnssXtraCallback {
+   /*
+    * Callback to request the client to download XTRA data. The client should
+    * download XTRA data and inject it by calling injectXtraData().
+    */
+   downloadRequestCb();
+};
diff --git a/gnss/1.0/types.hal b/gnss/1.0/types.hal
new file mode 100644 (file)
index 0000000..3120648
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * 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 android.hardware.gnss@1.0;
+
+enum ConstS32 : int32_t {
+/** Maximum number of SVs for gnssSvStatusCb(). */
+    GNSS_MAX_SVS = 64,
+
+/* Maximum number of Measurements in gnssMeasurementCb(). */
+    GNSS_MAX_MEASUREMENT = 64,
+};
+
+/* Milliseconds since January 1, 1970 */
+typedef int64_t GnssUtcTime;
+
+/*
+ * Constellation type of GnssSvInfo
+ */
+enum GnssConstellationType : uint8_t {
+    UNKNOWN = 0,
+    GNSS     = 1,
+    SBAS    = 2,
+    GLONASS = 3,
+    QZSS    = 4,
+    BEIDOU  = 5,
+    GALILEO = 6,
+};
+
+/* Represents a location. */
+struct GnssLocation {
+    /* Contains GnssLocationFlags bits. */
+    uint16_t gnssLocationFlags;
+
+    /* Represents latitude in degrees. */
+    double latitude;
+
+    /* Represents longitude in degrees. */
+    double longitude;
+
+    /*
+     * Represents altitude in meters above the WGS 84 reference ellipsoid.
+     */
+    double altitude;
+
+    /* Represents speed in meters per second. */
+    float speedMetersperSec;
+
+    /* Represents heading in degrees. */
+    float bearingDegrees;
+
+    /* Represents expected accuracy in meters. */
+    float accuracyMeters;
+
+    /* Timestamp for the location fix. */
+    GnssUtcTime timestamp;
+
+};
diff --git a/gnss/Android.bp b/gnss/Android.bp
new file mode 100644 (file)
index 0000000..bbb3e4b
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+]
diff --git a/graphics/Android.bp b/graphics/Android.bp
new file mode 100644 (file)
index 0000000..4ac7766
--- /dev/null
@@ -0,0 +1,10 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "allocator/2.0",
+    "allocator/2.0/default",
+    "common/1.0",
+    "composer/2.1",
+    "composer/2.1/default",
+    "mapper/2.0",
+    "mapper/2.0/default",
+]
diff --git a/graphics/allocator/2.0/Android.bp b/graphics/allocator/2.0/Android.bp
new file mode 100644 (file)
index 0000000..004d7d2
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.graphics.allocator@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.graphics.allocator@2.0",
+    srcs: [
+        "types.hal",
+        "IAllocator.hal",
+    ],
+    out: [
+        "android/hardware/graphics/allocator/2.0/types.cpp",
+        "android/hardware/graphics/allocator/2.0/AllocatorAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.graphics.allocator@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.graphics.allocator@2.0",
+    srcs: [
+        "types.hal",
+        "IAllocator.hal",
+    ],
+    out: [
+        "android/hardware/graphics/allocator/2.0/types.h",
+        "android/hardware/graphics/allocator/2.0/IAllocator.h",
+        "android/hardware/graphics/allocator/2.0/IHwAllocator.h",
+        "android/hardware/graphics/allocator/2.0/BnAllocator.h",
+        "android/hardware/graphics/allocator/2.0/BpAllocator.h",
+        "android/hardware/graphics/allocator/2.0/BsAllocator.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.graphics.allocator@2.0",
+    generated_sources: ["android.hardware.graphics.allocator@2.0_genc++"],
+    generated_headers: ["android.hardware.graphics.allocator@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.graphics.allocator@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/graphics/allocator/2.0/Android.mk b/graphics/allocator/2.0/Android.mk
new file mode 100644 (file)
index 0000000..3165fed
--- /dev/null
@@ -0,0 +1,38 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.graphics.allocator@2.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/graphics/allocator/2.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/IAllocator.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.allocator@2.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/graphics/allocator/2.0/IAllocator.hal b/graphics/allocator/2.0/IAllocator.hal
new file mode 100644 (file)
index 0000000..ff08a7e
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * 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 android.hardware.graphics.allocator@2.0;
+
+interface IAllocator {
+    enum Capability : int32_t {
+        /* reserved */
+        INVALID = 0,
+
+        /*
+         * testAllocate will always return UNDEFINED unless this capability
+         * is supported.
+         */
+        TEST_ALLOCATE = 1,
+
+        /*
+         * layerCount must be 1 unless this capability is supported.
+         */
+        LAYERED_BUFFERS = 2,
+    };
+
+    struct BufferDescriptorInfo {
+        /*
+         * The width specifies how many columns of pixels must be in the
+         * allocated buffer, but does not necessarily represent the offset in
+         * columns between the same column in adjacent rows. The rows may be
+         * padded.
+         */
+        uint32_t width;
+
+       /*
+        * The height specifies how many rows of pixels must be in the
+        * allocated buffer.
+        */
+        uint32_t height;
+
+       /*
+        * The number of image layers that must be in the allocated buffer.
+        */
+        uint32_t layerCount;
+
+        /* Buffer pixel format. */
+        PixelFormat format;
+
+        /*
+         * Buffer producer usage mask; valid flags can be found in the
+         * definition of ProducerUsage.
+         */
+        uint64_t producerUsageMask;
+
+        /*
+         * Buffer consumer usage mask; valid flags can be found in the
+         * definition of ConsumerUsage.
+         */
+        uint64_t consumerUsageMask;
+    };
+
+    /*
+     * Provides a list of supported capabilities (as described in the
+     * definition of Capability above). This list must not change after
+     * initialization.
+     *
+     * @return capabilities is a list of supported capabilities.
+     */
+    getCapabilities() generates (vec<Capability> capabilities);
+
+    /*
+     * Retrieves implementation-defined debug information, which will be
+     * displayed during, for example, `dumpsys SurfaceFlinger`.
+     *
+     * @return debugInfo is a string of debug information.
+     */
+    dumpDebugInfo() generates (string debugInfo);
+
+    /*
+     * Creates a new, opaque buffer descriptor.
+     *
+     * @param descriptorInfo specifies the attributes of the buffer
+     *        descriptor.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_VALUE when any attribute in descriptorInfo is invalid.
+     *         NO_RESOURCES when no more descriptors can currently be created.
+     * @return descriptor is the newly created buffer descriptor.
+     */
+    createDescriptor(BufferDescriptorInfo descriptorInfo)
+          generates (Error error,
+                     BufferDescriptor descriptor);
+
+    /*
+     * Destroys an existing buffer descriptor.
+     *
+     * @param descriptor is the descriptor to destroy.
+     * @return error is either NONE or BAD_DESCRIPTOR.
+     */
+    destroyDescriptor(BufferDescriptor descriptor) generates (Error error);
+
+    /*
+     * Tests whether a buffer allocation can succeed, ignoring potential
+     * resource contention which might lead to a NO_RESOURCES error.
+     *
+     * @param descriptors is a list of buffer descriptors.
+     * @return error is NONE or NOT_SHARED upon success;
+     *         NONE when buffers can be created and share a backing store.
+     *         NOT_SHARED when buffers can be created but require more than a
+     *                    backing store.
+     *         Otherwise,
+     *         BAD_DESCRIPTOR when any of the descriptors is invalid.
+     *         UNSUPPORTED when any of the descriptors can never be satisfied.
+     *         UNDEFINED when TEST_ALLOCATE is not listed in getCapabilities.
+     */
+    testAllocate(vec<BufferDescriptor> descriptors) generates (Error error);
+
+    /*
+     * Attempts to allocate a list of buffers sharing a backing store.
+     *
+     * Each buffer will correspond to one of the descriptors passed into the
+     * function and will hold a reference to its backing store. If the device
+     * is unable to share the backing store between the buffers, it must
+     * attempt to allocate the buffers with different backing stores and
+     * return NOT_SHARED if it is successful.
+     *
+     * @param descriptors is the buffer descriptors to attempt to allocate.
+     * @return error is NONE or NOT_SHARED upon success;
+     *         NONE when buffers can be created and share a backing store.
+     *         NOT_SHARED when buffers can be created but require more than a
+     *                    backing store.
+     *         Otherwise,
+     *         BAD_DESCRIPTOR when any of the descriptors is invalid.
+     *         UNSUPPORTED when any of the descriptors can never be satisfied.
+     *         NO_RESOURCES when any of the buffers cannot be created at this
+     *                      time.
+     * @return buffers is the allocated buffers.
+     */
+    allocate(vec<BufferDescriptor> descriptors)
+        generates (Error error,
+                   vec<Buffer> buffers);
+
+    /*
+     * Frees a buffer.
+     *
+     * @param buffer is the buffer to be freed.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_BUFFER when the buffer is invalid.
+     */
+    free(Buffer buffer) generates (Error error);
+
+    /*
+     * Exports a buffer for use in other client libraries or for cross-process
+     * sharing.
+     *
+     * The exported handle is a handle to the backing store of the buffer, not
+     * to the buffer itself. It however may not hold any reference to the
+     * backing store and may be considered invalid by client libraries. To use
+     * it and, in most cases, to save it for later use, a client must make a
+     * clone of the handle and have the cloned handle hold a reference to the
+     * backing store. Such a cloned handle will stay valid even after the
+     * original buffer is freed. Refer to native_handle_clone and IMapper for
+     * how a handle is cloned and how a reference is added.
+     *
+     * @param descriptor is the descriptor used to allocate the buffer.
+     * @param buffer is the buffer to be exported.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DESCRIPTOR when the descriptor is invalid.
+     *         BAD_BUFFER when the buffer is invalid.
+     *         BAD_VALUE when descriptor and buffer do not match.
+     *         NO_RESOURCES when the buffer cannot be exported at this time.
+     * @return bufferHandle is the exported handle.
+     */
+    exportHandle(BufferDescriptor descriptor,
+                 Buffer buffer)
+      generates (Error error,
+                 handle bufferHandle);
+};
diff --git a/graphics/allocator/2.0/default/Android.bp b/graphics/allocator/2.0/default/Android.bp
new file mode 100644 (file)
index 0000000..8eac8f5
--- /dev/null
@@ -0,0 +1,39 @@
+cc_library_shared {
+    name: "android.hardware.graphics.allocator@2.0-impl",
+    relative_install_path: "hw",
+    srcs: ["Gralloc.cpp"],
+    cppflags: ["-Wall", "-Wextra"],
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "libbase",
+        "libcutils",
+        "libhardware",
+        "libhidl",
+        "libhwbinder",
+        "liblog",
+        "libutils",
+    ],
+}
+
+cc_binary {
+    name: "android.hardware.graphics.allocator@2.0-service",
+    relative_install_path: "hw",
+    srcs: ["service.cpp"],
+    init_rc: ["android.hardware.graphics.allocator@2.0-service.rc"],
+
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "libhidl",
+        "libhwbinder",
+        "liblog",
+        "libutils",
+    ],
+}
+
+cc_library_static {
+    name: "libgralloc1-adapter",
+    srcs: ["gralloc1-adapter.c"],
+    include_dirs: ["system/core/libsync/include"],
+    cflags: ["-Wall", "-Wextra", "-Wno-unused-parameter"],
+    export_include_dirs: ["."],
+}
diff --git a/graphics/allocator/2.0/default/Gralloc.cpp b/graphics/allocator/2.0/default/Gralloc.cpp
new file mode 100644 (file)
index 0000000..8a74661
--- /dev/null
@@ -0,0 +1,307 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "GrallocPassthrough"
+
+#include <type_traits>
+#include <unordered_set>
+#include <vector>
+
+#include <string.h>
+
+#include <hardware/gralloc1.h>
+#include <log/log.h>
+
+#include "Gralloc.h"
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace allocator {
+namespace V2_0 {
+namespace implementation {
+
+class GrallocHal : public IAllocator {
+public:
+    GrallocHal(const hw_module_t* module);
+    virtual ~GrallocHal();
+
+    // IAllocator interface
+    Return<void> getCapabilities(getCapabilities_cb hidl_cb) override;
+    Return<void> dumpDebugInfo(dumpDebugInfo_cb hidl_cb) override;
+    Return<void> createDescriptor(const BufferDescriptorInfo& descriptorInfo,
+            createDescriptor_cb hidl_cb) override;
+    Return<Error> destroyDescriptor(BufferDescriptor descriptor) override;
+
+    Return<Error> testAllocate(
+            const hidl_vec<BufferDescriptor>& descriptors) override;
+    Return<void> allocate(const hidl_vec<BufferDescriptor>& descriptors,
+            allocate_cb hidl_cb) override;
+    Return<Error> free(Buffer buffer) override;
+
+    Return<void> exportHandle(BufferDescriptor descriptor,
+            Buffer buffer, exportHandle_cb hidl_cb) override;
+
+private:
+    void initCapabilities();
+
+    template<typename T>
+    void initDispatch(T& func, gralloc1_function_descriptor_t desc);
+    void initDispatch();
+
+    bool hasCapability(Capability capability) const;
+
+    gralloc1_device_t* mDevice;
+
+    std::unordered_set<Capability> mCapabilities;
+
+    struct {
+        GRALLOC1_PFN_DUMP dump;
+        GRALLOC1_PFN_CREATE_DESCRIPTOR createDescriptor;
+        GRALLOC1_PFN_DESTROY_DESCRIPTOR destroyDescriptor;
+        GRALLOC1_PFN_SET_DIMENSIONS setDimensions;
+        GRALLOC1_PFN_SET_FORMAT setFormat;
+        GRALLOC1_PFN_SET_LAYER_COUNT setLayerCount;
+        GRALLOC1_PFN_SET_CONSUMER_USAGE setConsumerUsage;
+        GRALLOC1_PFN_SET_PRODUCER_USAGE setProducerUsage;
+        GRALLOC1_PFN_ALLOCATE allocate;
+        GRALLOC1_PFN_RELEASE release;
+        GRALLOC1_PFN_GET_BACKING_STORE getBackingStore;
+        GRALLOC1_PFN_GET_STRIDE getStride;
+        GRALLOC1_PFN_GET_NUM_FLEX_PLANES getNumFlexPlanes;
+    } mDispatch;
+};
+
+GrallocHal::GrallocHal(const hw_module_t* module)
+    : mDevice(nullptr), mDispatch()
+{
+    int status = gralloc1_open(module, &mDevice);
+    if (status) {
+        LOG_ALWAYS_FATAL("failed to open gralloc1 device: %s",
+                strerror(-status));
+    }
+
+    initCapabilities();
+    initDispatch();
+}
+
+GrallocHal::~GrallocHal()
+{
+    gralloc1_close(mDevice);
+}
+
+void GrallocHal::initCapabilities()
+{
+    uint32_t count;
+    mDevice->getCapabilities(mDevice, &count, nullptr);
+
+    std::vector<Capability> caps(count);
+    mDevice->getCapabilities(mDevice, &count, reinterpret_cast<
+              std::underlying_type<Capability>::type*>(caps.data()));
+    caps.resize(count);
+
+    mCapabilities.insert(caps.cbegin(), caps.cend());
+}
+
+template<typename T>
+void GrallocHal::initDispatch(T& func, gralloc1_function_descriptor_t desc)
+{
+    auto pfn = mDevice->getFunction(mDevice, desc);
+    if (!pfn) {
+        LOG_ALWAYS_FATAL("failed to get gralloc1 function %d", desc);
+    }
+
+    func = reinterpret_cast<T>(pfn);
+}
+
+void GrallocHal::initDispatch()
+{
+    initDispatch(mDispatch.dump, GRALLOC1_FUNCTION_DUMP);
+    initDispatch(mDispatch.createDescriptor,
+            GRALLOC1_FUNCTION_CREATE_DESCRIPTOR);
+    initDispatch(mDispatch.destroyDescriptor,
+            GRALLOC1_FUNCTION_DESTROY_DESCRIPTOR);
+    initDispatch(mDispatch.setDimensions, GRALLOC1_FUNCTION_SET_DIMENSIONS);
+    initDispatch(mDispatch.setFormat, GRALLOC1_FUNCTION_SET_FORMAT);
+    if (hasCapability(Capability::LAYERED_BUFFERS)) {
+        initDispatch(
+                mDispatch.setLayerCount, GRALLOC1_FUNCTION_SET_LAYER_COUNT);
+    }
+    initDispatch(mDispatch.setConsumerUsage,
+            GRALLOC1_FUNCTION_SET_CONSUMER_USAGE);
+    initDispatch(mDispatch.setProducerUsage,
+            GRALLOC1_FUNCTION_SET_PRODUCER_USAGE);
+    initDispatch(mDispatch.allocate, GRALLOC1_FUNCTION_ALLOCATE);
+    initDispatch(mDispatch.release, GRALLOC1_FUNCTION_RELEASE);
+}
+
+bool GrallocHal::hasCapability(Capability capability) const
+{
+    return (mCapabilities.count(capability) > 0);
+}
+
+Return<void> GrallocHal::getCapabilities(getCapabilities_cb hidl_cb)
+{
+    std::vector<Capability> caps(
+            mCapabilities.cbegin(), mCapabilities.cend());
+
+    hidl_vec<Capability> reply;
+    reply.setToExternal(caps.data(), caps.size());
+    hidl_cb(reply);
+
+    return Void();
+}
+
+Return<void> GrallocHal::dumpDebugInfo(dumpDebugInfo_cb hidl_cb)
+{
+    uint32_t len = 0;
+    mDispatch.dump(mDevice, &len, nullptr);
+
+    std::vector<char> buf(len + 1);
+    mDispatch.dump(mDevice, &len, buf.data());
+    buf.resize(len + 1);
+    buf[len] = '\0';
+
+    hidl_string reply;
+    reply.setToExternal(buf.data(), len);
+    hidl_cb(reply);
+
+    return Void();
+}
+
+Return<void> GrallocHal::createDescriptor(
+        const BufferDescriptorInfo& descriptorInfo,
+        createDescriptor_cb hidl_cb)
+{
+    BufferDescriptor descriptor;
+    int32_t err = mDispatch.createDescriptor(mDevice, &descriptor);
+    if (err == GRALLOC1_ERROR_NONE) {
+        err = mDispatch.setDimensions(mDevice, descriptor,
+                descriptorInfo.width, descriptorInfo.height);
+    }
+    if (err == GRALLOC1_ERROR_NONE) {
+        err = mDispatch.setFormat(mDevice, descriptor,
+                static_cast<int32_t>(descriptorInfo.format));
+    }
+    if (err == GRALLOC1_ERROR_NONE &&
+            hasCapability(Capability::LAYERED_BUFFERS)) {
+        err = mDispatch.setLayerCount(mDevice, descriptor,
+                descriptorInfo.layerCount);
+    }
+    if (err == GRALLOC1_ERROR_NONE) {
+        uint64_t producerUsageMask = descriptorInfo.producerUsageMask;
+        if (producerUsageMask & GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN) {
+            producerUsageMask |= GRALLOC1_PRODUCER_USAGE_CPU_READ;
+        }
+        if (producerUsageMask & GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
+            producerUsageMask |= GRALLOC1_PRODUCER_USAGE_CPU_WRITE;
+        }
+        err = mDispatch.setProducerUsage(mDevice, descriptor,
+                descriptorInfo.producerUsageMask);
+    }
+    if (err == GRALLOC1_ERROR_NONE) {
+        uint64_t consumerUsageMask = descriptorInfo.consumerUsageMask;
+        if (consumerUsageMask & GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
+            consumerUsageMask |= GRALLOC1_CONSUMER_USAGE_CPU_READ;
+        }
+        err = mDispatch.setConsumerUsage(mDevice, descriptor,
+                consumerUsageMask);
+    }
+
+    hidl_cb(static_cast<Error>(err), descriptor);
+
+    return Void();
+}
+
+Return<Error> GrallocHal::destroyDescriptor(
+        BufferDescriptor descriptor)
+{
+    int32_t err = mDispatch.destroyDescriptor(mDevice, descriptor);
+    return static_cast<Error>(err);
+}
+
+Return<Error> GrallocHal::testAllocate(
+        const hidl_vec<BufferDescriptor>& descriptors)
+{
+    if (!hasCapability(Capability::TEST_ALLOCATE)) {
+        return Error::UNDEFINED;
+    }
+
+    int32_t err = mDispatch.allocate(mDevice, descriptors.size(),
+            &descriptors[0], nullptr);
+    return static_cast<Error>(err);
+}
+
+Return<void> GrallocHal::allocate(
+        const hidl_vec<BufferDescriptor>& descriptors,
+        allocate_cb hidl_cb) {
+    std::vector<buffer_handle_t> buffers(descriptors.size());
+    int32_t err = mDispatch.allocate(mDevice, descriptors.size(),
+            &descriptors[0], buffers.data());
+    if (err != GRALLOC1_ERROR_NONE && err != GRALLOC1_ERROR_NOT_SHARED) {
+        buffers.clear();
+    }
+
+    hidl_vec<Buffer> reply;
+    reply.setToExternal(
+            reinterpret_cast<Buffer*>(buffers.data()),
+            buffers.size());
+    hidl_cb(static_cast<Error>(err), reply);
+
+    return Void();
+}
+
+Return<Error> GrallocHal::free(Buffer buffer)
+{
+    buffer_handle_t handle = reinterpret_cast<buffer_handle_t>(buffer);
+    int32_t err = mDispatch.release(mDevice, handle);
+    return static_cast<Error>(err);
+}
+
+Return<void> GrallocHal::exportHandle(BufferDescriptor /*descriptor*/,
+        Buffer buffer, exportHandle_cb hidl_cb)
+{
+    // do we want to validate?
+    buffer_handle_t handle = reinterpret_cast<buffer_handle_t>(buffer);
+
+    hidl_cb(Error::NONE, handle);
+
+    return Void();
+}
+
+IAllocator* HIDL_FETCH_IAllocator(const char* /* name */) {
+    const hw_module_t* module;
+    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+    if (err) {
+        ALOGE("failed to get gralloc module");
+        return nullptr;
+    }
+
+    uint8_t major = (module->module_api_version >> 8) & 0xff;
+    if (major != 1) {
+        ALOGE("unknown gralloc module major version %d", major);
+        return nullptr;
+    }
+
+    return new GrallocHal(module);
+}
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace allocator
+} // namespace graphics
+} // namespace hardware
+} // namespace android
diff --git a/graphics/allocator/2.0/default/Gralloc.h b/graphics/allocator/2.0/default/Gralloc.h
new file mode 100644 (file)
index 0000000..c79eeaa
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 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.
+ */
+
+#ifndef ANDROID_HARDWARE_GRAPHICS_ALLOCATOR_V2_0_GRALLOC_H
+#define ANDROID_HARDWARE_GRAPHICS_ALLOCATOR_V2_0_GRALLOC_H
+
+#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace allocator {
+namespace V2_0 {
+namespace implementation {
+
+extern "C" IAllocator* HIDL_FETCH_IAllocator(const char* name);
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace allocator
+} // namespace graphics
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_GRAPHICS_ALLOCATOR_V2_0_GRALLOC_H
diff --git a/graphics/allocator/2.0/default/android.hardware.graphics.allocator@2.0-service.rc b/graphics/allocator/2.0/default/android.hardware.graphics.allocator@2.0-service.rc
new file mode 100644 (file)
index 0000000..8bb0d85
--- /dev/null
@@ -0,0 +1,5 @@
+service gralloc-2-0 /system/bin/hw/android.hardware.graphics.allocator@2.0-service
+    class hal
+    user system
+    group graphics drmrpc readproc
+    onrestart restart surfaceflinger
diff --git a/graphics/allocator/2.0/default/gralloc1-adapter.c b/graphics/allocator/2.0/default/gralloc1-adapter.c
new file mode 100644 (file)
index 0000000..724cd47
--- /dev/null
@@ -0,0 +1,660 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "Gralloc1Adapter"
+
+#include <stdatomic.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <pthread.h>
+
+#include <cutils/native_handle.h>
+#include <hardware/gralloc1.h>
+#include <sync/sync.h>
+#include <log/log.h>
+
+#include "gralloc1-adapter.h"
+
+struct gralloc1_adapter_module {
+    struct gralloc_module_t base;
+    struct gralloc1_adapter adapter;
+};
+
+struct gralloc1_adapter_device {
+    struct gralloc1_device base;
+
+    struct alloc_device_t* alloc_dev;
+
+    /* fixed size for thread safety */
+    char saved_dump[4096];
+    size_t saved_dump_size;
+};
+
+/* additional data associated with registered buffer_handle_t */
+struct gralloc1_adapter_buffer_data {
+    struct gralloc1_adapter_buffer_info info;
+
+    atomic_int refcount;
+    bool owned;
+};
+
+struct gralloc1_adapter_buffer_descriptor {
+    int width;
+    int height;
+    int format;
+    int producer_usage;
+    int consumer_usage;
+};
+
+static const struct gralloc1_adapter_module* gralloc1_adapter_module(
+        struct gralloc1_device* dev)
+{
+    return (const struct gralloc1_adapter_module*) dev->common.module;
+}
+
+static struct gralloc1_adapter_device* gralloc1_adapter_device(
+        struct gralloc1_device* dev)
+{
+    return (struct gralloc1_adapter_device*) dev;
+}
+
+static struct gralloc1_adapter_buffer_data* lookup_buffer_data(
+        struct gralloc1_device* dev, buffer_handle_t buffer)
+{
+    const struct gralloc1_adapter_module* mod = gralloc1_adapter_module(dev);
+    if (!mod->adapter.is_registered(&mod->base, buffer))
+        return NULL;
+
+    return mod->adapter.get_data(&mod->base, buffer);
+}
+
+static struct gralloc1_adapter_buffer_descriptor* lookup_buffer_descriptor(
+        struct gralloc1_device* dev, gralloc1_buffer_descriptor_t id)
+{
+    /* do we want to validate? */
+    return (struct gralloc1_adapter_buffer_descriptor*) ((uintptr_t) id);
+}
+
+static void device_dump(struct gralloc1_device* device,
+        uint32_t* outSize, char* outBuffer)
+{
+    struct gralloc1_adapter_device* dev = gralloc1_adapter_device(device);
+
+    if (outBuffer) {
+        uint32_t copy = (uint32_t) dev->saved_dump_size;
+        if (*outSize < copy) {
+            copy = *outSize;
+        } else {
+            *outSize = copy;
+        }
+
+        memcpy(outBuffer, dev->saved_dump, copy);
+    } else {
+        /* dump is optional and may not null-terminate */
+        if (dev->alloc_dev->dump) {
+            dev->alloc_dev->dump(dev->alloc_dev, dev->saved_dump,
+                    sizeof(dev->saved_dump) - 1);
+            dev->saved_dump_size = strlen(dev->saved_dump);
+        }
+
+        *outSize = (uint32_t) dev->saved_dump_size;
+    }
+}
+
+static int32_t device_create_descriptor(struct gralloc1_device* device,
+        gralloc1_buffer_descriptor_t* outDescriptor)
+{
+    struct gralloc1_adapter_buffer_descriptor* desc;
+
+    desc = calloc(1, sizeof(*desc));
+    if (!desc) {
+        return GRALLOC1_ERROR_NO_RESOURCES;
+    }
+
+    *outDescriptor = (gralloc1_buffer_descriptor_t) (uintptr_t) desc;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_destroy_descriptor(struct gralloc1_device* device,
+        gralloc1_buffer_descriptor_t descriptor)
+{
+    struct gralloc1_adapter_buffer_descriptor* desc =
+        lookup_buffer_descriptor(device, descriptor);
+    if (!desc) {
+        return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    }
+
+    free(desc);
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_set_consumer_usage(struct gralloc1_device* device,
+        gralloc1_buffer_descriptor_t descriptor, uint64_t usage)
+{
+    struct gralloc1_adapter_buffer_descriptor* desc =
+        lookup_buffer_descriptor(device, descriptor);
+    if (!desc) {
+        return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    }
+
+    desc->consumer_usage = (int) usage;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_set_dimensions(struct gralloc1_device* device,
+        gralloc1_buffer_descriptor_t descriptor,
+        uint32_t width, uint32_t height)
+{
+    struct gralloc1_adapter_buffer_descriptor* desc =
+        lookup_buffer_descriptor(device, descriptor);
+    if (!desc) {
+        return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    }
+
+    desc->width = (int) width;
+    desc->height = (int) height;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_set_format(struct gralloc1_device* device,
+        gralloc1_buffer_descriptor_t descriptor, int32_t format)
+{
+    struct gralloc1_adapter_buffer_descriptor* desc =
+        lookup_buffer_descriptor(device, descriptor);
+    if (!desc) {
+        return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    }
+
+    desc->format = format;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_set_producer_usage(struct gralloc1_device* device,
+        gralloc1_buffer_descriptor_t descriptor, uint64_t usage)
+{
+    struct gralloc1_adapter_buffer_descriptor* desc =
+        lookup_buffer_descriptor(device, descriptor);
+    if (!desc) {
+        return GRALLOC1_ERROR_BAD_DESCRIPTOR;
+    }
+
+    desc->producer_usage = (int) usage;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_get_backing_store(struct gralloc1_device* device,
+        buffer_handle_t buffer, gralloc1_backing_store_t* outStore)
+{
+    /* we never share backing store */
+    *outStore = (gralloc1_backing_store_t) (uintptr_t) buffer;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_get_consumer_usage(struct gralloc1_device* device,
+        buffer_handle_t buffer, uint64_t* outUsage)
+{
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    if (!data) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    *outUsage = data->info.usage;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_get_dimensions(struct gralloc1_device* device,
+        buffer_handle_t buffer, uint32_t* outWidth, uint32_t* outHeight)
+{
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    if (!data) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    *outWidth = data->info.width;
+    *outHeight = data->info.height;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_get_format(struct gralloc1_device* device,
+        buffer_handle_t buffer, int32_t* outFormat)
+{
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    if (!data) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    *outFormat = data->info.format;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_get_producer_usage(struct gralloc1_device* device,
+        buffer_handle_t buffer, uint64_t* outUsage)
+{
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    if (!data) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    *outUsage = data->info.usage;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_get_stride(struct gralloc1_device* device,
+        buffer_handle_t buffer, uint32_t* outStride)
+{
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    if (!data) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    *outStride = data->info.stride;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_allocate(struct gralloc1_device* device,
+        uint32_t numDescriptors,
+        const gralloc1_buffer_descriptor_t* descriptors,
+        buffer_handle_t* outBuffers)
+{
+    const struct gralloc1_adapter_module* mod =
+        gralloc1_adapter_module(device);
+    struct gralloc1_adapter_device* dev = gralloc1_adapter_device(device);
+    gralloc1_error_t err = GRALLOC1_ERROR_NONE;
+    uint32_t i;
+
+    for (i = 0; i < numDescriptors; i++) {
+        const struct gralloc1_adapter_buffer_descriptor* desc =
+            lookup_buffer_descriptor(device, descriptors[i]);
+        struct gralloc1_adapter_buffer_data* data;
+        buffer_handle_t buffer;
+        int dummy_stride;
+        int ret;
+
+        if (!desc) {
+            err = GRALLOC1_ERROR_BAD_DESCRIPTOR;
+            break;
+        }
+
+        data = calloc(1, sizeof(*data));
+        if (!data) {
+            err = GRALLOC1_ERROR_NO_RESOURCES;
+            break;
+        }
+
+        ret = dev->alloc_dev->alloc(dev->alloc_dev, desc->width, desc->height,
+                desc->format, desc->producer_usage | desc->consumer_usage,
+                &buffer, &dummy_stride);
+        if (ret) {
+            free(data);
+            err = GRALLOC1_ERROR_NO_RESOURCES;
+            break;
+        }
+
+        mod->adapter.get_info(&mod->base, buffer, &data->info);
+        data->refcount = 1;
+        data->owned = true;
+
+        mod->adapter.set_data(&mod->base, buffer, data);
+
+        outBuffers[i] = buffer;
+    }
+
+    if (err != GRALLOC1_ERROR_NONE) {
+        uint32_t j;
+        for (j = 0; j < i; j++) {
+            free(mod->adapter.get_data(&mod->base, outBuffers[i]));
+            dev->alloc_dev->free(dev->alloc_dev, outBuffers[i]);
+        }
+
+        return err;
+    }
+
+    return (numDescriptors > 1) ?
+        GRALLOC1_ERROR_NOT_SHARED : GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_retain(struct gralloc1_device* device,
+        buffer_handle_t buffer)
+{
+    static pthread_mutex_t register_mutex = PTHREAD_MUTEX_INITIALIZER;
+    const struct gralloc1_adapter_module* mod =
+        gralloc1_adapter_module(device);
+    struct gralloc1_adapter_buffer_data* data;
+
+    pthread_mutex_lock(&register_mutex);
+
+    if (mod->adapter.is_registered(&mod->base, buffer)) {
+        data = mod->adapter.get_data(&mod->base, buffer);
+        data->refcount++;
+    } else {
+        int ret;
+
+        data = calloc(1, sizeof(*data));
+        if (!data) {
+            pthread_mutex_unlock(&register_mutex);
+            return GRALLOC1_ERROR_NO_RESOURCES;
+        }
+
+        ret = mod->base.registerBuffer(&mod->base, buffer);
+        if (ret) {
+            pthread_mutex_unlock(&register_mutex);
+            free(data);
+
+            return GRALLOC1_ERROR_NO_RESOURCES;
+        }
+
+        mod->adapter.get_info(&mod->base, buffer, &data->info);
+        data->refcount = 1;
+        data->owned = false;
+
+        mod->adapter.set_data(&mod->base, buffer, data);
+    }
+
+    pthread_mutex_unlock(&register_mutex);
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_release(struct gralloc1_device* device,
+        buffer_handle_t buffer)
+{
+    struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    if (!data) {
+        ALOGE("unable to release unregistered buffer %p", buffer);
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    data->refcount--;
+    if (!data->refcount) {
+        if (data->owned) {
+            struct gralloc1_adapter_device* dev =
+                gralloc1_adapter_device(device);
+            dev->alloc_dev->free(dev->alloc_dev, buffer);
+        } else {
+            const struct gralloc1_adapter_module* mod =
+                gralloc1_adapter_module(device);
+            mod->base.unregisterBuffer(&mod->base, buffer);
+
+            native_handle_close(buffer);
+            native_handle_delete((native_handle_t*) buffer);
+        }
+
+        free(data);
+    }
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_get_num_flex_planes(struct gralloc1_device* device,
+        buffer_handle_t buffer, uint32_t* outNumPlanes)
+{
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    if (!data) {
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    *outNumPlanes = data->info.num_flex_planes;
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_lock(struct gralloc1_device* device,
+        buffer_handle_t buffer,
+        uint64_t producerUsage, uint64_t consumerUsage,
+        const gralloc1_rect_t* accessRegion, void** outData,
+        int32_t acquireFence)
+{
+    const struct gralloc1_adapter_module* mod =
+        gralloc1_adapter_module(device);
+    const int usage = (int) (producerUsage | consumerUsage);
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    int ret;
+
+    if (!data) {
+        ALOGE("unable to lock unregistered buffer %p", buffer);
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    if (mod->adapter.real_module_api_version >=
+            GRALLOC_MODULE_API_VERSION_0_3) {
+        ret = mod->base.lockAsync(&mod->base,
+                buffer, usage,
+                accessRegion->left,
+                accessRegion->top,
+                accessRegion->width,
+                accessRegion->height,
+                outData, acquireFence);
+    } else {
+        if (acquireFence >= 0) {
+            sync_wait(acquireFence, -1);
+        }
+
+        ret = mod->base.lock(&mod->base,
+                buffer, usage,
+                accessRegion->left,
+                accessRegion->top,
+                accessRegion->width,
+                accessRegion->height,
+                outData);
+
+        if (acquireFence >= 0 && !ret) {
+            close(acquireFence);
+        }
+    }
+
+    return (ret) ? GRALLOC1_ERROR_NO_RESOURCES : GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_lock_flex(struct gralloc1_device* device,
+        buffer_handle_t buffer,
+        uint64_t producerUsage, uint64_t consumerUsage,
+        const gralloc1_rect_t* accessRegion,
+        struct android_flex_layout* outFlexLayout,
+        int32_t acquireFence)
+{
+    const struct gralloc1_adapter_module* mod =
+        gralloc1_adapter_module(device);
+    const int usage = (int) (producerUsage | consumerUsage);
+    const struct gralloc1_adapter_buffer_data* data =
+        lookup_buffer_data(device, buffer);
+    struct android_ycbcr ycbcr;
+    int ret;
+
+    if (!data) {
+        ALOGE("unable to lockFlex unregistered buffer %p", buffer);
+        return GRALLOC1_ERROR_BAD_HANDLE;
+    }
+
+    if (outFlexLayout->num_planes < data->info.num_flex_planes) {
+        return GRALLOC1_ERROR_BAD_VALUE;
+    }
+
+    if (mod->adapter.real_module_api_version >=
+            GRALLOC_MODULE_API_VERSION_0_3 && mod->base.lockAsync_ycbcr) {
+        ret = mod->base.lockAsync_ycbcr(&mod->base,
+                buffer, usage,
+                accessRegion->left,
+                accessRegion->top,
+                accessRegion->width,
+                accessRegion->height,
+                &ycbcr, acquireFence);
+    } else if (mod->base.lock_ycbcr) {
+        if (acquireFence >= 0) {
+            sync_wait(acquireFence, -1);
+        }
+
+        ret = mod->base.lock_ycbcr(&mod->base,
+                buffer, usage,
+                accessRegion->left,
+                accessRegion->top,
+                accessRegion->width,
+                accessRegion->height,
+                &ycbcr);
+
+        if (acquireFence >= 0 && !ret) {
+            close(acquireFence);
+        }
+    } else {
+        return GRALLOC1_ERROR_UNSUPPORTED;
+    }
+
+    if (ret) {
+        return GRALLOC1_ERROR_NO_RESOURCES;
+    }
+
+    mod->adapter.get_flexible_layout(&mod->base, buffer,
+            &ycbcr, outFlexLayout);
+
+    return GRALLOC1_ERROR_NONE;
+}
+
+static int32_t device_unlock(struct gralloc1_device* device,
+        buffer_handle_t buffer, int32_t* outReleaseFence)
+{
+    const struct gralloc1_adapter_module* mod =
+        gralloc1_adapter_module(device);
+    int ret;
+
+    if (mod->adapter.real_module_api_version >=
+            GRALLOC_MODULE_API_VERSION_0_3) {
+        ret = mod->base.unlockAsync(&mod->base, buffer, outReleaseFence);
+    } else {
+        ret = mod->base.unlock(&mod->base, buffer);
+        if (!ret) {
+            *outReleaseFence = -1;
+        }
+    }
+
+    return (ret) ? GRALLOC1_ERROR_BAD_HANDLE : GRALLOC1_ERROR_NONE;
+}
+
+static gralloc1_function_pointer_t device_get_function(
+        struct gralloc1_device* device, int32_t descriptor)
+{
+    switch ((gralloc1_function_descriptor_t) descriptor) {
+#define CASE(id, ptr)              \
+    case GRALLOC1_FUNCTION_ ## id: \
+        return (gralloc1_function_pointer_t) device_ ## ptr
+    CASE(DUMP, dump);
+    CASE(CREATE_DESCRIPTOR, create_descriptor);
+    CASE(DESTROY_DESCRIPTOR, destroy_descriptor);
+    CASE(SET_CONSUMER_USAGE, set_consumer_usage);
+    CASE(SET_DIMENSIONS, set_dimensions);
+    CASE(SET_FORMAT, set_format);
+    CASE(SET_PRODUCER_USAGE, set_producer_usage);
+    CASE(GET_BACKING_STORE, get_backing_store);
+    CASE(GET_CONSUMER_USAGE, get_consumer_usage);
+    CASE(GET_DIMENSIONS, get_dimensions);
+    CASE(GET_FORMAT, get_format);
+    CASE(GET_PRODUCER_USAGE, get_producer_usage);
+    CASE(GET_STRIDE, get_stride);
+    CASE(ALLOCATE, allocate);
+    CASE(RETAIN, retain);
+    CASE(RELEASE, release);
+    CASE(GET_NUM_FLEX_PLANES, get_num_flex_planes);
+    CASE(LOCK, lock);
+    CASE(LOCK_FLEX, lock_flex);
+    CASE(UNLOCK, unlock);
+#undef CASE
+    default: return NULL;
+    }
+}
+
+static void device_get_capabilities(struct gralloc1_device* device,
+        uint32_t* outCount, int32_t* outCapabilities)
+{
+    *outCount = 0;
+}
+
+static int device_close(struct hw_device_t* device)
+{
+    struct gralloc1_adapter_device* dev =
+        (struct gralloc1_adapter_device*) device;
+    int ret;
+
+    ret = dev->alloc_dev->common.close(&dev->alloc_dev->common);
+    if (!ret) {
+        free(dev);
+    }
+
+    return ret;
+}
+
+int gralloc1_adapter_device_open(const struct hw_module_t* module,
+        const char* id, struct hw_device_t** device)
+{
+    const struct gralloc1_adapter_module* mod =
+        (const struct gralloc1_adapter_module*) module;
+    struct alloc_device_t* alloc_dev;
+    struct gralloc1_adapter_device* dev;
+    int ret;
+
+    if (strcmp(id, GRALLOC_HARDWARE_MODULE_ID) != 0) {
+        ALOGE("unknown gralloc1 device id: %s", id);
+        return -EINVAL;
+    }
+
+    ret = module->methods->open(module, GRALLOC_HARDWARE_GPU0,
+            (struct hw_device_t**) &alloc_dev);
+    if (ret) {
+        return ret;
+    }
+
+    dev = malloc(sizeof(*dev));
+    if (!dev) {
+        alloc_dev->common.close(&alloc_dev->common);
+        return -ENOMEM;
+    }
+
+    *dev = (struct gralloc1_adapter_device) {
+        .base = {
+            .common = {
+                .tag = HARDWARE_DEVICE_TAG,
+                .version = HARDWARE_DEVICE_API_VERSION(0, 0),
+                .module = (struct hw_module_t*) mod,
+                .close = device_close,
+            },
+            .getCapabilities = device_get_capabilities,
+            .getFunction = device_get_function,
+        },
+        .alloc_dev = alloc_dev,
+    };
+
+    *device = (struct hw_device_t*) dev;
+
+    return 0;
+}
diff --git a/graphics/allocator/2.0/default/gralloc1-adapter.h b/graphics/allocator/2.0/default/gralloc1-adapter.h
new file mode 100644 (file)
index 0000000..f48cd9e
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright 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.
+ */
+#ifndef ANDROID_HARDWARE_GRALLOC1_ADAPTER_H
+#define ANDROID_HARDWARE_GRALLOC1_ADAPTER_H
+
+#include <stdbool.h>
+#include <hardware/gralloc.h>
+
+__BEGIN_DECLS
+
+struct gralloc1_adapter_buffer_info {
+    int width;
+    int height;
+    int format;
+    int usage;
+
+    int stride;
+    uint32_t num_flex_planes;
+};
+
+/* This struct must be embedded in the HAL's HAL_MODULE_INFO_SYM and must
+ * follow gralloc_module_t immediately. */
+struct gralloc1_adapter {
+    uint16_t real_module_api_version;
+
+    /* Return true if the buffer is registered.  A locally allocated buffer is
+     * always registered.
+     *
+     * This function is called frequently.  It must be thread safe just like
+     * other functions are.
+     */
+    bool (*is_registered)(const struct gralloc_module_t* mod,
+            buffer_handle_t buffer);
+
+    /* Set the adapter data for a registered buffer. */
+    void (*set_data)(const struct gralloc_module_t* mod,
+            buffer_handle_t buffer, void* data);
+
+    /* Get the adapter data for a registered buffer. */
+    void* (*get_data)(const struct gralloc_module_t* mod,
+            buffer_handle_t buffer);
+
+    /* Get the buffer info, such as width, height, etc. */
+    void (*get_info)(const struct gralloc_module_t* mod,
+            buffer_handle_t buffer,
+            struct gralloc1_adapter_buffer_info* info);
+
+    /* Get the flexilble layout matching ycbcr. */
+    void (*get_flexible_layout)(const struct gralloc_module_t* mod,
+            buffer_handle_t buffer, const struct android_ycbcr* ycbcr,
+            struct android_flex_layout* layout);
+};
+
+int gralloc1_adapter_device_open(const struct hw_module_t* module,
+        const char* id, struct hw_device_t** device);
+
+__END_DECLS
+
+#endif /* ANDROID_HARDWARE_GRALLOC1_ADAPTER_H */
diff --git a/graphics/allocator/2.0/default/service.cpp b/graphics/allocator/2.0/default/service.cpp
new file mode 100644 (file)
index 0000000..525b342
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "android.hardware.graphics.allocator@2.0-service"
+
+#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
+
+#include <hidl/LegacySupport.h>
+
+using android::hardware::graphics::allocator::V2_0::IAllocator;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IAllocator>("gralloc");
+}
diff --git a/graphics/allocator/2.0/types.hal b/graphics/allocator/2.0/types.hal
new file mode 100644 (file)
index 0000000..23b7345
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * 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 android.hardware.graphics.allocator@2.0;
+
+enum Error : int32_t {
+    NONE            = 0, /* no error */
+    BAD_DESCRIPTOR  = 1, /* invalid BufferDescriptor */
+    BAD_BUFFER      = 2, /* invalid Buffer */
+    BAD_VALUE       = 3, /* invalid width, height, etc. */
+    NOT_SHARED      = 4, /* buffers not sharing backing store */
+    NO_RESOURCES    = 5, /* temporary failure due to resource contention */
+    UNDEFINED       = 6, /* an operation has no defined meaning */
+    UNSUPPORTED     = 7, /* permanent failure */
+};
+
+enum ProducerUsage : uint64_t {
+    /* bit 0 is reserved */
+
+    /* buffer will be read by CPU occasionally */
+    CPU_READ        = 1ULL << 1,
+    /* buffer will be read by CPU frequently */
+    CPU_READ_OFTEN  = 1ULL << 2,
+
+    /* bit 3 is reserved */
+    /* bit 4 is reserved */
+
+    /* buffer will be written by CPU occasionally */
+    CPU_WRITE       = 1ULL << 5,
+    /* buffer will be written by CPU frequently */
+    CPU_WRITE_OFTEN = 1ULL << 6,
+
+    /* bit 7 is reserved */
+    /* bit 8 is reserved */
+
+    /* buffer will be used as a GPU render target */
+    GPU_RENDER_TARGET = 1ULL << 9,
+
+    /* bit 10 is reserved */
+    /* bit 11 is reserved */
+    /* bit 12 is reserved */
+    /* bit 13 is reserved */
+
+    /*
+     * Buffer is allocated with hardware-level protection against copying the
+     * contents (or information derived from the contents) into unprotected
+     * memory.
+     */
+    PROTECTED         = 1ULL << 14,
+
+    /* bit 15 is reserved */
+    /* bit 16 is reserved */
+
+    /* buffer will be used as a camera HAL output */
+    CAMERA            = 1ULL << 17,
+
+    /* bit 18 is reserved */
+    /* bit 19 is reserved */
+    /* bit 20 is reserved */
+    /* bit 21 is reserved */
+
+    /* buffer will be used as a video decoder output */
+    VIDEO_DECODER     = 1ULL << 22,
+
+    /* bits 23-27 are reserved for future versions */
+    /* bits 28-31 are reserved for vendor extensions */
+
+    /* bits 32-47 are reserved for future versions */
+    /* bits 48-63 are reserved for vendor extensions */
+};
+
+enum ConsumerUsage : uint64_t {
+    /* bit 0 is reserved */
+
+    /* buffer will be read by CPU occasionally */
+    CPU_READ          = 1ULL << 1,
+    /* buffer will be read by CPU frequently */
+    CPU_READ_OFTEN    = 1ULL << 2,
+
+    /* bit 3 is reserved */
+    /* bit 4 is reserved */
+    /* bit 5 is reserved */
+    /* bit 6 is reserved */
+    /* bit 7 is reserved */
+
+    /* buffer will be used as a GPU texture */
+    GPU_TEXTURE       = 1ULL << 8,
+
+    /* bit 9 is reserved */
+    /* bit 10 is reserved */
+
+    /* buffer will be used by hwcomposer HAL */
+    HWCOMPOSER        = 1ULL << 11,
+    /* buffer will be as a hwcomposer HAL client target */
+    CLIENT_TARGET     = 1ULL << 12,
+
+    /* bit 13 is reserved */
+    /* bit 14 is reserved */
+
+    /* buffer will be used as a hwcomposer HAL cursor */
+    CURSOR            = 1ULL << 15,
+
+    /* buffer will be used as a video encoder input */
+    VIDEO_ENCODER     = 1ULL << 16,
+
+    /* bit 17 is reserved */
+
+    /* buffer will be used as a camera HAL input */
+    CAMERA            = 1ULL << 18,
+
+    /* bit 19 is reserved */
+
+    /* buffer will be used as a renderscript allocation */
+    RENDERSCRIPT      = 1ULL << 20,
+
+    /* bit 21 is reserved */
+    /* bit 22 is reserved */
+
+    /* bits 23-27 are reserved for future versions */
+    /* bits 28-31 are reserved for vendor extensions */
+
+    /* bits 32-47 are reserved for future versions */
+    /* bits 48-63 are reserved for vendor extensions */
+};
+
+/*
+ * Copied from android_pixel_format_t.
+ *
+ * TODO(olv) copy comments as well and have android_pixel_format_t generated
+ */
+@export(name="android_pixel_format", value_prefix="HAL_PIXEL_FORMAT_")
+enum PixelFormat : int32_t {
+    RGBA_8888              = 1,
+    RGBX_8888              = 2,
+    RGB_888                = 3,
+    RGB_565                = 4,
+    BGRA_8888              = 5,
+    YV12                   = 0x32315659,
+    Y8                     = 0x20203859,
+    Y16                    = 0x20363159,
+    RAW16                  = 0x20,
+    RAW10                  = 0x25,
+    RAW12                  = 0x26,
+    RAW_OPAQUE             = 0x24,
+    BLOB                   = 0x21,
+    IMPLEMENTATION_DEFINED = 0x22,
+    YCbCr_420_888          = 0x23,
+    YCbCr_422_888          = 0x27,
+    YCbCr_444_888          = 0x28,
+    FLEX_RGB_888           = 0x29,
+    FLEX_RGBA_8888         = 0x2A,
+    YCbCr_422_SP           = 0x10,
+    YCrCb_420_SP           = 0x11,
+    YCbCr_422_I            = 0x14,
+};
+
+typedef uint64_t BufferDescriptor;
+typedef uint64_t Buffer;
diff --git a/graphics/common/1.0/Android.bp b/graphics/common/1.0/Android.bp
new file mode 100644 (file)
index 0000000..fa95ca0
--- /dev/null
@@ -0,0 +1,43 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.graphics.common@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.graphics.common@1.0",
+    srcs: [
+        "types.hal",
+    ],
+    out: [
+        "android/hardware/graphics/common/1.0/types.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.graphics.common@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.graphics.common@1.0",
+    srcs: [
+        "types.hal",
+    ],
+    out: [
+        "android/hardware/graphics/common/1.0/types.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.graphics.common@1.0",
+    generated_sources: ["android.hardware.graphics.common@1.0_genc++"],
+    generated_headers: ["android.hardware.graphics.common@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.graphics.common@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/graphics/common/1.0/Android.mk b/graphics/common/1.0/Android.mk
new file mode 100644 (file)
index 0000000..17b67b6
--- /dev/null
@@ -0,0 +1,265 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.graphics.common@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (ColorMode)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/ColorMode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.ColorMode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ColorTransform)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/ColorTransform.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.ColorTransform
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Dataspace)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/Dataspace.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.Dataspace
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Hdr)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/Hdr.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.Hdr
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PixelFormat)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/PixelFormat.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.PixelFormat
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Transform)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/Transform.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.Transform
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.graphics.common@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (ColorMode)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/ColorMode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.ColorMode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ColorTransform)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/ColorTransform.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.ColorTransform
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Dataspace)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/Dataspace.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.Dataspace
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Hdr)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/Hdr.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.Hdr
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PixelFormat)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/PixelFormat.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.PixelFormat
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Transform)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/Transform.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0::types.Transform
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.graphics.common@1.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/graphics/common/1.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.graphics.common@1.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/graphics/common/1.0/types.hal b/graphics/common/1.0/types.hal
new file mode 100644 (file)
index 0000000..9726c3a
--- /dev/null
@@ -0,0 +1,1340 @@
+/*
+ * 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 android.hardware.graphics.common@1.0;
+
+/**
+ * pixel format definitions
+ */
+@export(name="android_pixel_format_t", value_prefix="HAL_PIXEL_FORMAT_")
+enum PixelFormat : int32_t {
+    /*
+     * "linear" color pixel formats:
+     *
+     * When used with ANativeWindow, the dataSpace field describes the color
+     * space of the buffer.
+     *
+     * The color space determines, for example, if the formats are linear or
+     * gamma-corrected; or whether any special operations are performed when
+     * reading or writing into a buffer in one of these formats.
+     */
+    RGBA_8888          = 1,
+    RGBX_8888          = 2,
+    RGB_888            = 3,
+    RGB_565            = 4,
+    BGRA_8888          = 5,
+
+    /*
+     * The following formats use a 16bit float per color component.
+     */
+    RGBA_FP16          = 0x10,
+    RGBX_FP16          = 0x11,
+
+    /*
+     * 0x100 - 0x1FF
+     *
+     * This range is reserved for pixel formats that are specific to the HAL
+     * implementation.  Implementations can use any value in this range to
+     * communicate video pixel formats between their HAL modules.  These formats
+     * must not have an alpha channel.  Additionally, an EGLimage created from a
+     * gralloc buffer of one of these formats must be supported for use with the
+     * GL_OES_EGL_image_external OpenGL ES extension.
+     */
+
+    /*
+     * Android YUV format:
+     *
+     * This format is exposed outside of the HAL to software decoders and
+     * applications.  EGLImageKHR must support it in conjunction with the
+     * OES_EGL_image_external extension.
+     *
+     * YV12 is a 4:2:0 YCrCb planar format comprised of a WxH Y plane followed
+     * by (W/2) x (H/2) Cr and Cb planes.
+     *
+     * This format assumes
+     * - an even width
+     * - an even height
+     * - a horizontal stride multiple of 16 pixels
+     * - a vertical stride equal to the height
+     *
+     *   y_size = stride * height
+     *   c_stride = ALIGN(stride/2, 16)
+     *   c_size = c_stride * height/2
+     *   size = y_size + c_size * 2
+     *   cr_offset = y_size
+     *   cb_offset = y_size + c_size
+     *
+     * When used with ANativeWindow, the dataSpace field describes the color
+     * space of the buffer.
+     */
+    YV12   = 0x32315659, // YCrCb 4:2:0 Planar
+
+
+    /*
+     * Android Y8 format:
+     *
+     * This format is exposed outside of the HAL to the framework.
+     * The expected gralloc usage flags are SW_* and HW_CAMERA_*,
+     * and no other HW_ flags will be used.
+     *
+     * Y8 is a YUV planar format comprised of a WxH Y plane,
+     * with each pixel being represented by 8 bits.
+     *
+     * It is equivalent to just the Y plane from YV12.
+     *
+     * This format assumes
+     * - an even width
+     * - an even height
+     * - a horizontal stride multiple of 16 pixels
+     * - a vertical stride equal to the height
+     *
+     *   size = stride * height
+     *
+     * When used with ANativeWindow, the dataSpace field describes the color
+     * space of the buffer.
+     */
+    Y8     = 0x20203859,
+
+    /*
+     * Android Y16 format:
+     *
+     * This format is exposed outside of the HAL to the framework.
+     * The expected gralloc usage flags are SW_* and HW_CAMERA_*,
+     * and no other HW_ flags will be used.
+     *
+     * Y16 is a YUV planar format comprised of a WxH Y plane,
+     * with each pixel being represented by 16 bits.
+     *
+     * It is just like Y8, but has double the bits per pixel (little endian).
+     *
+     * This format assumes
+     * - an even width
+     * - an even height
+     * - a horizontal stride multiple of 16 pixels
+     * - a vertical stride equal to the height
+     * - strides are specified in pixels, not in bytes
+     *
+     *   size = stride * height * 2
+     *
+     * When used with ANativeWindow, the dataSpace field describes the color
+     * space of the buffer, except that dataSpace field
+     * HAL_DATASPACE_DEPTH indicates that this buffer contains a depth
+     * image where each sample is a distance value measured by a depth camera,
+     * plus an associated confidence value.
+     */
+    Y16    = 0x20363159,
+
+    /*
+     * Android RAW sensor format:
+     *
+     * This format is exposed outside of the camera HAL to applications.
+     *
+     * RAW16 is a single-channel, 16-bit, little endian format, typically
+     * representing raw Bayer-pattern images from an image sensor, with minimal
+     * processing.
+     *
+     * The exact pixel layout of the data in the buffer is sensor-dependent, and
+     * needs to be queried from the camera device.
+     *
+     * Generally, not all 16 bits are used; more common values are 10 or 12
+     * bits. If not all bits are used, the lower-order bits are filled first.
+     * All parameters to interpret the raw data (black and white points,
+     * color space, etc) must be queried from the camera device.
+     *
+     * This format assumes
+     * - an even width
+     * - an even height
+     * - a horizontal stride multiple of 16 pixels
+     * - a vertical stride equal to the height
+     * - strides are specified in pixels, not in bytes
+     *
+     *   size = stride * height * 2
+     *
+     * This format must be accepted by the gralloc module when used with the
+     * following usage flags:
+     *    - GRALLOC_USAGE_HW_CAMERA_*
+     *    - GRALLOC_USAGE_SW_*
+     *    - GRALLOC_USAGE_RENDERSCRIPT
+     *
+     * When used with ANativeWindow, the dataSpace should be
+     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
+     * extra metadata to define.
+     */
+    RAW16 = 0x20,
+
+    /*
+     * Android RAW10 format:
+     *
+     * This format is exposed outside of the camera HAL to applications.
+     *
+     * RAW10 is a single-channel, 10-bit per pixel, densely packed in each row,
+     * unprocessed format, usually representing raw Bayer-pattern images coming from
+     * an image sensor.
+     *
+     * In an image buffer with this format, starting from the first pixel of each
+     * row, each 4 consecutive pixels are packed into 5 bytes (40 bits). Each one
+     * of the first 4 bytes contains the top 8 bits of each pixel, The fifth byte
+     * contains the 2 least significant bits of the 4 pixels, the exact layout data
+     * for each 4 consecutive pixels is illustrated below (Pi[j] stands for the jth
+     * bit of the ith pixel):
+     *
+     *          bit 7                                     bit 0
+     *          =====|=====|=====|=====|=====|=====|=====|=====|
+     * Byte 0: |P0[9]|P0[8]|P0[7]|P0[6]|P0[5]|P0[4]|P0[3]|P0[2]|
+     *         |-----|-----|-----|-----|-----|-----|-----|-----|
+     * Byte 1: |P1[9]|P1[8]|P1[7]|P1[6]|P1[5]|P1[4]|P1[3]|P1[2]|
+     *         |-----|-----|-----|-----|-----|-----|-----|-----|
+     * Byte 2: |P2[9]|P2[8]|P2[7]|P2[6]|P2[5]|P2[4]|P2[3]|P2[2]|
+     *         |-----|-----|-----|-----|-----|-----|-----|-----|
+     * Byte 3: |P3[9]|P3[8]|P3[7]|P3[6]|P3[5]|P3[4]|P3[3]|P3[2]|
+     *         |-----|-----|-----|-----|-----|-----|-----|-----|
+     * Byte 4: |P3[1]|P3[0]|P2[1]|P2[0]|P1[1]|P1[0]|P0[1]|P0[0]|
+     *          ===============================================
+     *
+     * This format assumes
+     * - a width multiple of 4 pixels
+     * - an even height
+     * - a vertical stride equal to the height
+     * - strides are specified in bytes, not in pixels
+     *
+     *   size = stride * height
+     *
+     * When stride is equal to width * (10 / 8), there will be no padding bytes at
+     * the end of each row, the entire image data is densely packed. When stride is
+     * larger than width * (10 / 8), padding bytes will be present at the end of each
+     * row (including the last row).
+     *
+     * This format must be accepted by the gralloc module when used with the
+     * following usage flags:
+     *    - GRALLOC_USAGE_HW_CAMERA_*
+     *    - GRALLOC_USAGE_SW_*
+     *    - GRALLOC_USAGE_RENDERSCRIPT
+     *
+     * When used with ANativeWindow, the dataSpace field should be
+     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
+     * extra metadata to define.
+     */
+    RAW10 = 0x25,
+
+    /*
+     * Android RAW12 format:
+     *
+     * This format is exposed outside of camera HAL to applications.
+     *
+     * RAW12 is a single-channel, 12-bit per pixel, densely packed in each row,
+     * unprocessed format, usually representing raw Bayer-pattern images coming from
+     * an image sensor.
+     *
+     * In an image buffer with this format, starting from the first pixel of each
+     * row, each two consecutive pixels are packed into 3 bytes (24 bits). The first
+     * and second byte contains the top 8 bits of first and second pixel. The third
+     * byte contains the 4 least significant bits of the two pixels, the exact layout
+     * data for each two consecutive pixels is illustrated below (Pi[j] stands for
+     * the jth bit of the ith pixel):
+     *
+     *           bit 7                                            bit 0
+     *          ======|======|======|======|======|======|======|======|
+     * Byte 0: |P0[11]|P0[10]|P0[ 9]|P0[ 8]|P0[ 7]|P0[ 6]|P0[ 5]|P0[ 4]|
+     *         |------|------|------|------|------|------|------|------|
+     * Byte 1: |P1[11]|P1[10]|P1[ 9]|P1[ 8]|P1[ 7]|P1[ 6]|P1[ 5]|P1[ 4]|
+     *         |------|------|------|------|------|------|------|------|
+     * Byte 2: |P1[ 3]|P1[ 2]|P1[ 1]|P1[ 0]|P0[ 3]|P0[ 2]|P0[ 1]|P0[ 0]|
+     *          =======================================================
+     *
+     * This format assumes:
+     * - a width multiple of 4 pixels
+     * - an even height
+     * - a vertical stride equal to the height
+     * - strides are specified in bytes, not in pixels
+     *
+     *   size = stride * height
+     *
+     * When stride is equal to width * (12 / 8), there will be no padding bytes at
+     * the end of each row, the entire image data is densely packed. When stride is
+     * larger than width * (12 / 8), padding bytes will be present at the end of
+     * each row (including the last row).
+     *
+     * This format must be accepted by the gralloc module when used with the
+     * following usage flags:
+     *    - GRALLOC_USAGE_HW_CAMERA_*
+     *    - GRALLOC_USAGE_SW_*
+     *    - GRALLOC_USAGE_RENDERSCRIPT
+     *
+     * When used with ANativeWindow, the dataSpace field should be
+     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
+     * extra metadata to define.
+     */
+    RAW12 = 0x26,
+
+    /*
+     * Android opaque RAW format:
+     *
+     * This format is exposed outside of the camera HAL to applications.
+     *
+     * RAW_OPAQUE is a format for unprocessed raw image buffers coming from an
+     * image sensor. The actual structure of buffers of this format is
+     * implementation-dependent.
+     *
+     * This format must be accepted by the gralloc module when used with the
+     * following usage flags:
+     *    - GRALLOC_USAGE_HW_CAMERA_*
+     *    - GRALLOC_USAGE_SW_*
+     *    - GRALLOC_USAGE_RENDERSCRIPT
+     *
+     * When used with ANativeWindow, the dataSpace field should be
+     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
+     * extra metadata to define.
+     */
+    RAW_OPAQUE = 0x24,
+
+    /*
+     * Android binary blob graphics buffer format:
+     *
+     * This format is used to carry task-specific data which does not have a
+     * standard image structure. The details of the format are left to the two
+     * endpoints.
+     *
+     * A typical use case is for transporting JPEG-compressed images from the
+     * Camera HAL to the framework or to applications.
+     *
+     * Buffers of this format must have a height of 1, and width equal to their
+     * size in bytes.
+     *
+     * When used with ANativeWindow, the mapping of the dataSpace field to
+     * buffer contents for BLOB is as follows:
+     *
+     *  dataSpace value               | Buffer contents
+     * -------------------------------+-----------------------------------------
+     *  HAL_DATASPACE_JFIF            | An encoded JPEG image
+     *  HAL_DATASPACE_DEPTH           | An android_depth_points buffer
+     *  Other                         | Unsupported
+     *
+     */
+    BLOB = 0x21,
+
+    /*
+     * Android format indicating that the choice of format is entirely up to the
+     * device-specific Gralloc implementation.
+     *
+     * The Gralloc implementation should examine the usage bits passed in when
+     * allocating a buffer with this format, and it should derive the pixel
+     * format from those usage flags.  This format will never be used with any
+     * of the GRALLOC_USAGE_SW_* usage flags.
+     *
+     * If a buffer of this format is to be used as an OpenGL ES texture, the
+     * framework will assume that sampling the texture will always return an
+     * alpha value of 1.0 (i.e. the buffer contains only opaque pixel values).
+     *
+     * When used with ANativeWindow, the dataSpace field describes the color
+     * space of the buffer.
+     */
+    IMPLEMENTATION_DEFINED = 0x22,
+
+    /*
+     * Android flexible YCbCr 4:2:0 formats
+     *
+     * This format allows platforms to use an efficient YCbCr/YCrCb 4:2:0
+     * buffer layout, while still describing the general format in a
+     * layout-independent manner.  While called YCbCr, it can be
+     * used to describe formats with either chromatic ordering, as well as
+     * whole planar or semiplanar layouts.
+     *
+     * struct android_ycbcr (below) is the the struct used to describe it.
+     *
+     * This format must be accepted by the gralloc module when
+     * USAGE_SW_WRITE_* or USAGE_SW_READ_* are set.
+     *
+     * This format is locked for use by gralloc's (*lock_ycbcr) method, and
+     * locking with the (*lock) method will return an error.
+     *
+     * When used with ANativeWindow, the dataSpace field describes the color
+     * space of the buffer.
+     */
+    YCBCR_420_888 = 0x23,
+
+    /*
+     * Android flexible YCbCr 4:2:2 formats
+     *
+     * This format allows platforms to use an efficient YCbCr/YCrCb 4:2:2
+     * buffer layout, while still describing the general format in a
+     * layout-independent manner.  While called YCbCr, it can be
+     * used to describe formats with either chromatic ordering, as well as
+     * whole planar or semiplanar layouts.
+     *
+     * This format is currently only used by SW readable buffers
+     * produced by MediaCodecs, so the gralloc module can ignore this format.
+     */
+    YCBCR_422_888 = 0x27,
+
+    /*
+     * Android flexible YCbCr 4:4:4 formats
+     *
+     * This format allows platforms to use an efficient YCbCr/YCrCb 4:4:4
+     * buffer layout, while still describing the general format in a
+     * layout-independent manner.  While called YCbCr, it can be
+     * used to describe formats with either chromatic ordering, as well as
+     * whole planar or semiplanar layouts.
+     *
+     * This format is currently only used by SW readable buffers
+     * produced by MediaCodecs, so the gralloc module can ignore this format.
+     */
+    YCBCR_444_888 = 0x28,
+
+    /*
+     * Android flexible RGB 888 formats
+     *
+     * This format allows platforms to use an efficient RGB/BGR/RGBX/BGRX
+     * buffer layout, while still describing the general format in a
+     * layout-independent manner.  While called RGB, it can be
+     * used to describe formats with either color ordering and optional
+     * padding, as well as whole planar layout.
+     *
+     * This format is currently only used by SW readable buffers
+     * produced by MediaCodecs, so the gralloc module can ignore this format.
+     */
+    FLEX_RGB_888 = 0x29,
+
+    /*
+     * Android flexible RGBA 8888 formats
+     *
+     * This format allows platforms to use an efficient RGBA/BGRA/ARGB/ABGR
+     * buffer layout, while still describing the general format in a
+     * layout-independent manner.  While called RGBA, it can be
+     * used to describe formats with any of the component orderings, as
+     * well as whole planar layout.
+     *
+     * This format is currently only used by SW readable buffers
+     * produced by MediaCodecs, so the gralloc module can ignore this format.
+     */
+    FLEX_RGBA_8888 = 0x2A,
+
+    /* Legacy formats (deprecated), used by ImageFormat.java */
+    YCBCR_422_SP       = 0x10, // NV16
+    YCRCB_420_SP       = 0x11, // NV21
+    YCBCR_422_I        = 0x14, // YUY2
+};
+
+/**
+ * Transformation definitions
+ *
+ * IMPORTANT NOTE:
+ * ROT_90 is applied CLOCKWISE and AFTER FLIP_{H|V}.
+ *
+ */
+@export(name="android_transform_t", value_prefix="HAL_TRANSFORM_")
+enum Transform : int32_t {
+    /* flip source image horizontally (around the vertical axis) */
+    FLIP_H    = 0x01,
+    /* flip source image vertically (around the horizontal axis)*/
+    FLIP_V    = 0x02,
+    /* rotate source image 90 degrees clockwise */
+    ROT_90    = 0x04,
+    /* rotate source image 180 degrees */
+    ROT_180   = 0x03,
+    /* rotate source image 270 degrees clockwise */
+    ROT_270   = 0x07,
+
+    /* 0x08 is reserved */
+};
+
+/**
+ * Dataspace Definitions
+ * ======================
+ *
+ * Dataspace is the definition of how pixel values should be interpreted.
+ *
+ * For many formats, this is the colorspace of the image data, which includes
+ * primaries (including white point) and the transfer characteristic function,
+ * which describes both gamma curve and numeric range (within the bit depth).
+ *
+ * Other dataspaces include depth measurement data from a depth camera.
+ *
+ * A dataspace is comprised of a number of fields.
+ *
+ * Version
+ * --------
+ * The top 2 bits represent the revision of the field specification. This is
+ * currently always 0.
+ *
+ *
+ * bits    31-30 29                      -                          0
+ *        +-----+----------------------------------------------------+
+ * fields | Rev |            Revision specific fields                |
+ *        +-----+----------------------------------------------------+
+ *
+ * Field layout for version = 0:
+ * ----------------------------
+ *
+ * A dataspace is comprised of the following fields:
+ *      Standard
+ *      Transfer function
+ *      Range
+ *
+ * bits    31-30 29-27 26 -  22 21 -  16 15             -           0
+ *        +-----+-----+--------+--------+----------------------------+
+ * fields |  0  |Range|Transfer|Standard|    Legacy and custom       |
+ *        +-----+-----+--------+--------+----------------------------+
+ *          VV    RRR   TTTTT    SSSSSS    LLLLLLLL       LLLLLLLL
+ *
+ * If range, transfer and standard fields are all 0 (e.g. top 16 bits are
+ * all zeroes), the bottom 16 bits contain either a legacy dataspace value,
+ * or a custom value.
+ */
+@export(name="android_dataspace_t", value_prefix="HAL_DATASPACE_")
+enum Dataspace : int32_t {
+    /*
+     * Default-assumption data space, when not explicitly specified.
+     *
+     * It is safest to assume the buffer is an image with sRGB primaries and
+     * encoding ranges, but the consumer and/or the producer of the data may
+     * simply be using defaults. No automatic gamma transform should be
+     * expected, except for a possible display gamma transform when drawn to a
+     * screen.
+     */
+    UNKNOWN = 0x0,
+
+    /*
+     * Arbitrary dataspace with manually defined characteristics.  Definition
+     * for colorspaces or other meaning must be communicated separately.
+     *
+     * This is used when specifying primaries, transfer characteristics,
+     * etc. separately.
+     *
+     * A typical use case is in video encoding parameters (e.g. for H.264),
+     * where a colorspace can have separately defined primaries, transfer
+     * characteristics, etc.
+     */
+    ARBITRARY = 0x1,
+
+    /*
+     * Color-description aspects
+     *
+     * The following aspects define various characteristics of the color
+     * specification. These represent bitfields, so that a data space value
+     * can specify each of them independently.
+     */
+
+    STANDARD_SHIFT = 16,
+
+    /*
+     * Standard aspect
+     *
+     * Defines the chromaticity coordinates of the source primaries in terms of
+     * the CIE 1931 definition of x and y specified in ISO 11664-1.
+     */
+    STANDARD_MASK = 63 << STANDARD_SHIFT,  // 0x3F
+
+    /*
+     * Chromacity coordinates are unknown or are determined by the application.
+     * Implementations shall use the following suggested standards:
+     *
+     * All YCbCr formats: BT709 if size is 720p or larger (since most video
+     *                    content is letterboxed this corresponds to width is
+     *                    1280 or greater, or height is 720 or greater).
+     *                    BT601_625 if size is smaller than 720p or is JPEG.
+     * All RGB formats:   BT709.
+     *
+     * For all other formats standard is undefined, and implementations should use
+     * an appropriate standard for the data represented.
+     */
+    STANDARD_UNSPECIFIED = 0 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.300   0.600
+     *  blue            0.150   0.060
+     *  red             0.640   0.330
+     *  white (D65)     0.3127  0.3290
+     *
+     * Use the unadjusted KR = 0.2126, KB = 0.0722 luminance interpretation
+     * for RGB conversion.
+     */
+    STANDARD_BT709 = 1 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.290   0.600
+     *  blue            0.150   0.060
+     *  red             0.640   0.330
+     *  white (D65)     0.3127  0.3290
+     *
+     *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
+     *  for RGB conversion from the one purely determined by the primaries
+     *  to minimize the color shift into RGB space that uses BT.709
+     *  primaries.
+     */
+    STANDARD_BT601_625 = 2 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.290   0.600
+     *  blue            0.150   0.060
+     *  red             0.640   0.330
+     *  white (D65)     0.3127  0.3290
+     *
+     * Use the unadjusted KR = 0.222, KB = 0.071 luminance interpretation
+     * for RGB conversion.
+     */
+    STANDARD_BT601_625_UNADJUSTED = 3 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.310   0.595
+     *  blue            0.155   0.070
+     *  red             0.630   0.340
+     *  white (D65)     0.3127  0.3290
+     *
+     *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
+     *  for RGB conversion from the one purely determined by the primaries
+     *  to minimize the color shift into RGB space that uses BT.709
+     *  primaries.
+     */
+    STANDARD_BT601_525 = 4 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.310   0.595
+     *  blue            0.155   0.070
+     *  red             0.630   0.340
+     *  white (D65)     0.3127  0.3290
+     *
+     * Use the unadjusted KR = 0.212, KB = 0.087 luminance interpretation
+     * for RGB conversion (as in SMPTE 240M).
+     */
+    STANDARD_BT601_525_UNADJUSTED = 5 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.170   0.797
+     *  blue            0.131   0.046
+     *  red             0.708   0.292
+     *  white (D65)     0.3127  0.3290
+     *
+     * Use the unadjusted KR = 0.2627, KB = 0.0593 luminance interpretation
+     * for RGB conversion.
+     */
+    STANDARD_BT2020 = 6 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.170   0.797
+     *  blue            0.131   0.046
+     *  red             0.708   0.292
+     *  white (D65)     0.3127  0.3290
+     *
+     * Use the unadjusted KR = 0.2627, KB = 0.0593 luminance interpretation
+     * for RGB conversion using the linear domain.
+     */
+    STANDARD_BT2020_CONSTANT_LUMINANCE = 7 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x      y
+     *  green           0.21   0.71
+     *  blue            0.14   0.08
+     *  red             0.67   0.33
+     *  white (C)       0.310  0.316
+     *
+     * Use the unadjusted KR = 0.30, KB = 0.11 luminance interpretation
+     * for RGB conversion.
+     */
+    STANDARD_BT470M = 8 << STANDARD_SHIFT,
+
+    /*
+     * Primaries:       x       y
+     *  green           0.243   0.692
+     *  blue            0.145   0.049
+     *  red             0.681   0.319
+     *  white (C)       0.310   0.316
+     *
+     * Use the unadjusted KR = 0.254, KB = 0.068 luminance interpretation
+     * for RGB conversion.
+     */
+    STANDARD_FILM = 9 << STANDARD_SHIFT,
+
+    /*
+     * SMPTE EG 432-1 and SMPTE RP 431-2. (DCI-P3)
+     * Primaries:       x       y
+     *  green           0.265   0.690
+     *  blue            0.150   0.060
+     *  red             0.680   0.320
+     *  white (D65)     0.3127  0.3290
+     */
+    STANDARD_DCI_P3 = 10 << STANDARD_SHIFT,
+
+    /*
+     * Adobe RGB
+     * Primaries:       x       y
+     *  green           0.210   0.710
+     *  blue            0.150   0.060
+     *  red             0.640   0.330
+     *  white (D65)     0.3127  0.3290
+     */
+    STANDARD_ADOBE_RGB = 11 << STANDARD_SHIFT,
+
+
+
+    TRANSFER_SHIFT = 22,
+
+    /*
+     * Transfer aspect
+     *
+     * Transfer characteristics are the opto-electronic transfer characteristic
+     * at the source as a function of linear optical intensity (luminance).
+     *
+     * For digital signals, E corresponds to the recorded value. Normally, the
+     * transfer function is applied in RGB space to each of the R, G and B
+     * components independently. This may result in color shift that can be
+     * minized by applying the transfer function in Lab space only for the L
+     * component. Implementation may apply the transfer function in RGB space
+     * for all pixel formats if desired.
+     */
+
+    TRANSFER_MASK = 31 << TRANSFER_SHIFT,  // 0x1F
+
+    /*
+     * Transfer characteristics are unknown or are determined by the
+     * application.
+     *
+     * Implementations should use the following transfer functions:
+     *
+     * For YCbCr formats: use TRANSFER_SMPTE_170M
+     * For RGB formats: use TRANSFER_SRGB
+     *
+     * For all other formats transfer function is undefined, and implementations
+     * should use an appropriate standard for the data represented.
+     */
+    TRANSFER_UNSPECIFIED = 0 << TRANSFER_SHIFT,
+
+    /*
+     * Transfer characteristic curve:
+     *  E = L
+     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
+     *      E - corresponding electrical signal
+     */
+    TRANSFER_LINEAR = 1 << TRANSFER_SHIFT,
+
+    /*
+     * Transfer characteristic curve:
+     *
+     * E = 1.055 * L^(1/2.4) - 0.055  for 0.0031308 <= L <= 1
+     *   = 12.92 * L                  for 0 <= L < 0.0031308
+     *     L - luminance of image 0 <= L <= 1 for conventional colorimetry
+     *     E - corresponding electrical signal
+     */
+    TRANSFER_SRGB = 2 << TRANSFER_SHIFT,
+
+    /*
+     * BT.601 525, BT.601 625, BT.709, BT.2020
+     *
+     * Transfer characteristic curve:
+     *  E = 1.099 * L ^ 0.45 - 0.099  for 0.018 <= L <= 1
+     *    = 4.500 * L                 for 0 <= L < 0.018
+     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
+     *      E - corresponding electrical signal
+     */
+    TRANSFER_SMPTE_170M = 3 << TRANSFER_SHIFT,
+
+    /*
+     * Assumed display gamma 2.2.
+     *
+     * Transfer characteristic curve:
+     *  E = L ^ (1/2.2)
+     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
+     *      E - corresponding electrical signal
+     */
+    TRANSFER_GAMMA2_2 = 4 << TRANSFER_SHIFT,
+
+    /*
+     *  display gamma 2.6.
+     *
+     * Transfer characteristic curve:
+     *  E = L ^ (1/2.6)
+     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
+     *      E - corresponding electrical signal
+     */
+    TRANSFER_GAMMA2_6 = 5 << TRANSFER_SHIFT,
+
+    /*
+     *  display gamma 2.8.
+     *
+     * Transfer characteristic curve:
+     *  E = L ^ (1/2.8)
+     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
+     *      E - corresponding electrical signal
+     */
+    TRANSFER_GAMMA2_8 = 6 << TRANSFER_SHIFT,
+
+    /*
+     * SMPTE ST 2084
+     *
+     * Transfer characteristic curve:
+     *  E = ((c1 + c2 * L^n) / (1 + c3 * L^n)) ^ m
+     *  c1 = c3 - c2 + 1 = 3424 / 4096 = 0.8359375
+     *  c2 = 32 * 2413 / 4096 = 18.8515625
+     *  c3 = 32 * 2392 / 4096 = 18.6875
+     *  m = 128 * 2523 / 4096 = 78.84375
+     *  n = 0.25 * 2610 / 4096 = 0.1593017578125
+     *      L - luminance of image 0 <= L <= 1 for HDR colorimetry.
+     *          L = 1 corresponds to 10000 cd/m2
+     *      E - corresponding electrical signal
+     */
+    TRANSFER_ST2084 = 7 << TRANSFER_SHIFT,
+
+    /*
+     * ARIB STD-B67 Hybrid Log Gamma
+     *
+     * Transfer characteristic curve:
+     *  E = r * L^0.5                 for 0 <= L <= 1
+     *    = a * ln(L - b) + c         for 1 < L
+     *  a = 0.17883277
+     *  b = 0.28466892
+     *  c = 0.55991073
+     *  r = 0.5
+     *      L - luminance of image 0 <= L for HDR colorimetry. L = 1 corresponds
+     *          to reference white level of 100 cd/m2
+     *      E - corresponding electrical signal
+     */
+    TRANSFER_HLG = 8 << TRANSFER_SHIFT,
+
+    RANGE_SHIFT = 27,
+
+    /*
+     * Range aspect
+     *
+     * Defines the range of values corresponding to the unit range of 0-1.
+     * This is defined for YCbCr only, but can be expanded to RGB space.
+     */
+    RANGE_MASK = 7 << RANGE_SHIFT,  // 0x7
+
+    /*
+     * Range is unknown or are determined by the application.  Implementations
+     * shall use the following suggested ranges:
+     *
+     * All YCbCr formats: limited range.
+     * All RGB or RGBA formats (including RAW and Bayer): full range.
+     * All Y formats: full range
+     *
+     * For all other formats range is undefined, and implementations should use
+     * an appropriate range for the data represented.
+     */
+    RANGE_UNSPECIFIED = 0 << RANGE_SHIFT,
+
+    /*
+     * Full range uses all values for Y, Cb and Cr from
+     * 0 to 2^b-1, where b is the bit depth of the color format.
+     */
+    RANGE_FULL = 1 << RANGE_SHIFT,
+
+    /*
+     * Limited range uses values 16/256*2^b to 235/256*2^b for Y, and
+     * 1/16*2^b to 15/16*2^b for Cb, Cr, R, G and B, where b is the bit depth of
+     * the color format.
+     *
+     * E.g. For 8-bit-depth formats:
+     * Luma (Y) samples should range from 16 to 235, inclusive
+     * Chroma (Cb, Cr) samples should range from 16 to 240, inclusive
+     *
+     * For 10-bit-depth formats:
+     * Luma (Y) samples should range from 64 to 940, inclusive
+     * Chroma (Cb, Cr) samples should range from 64 to 960, inclusive
+     */
+    RANGE_LIMITED = 2 << RANGE_SHIFT,
+
+    /*
+     * Extended range is used for scRGB. Intended for use with
+     * floating point pixel formats. [0.0 - 1.0] is the standard
+     * sRGB space. Values outside the range 0.0 - 1.0 can encode
+     * color outside the sRGB gamut.
+     * Used to blend / merge multiple dataspaces on a single display.
+     */
+    RANGE_EXTENDED = 3 << RANGE_SHIFT,
+
+    /*
+     * Legacy dataspaces
+     */
+
+    /*
+     * sRGB linear encoding:
+     *
+     * The red, green, and blue components are stored in sRGB space, but
+     * are linear, not gamma-encoded.
+     * The RGB primaries and the white point are the same as BT.709.
+     *
+     * The values are encoded using the full range ([0,255] for 8-bit) for all
+     * components.
+     */
+    SRGB_LINEAR = 0x200, // deprecated, use V0_SRGB_LINEAR
+
+    V0_SRGB_LINEAR = STANDARD_BT709 | TRANSFER_LINEAR | RANGE_FULL,
+
+
+    /*
+     * scRGB linear encoding:
+     *
+     * The red, green, and blue components are stored in extended sRGB space,
+     * but are linear, not gamma-encoded.
+     * The RGB primaries and the white point are the same as BT.709.
+     *
+     * The values are floating point.
+     * A pixel value of 1.0, 1.0, 1.0 corresponds to sRGB white (D65) at 80 nits.
+     * Values beyond the range [0.0 - 1.0] would correspond to other colors
+     * spaces and/or HDR content.
+     */
+    V0_SCRGB_LINEAR = STANDARD_BT709 | TRANSFER_LINEAR | RANGE_EXTENDED,
+
+
+    /*
+     * sRGB gamma encoding:
+     *
+     * The red, green and blue components are stored in sRGB space, and
+     * converted to linear space when read, using the SRGB transfer function
+     * for each of the R, G and B components. When written, the inverse
+     * transformation is performed.
+     *
+     * The alpha component, if present, is always stored in linear space and
+     * is left unmodified when read or written.
+     *
+     * Use full range and BT.709 standard.
+     */
+    SRGB = 0x201, // deprecated, use V0_SRGB
+
+    V0_SRGB = STANDARD_BT709 | TRANSFER_SRGB | RANGE_FULL,
+
+
+    /*
+     * scRGB:
+     *
+     * The red, green, and blue components are stored in extended sRGB space,
+     * but are linear, not gamma-encoded.
+     * The RGB primaries and the white point are the same as BT.709.
+     *
+     * The values are floating point.
+     * A pixel value of 1.0, 1.0, 1.0 corresponds to sRGB white (D65) at 80 nits.
+     * Values beyond the range [0.0 - 1.0] would correspond to other colors
+     * spaces and/or HDR content.
+     *
+     * TODO (courtneygo): Will we actually use this? We intend to use FP16
+     * storage for data using scRGB so we can do all work in linear space
+     * and don't have to worry as much about limited precision.
+     */
+    V0_SCRGB = STANDARD_BT709 | TRANSFER_SRGB | RANGE_EXTENDED,
+
+    /*
+     * YCbCr Colorspaces
+     * -----------------
+     *
+     * Primaries are given using (x,y) coordinates in the CIE 1931 definition
+     * of x and y specified by ISO 11664-1.
+     *
+     * Transfer characteristics are the opto-electronic transfer characteristic
+     * at the source as a function of linear optical intensity (luminance).
+     */
+
+    /*
+     * JPEG File Interchange Format (JFIF)
+     *
+     * Same model as BT.601-625, but all values (Y, Cb, Cr) range from 0 to 255
+     *
+     * Use full range, BT.601 transfer and BT.601_625 standard.
+     */
+    JFIF = 0x101, // deprecated, use V0_JFIF
+
+    V0_JFIF = STANDARD_BT601_625 | TRANSFER_SMPTE_170M | RANGE_FULL,
+
+    /*
+     * ITU-R Recommendation 601 (BT.601) - 625-line
+     *
+     * Standard-definition television, 625 Lines (PAL)
+     *
+     * Use limited range, BT.601 transfer and BT.601_625 standard.
+     */
+    BT601_625 = 0x102, // deprecated, use V0_BT601_625
+
+    V0_BT601_625 = STANDARD_BT601_625 | TRANSFER_SMPTE_170M | RANGE_LIMITED,
+
+
+    /*
+     * ITU-R Recommendation 601 (BT.601) - 525-line
+     *
+     * Standard-definition television, 525 Lines (NTSC)
+     *
+     * Use limited range, BT.601 transfer and BT.601_525 standard.
+     */
+    BT601_525 = 0x103, // deprecated, use V0_BT601_525
+
+    V0_BT601_525 = STANDARD_BT601_525 | TRANSFER_SMPTE_170M | RANGE_LIMITED,
+
+    /*
+     * ITU-R Recommendation 709 (BT.709)
+     *
+     * High-definition television
+     *
+     * Use limited range, BT.709 transfer and BT.709 standard.
+     */
+    BT709 = 0x104, // deprecated, use V0_BT709
+
+    V0_BT709 = STANDARD_BT709 | TRANSFER_SMPTE_170M | RANGE_LIMITED,
+
+
+    /*
+     * SMPTE EG 432-1 and SMPTE RP 431-2.
+     *
+     * Digital Cinema DCI-P3
+     *
+     * Use full range, linear transfer and D65 DCI-P3 standard
+     */
+    DCI_P3_LINEAR = STANDARD_DCI_P3 | TRANSFER_LINEAR | RANGE_FULL,
+
+
+    /*
+     * SMPTE EG 432-1 and SMPTE RP 431-2.
+     *
+     * Digital Cinema DCI-P3
+     *
+     * Use full range, gamma 2.6 transfer and D65 DCI-P3 standard
+     * Note: Application is responsible for gamma encoding the data as
+     * a 2.6 gamma encoding is not supported in HW.
+     */
+    DCI_P3 = STANDARD_DCI_P3 | TRANSFER_GAMMA2_6 | RANGE_FULL,
+
+
+    /*
+     * Adobe RGB
+     *
+     * Use full range, gamma 2.2 transfer and Adobe RGB primaries
+     * Note: Application is responsible for gamma encoding the data as
+     * a 2.2 gamma encoding is not supported in HW.
+     */
+    ADOBE_RGB = STANDARD_ADOBE_RGB | TRANSFER_GAMMA2_2 | RANGE_FULL,
+
+
+    /*
+     * ITU-R Recommendation 2020 (BT.2020)
+     *
+     * Ultra High-definition television
+     *
+     * Use full range, linear transfer and BT2020 standard
+     */
+    BT2020_LINEAR = STANDARD_BT2020 | TRANSFER_LINEAR | RANGE_FULL,
+
+
+    /*
+     * ITU-R Recommendation 2020 (BT.2020)
+     *
+     * Ultra High-definition television
+     *
+     * Use full range, BT.709 transfer and BT2020 standard
+     */
+    BT2020 = STANDARD_BT2020 | TRANSFER_SMPTE_170M | RANGE_FULL,
+
+
+    /*
+     * Data spaces for non-color formats
+     */
+
+    /*
+     * The buffer contains depth ranging measurements from a depth camera.
+     * This value is valid with formats:
+     *    HAL_PIXEL_FORMAT_Y16: 16-bit samples, consisting of a depth measurement
+     *       and an associated confidence value. The 3 MSBs of the sample make
+     *       up the confidence value, and the low 13 LSBs of the sample make up
+     *       the depth measurement.
+     *       For the confidence section, 0 means 100% confidence, 1 means 0%
+     *       confidence. The mapping to a linear float confidence value between
+     *       0.f and 1.f can be obtained with
+     *         float confidence = (((depthSample >> 13) - 1) & 0x7) / 7.0f;
+     *       The depth measurement can be extracted simply with
+     *         uint16_t range = (depthSample & 0x1FFF);
+     *    HAL_PIXEL_FORMAT_BLOB: A depth point cloud, as
+     *       a variable-length float (x,y,z, confidence) coordinate point list.
+     *       The point cloud will be represented with the android_depth_points
+     *       structure.
+     */
+    DEPTH = 0x1000
+};
+
+/*
+ * Color modes that may be supported by a display.
+ *
+ * Definitions:
+ * Rendering intent generally defines the goal in mapping a source (input)
+ * color to a destination device color for a given color mode.
+ *
+ *  It is important to keep in mind three cases where mapping may be applied:
+ *  1. The source gamut is much smaller than the destination (display) gamut
+ *  2. The source gamut is much larger than the destination gamut (this will
+ *  ordinarily be handled using colorimetric rendering, below)
+ *  3. The source and destination gamuts are roughly equal, although not
+ *  completely overlapping
+ *  Also, a common requirement for mappings is that skin tones should be
+ *  preserved, or at least remain natural in appearance.
+ *
+ *  Colorimetric Rendering Intent (All cases):
+ *  Colorimetric indicates that colors should be preserved. In the case
+ *  that the source gamut lies wholly within the destination gamut or is
+ *  about the same (#1, #3), this will simply mean that no manipulations
+ *  (no saturation boost, for example) are applied. In the case where some
+ *  source colors lie outside the destination gamut (#2, #3), those will
+ *  need to be mapped to colors that are within the destination gamut,
+ *  while the already in-gamut colors remain unchanged.
+ *
+ *  Non-colorimetric transforms can take many forms. There are no hard
+ *  rules and it's left to the implementation to define.
+ *  Two common intents are described below.
+ *
+ *  Stretched-Gamut Enhancement Intent (Source < Destination):
+ *  When the destination gamut is much larger than the source gamut (#1), the
+ *  source primaries may be redefined to reflect the full extent of the
+ *  destination space, or to reflect an intermediate gamut.
+ *  Skin-tone preservation would likely be applied. An example might be sRGB
+ *  input displayed on a DCI-P3 capable device, with skin-tone preservation.
+ *
+ *  Within-Gamut Enhancement Intent (Source >= Destination):
+ *  When the device (destination) gamut is not larger than the source gamut
+ *  (#2 or #3), but the appearance of a larger gamut is desired, techniques
+ *  such as saturation boost may be applied to the source colors. Skin-tone
+ *  preservation may be applied. There is no unique method for within-gamut
+ *  enhancement; it would be defined within a flexible color mode.
+ *
+ */
+@export(name="android_color_mode_t", value_prefix="HAL_COLOR_MODE_")
+enum ColorMode : int32_t {
+  /*
+   * DEFAULT is the "native" gamut of the display.
+   * White Point: Vendor/OEM defined
+   * Panel Gamma: Vendor/OEM defined (typically 2.2)
+   * Rendering Intent: Vendor/OEM defined (typically 'enhanced')
+   */
+  NATIVE = 0,
+
+  /*
+   * STANDARD_BT601_625 corresponds with display
+   * settings that implement the ITU-R Recommendation BT.601
+   * or Rec 601. Using 625 line version
+   * Rendering Intent: Colorimetric
+   * Primaries:
+   *                  x       y
+   *  green           0.290   0.600
+   *  blue            0.150   0.060
+   *  red             0.640   0.330
+   *  white (D65)     0.3127  0.3290
+   *
+   *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
+   *  for RGB conversion from the one purely determined by the primaries
+   *  to minimize the color shift into RGB space that uses BT.709
+   *  primaries.
+   *
+   * Gamma Correction (GC):
+   *
+   *  if Vlinear < 0.018
+   *    Vnonlinear = 4.500 * Vlinear
+   *  else
+   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
+   */
+  STANDARD_BT601_625 = 1,
+
+  /*
+   * Primaries:
+   *                  x       y
+   *  green           0.290   0.600
+   *  blue            0.150   0.060
+   *  red             0.640   0.330
+   *  white (D65)     0.3127  0.3290
+   *
+   *  Use the unadjusted KR = 0.222, KB = 0.071 luminance interpretation
+   *  for RGB conversion.
+   *
+   * Gamma Correction (GC):
+   *
+   *  if Vlinear < 0.018
+   *    Vnonlinear = 4.500 * Vlinear
+   *  else
+   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
+   */
+  STANDARD_BT601_625_UNADJUSTED = 2,
+
+  /*
+   * Primaries:
+   *                  x       y
+   *  green           0.310   0.595
+   *  blue            0.155   0.070
+   *  red             0.630   0.340
+   *  white (D65)     0.3127  0.3290
+   *
+   *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
+   *  for RGB conversion from the one purely determined by the primaries
+   *  to minimize the color shift into RGB space that uses BT.709
+   *  primaries.
+   *
+   * Gamma Correction (GC):
+   *
+   *  if Vlinear < 0.018
+   *    Vnonlinear = 4.500 * Vlinear
+   *  else
+   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
+   */
+  STANDARD_BT601_525 = 3,
+
+  /*
+   * Primaries:
+   *                  x       y
+   *  green           0.310   0.595
+   *  blue            0.155   0.070
+   *  red             0.630   0.340
+   *  white (D65)     0.3127  0.3290
+   *
+   *  Use the unadjusted KR = 0.212, KB = 0.087 luminance interpretation
+   *  for RGB conversion (as in SMPTE 240M).
+   *
+   * Gamma Correction (GC):
+   *
+   *  if Vlinear < 0.018
+   *    Vnonlinear = 4.500 * Vlinear
+   *  else
+   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
+   */
+  STANDARD_BT601_525_UNADJUSTED = 4,
+
+  /*
+   * REC709 corresponds with display settings that implement
+   * the ITU-R Recommendation BT.709 / Rec. 709 for high-definition television.
+   * Rendering Intent: Colorimetric
+   * Primaries:
+   *                  x       y
+   *  green           0.300   0.600
+   *  blue            0.150   0.060
+   *  red             0.640   0.330
+   *  white (D65)     0.3127  0.3290
+   *
+   * HDTV REC709 Inverse Gamma Correction (IGC): V represents normalized
+   * (with [0 to 1] range) value of R, G, or B.
+   *
+   *  if Vnonlinear < 0.081
+   *    Vlinear = Vnonlinear / 4.5
+   *  else
+   *    Vlinear = ((Vnonlinear + 0.099) / 1.099) ^ (1/0.45)
+   *
+   * HDTV REC709 Gamma Correction (GC):
+   *
+   *  if Vlinear < 0.018
+   *    Vnonlinear = 4.5 * Vlinear
+   *  else
+   *    Vnonlinear = 1.099 * (Vlinear) ^ 0.45 – 0.099
+   */
+  STANDARD_BT709 = 5,
+
+  /*
+   * DCI_P3 corresponds with display settings that implement
+   * SMPTE EG 432-1 and SMPTE RP 431-2
+   * Rendering Intent: Colorimetric
+   * Primaries:
+   *                  x       y
+   *  green           0.265   0.690
+   *  blue            0.150   0.060
+   *  red             0.680   0.320
+   *  white (D65)     0.3127  0.3290
+   *
+   * Gamma: 2.2
+   */
+  DCI_P3 = 6,
+
+  /*
+   * SRGB corresponds with display settings that implement
+   * the sRGB color space. Uses the same primaries as ITU-R Recommendation
+   * BT.709
+   * Rendering Intent: Colorimetric
+   * Primaries:
+   *                  x       y
+   *  green           0.300   0.600
+   *  blue            0.150   0.060
+   *  red             0.640   0.330
+   *  white (D65)     0.3127  0.3290
+   *
+   * PC/Internet (sRGB) Inverse Gamma Correction (IGC):
+   *
+   *  if Vnonlinear ≤ 0.03928
+   *    Vlinear = Vnonlinear / 12.92
+   *  else
+   *    Vlinear = ((Vnonlinear + 0.055)/1.055) ^ 2.4
+   *
+   * PC/Internet (sRGB) Gamma Correction (GC):
+   *
+   *  if Vlinear ≤ 0.0031308
+   *    Vnonlinear = 12.92 * Vlinear
+   *  else
+   *    Vnonlinear = 1.055 * (Vlinear)^(1/2.4) – 0.055
+   */
+  SRGB = 7,
+
+  /*
+   * ADOBE_RGB corresponds with the RGB color space developed
+   * by Adobe Systems, Inc. in 1998.
+   * Rendering Intent: Colorimetric
+   * Primaries:
+   *                  x       y
+   *  green           0.210   0.710
+   *  blue            0.150   0.060
+   *  red             0.640   0.330
+   *  white (D65)     0.3127  0.3290
+   *
+   * Gamma: 2.2
+   */
+  ADOBE_RGB = 8
+};
+
+/*
+ * Color transforms that may be applied by hardware composer to the whole
+ * display.
+ */
+@export(name="android_color_transform_t", value_prefix="HAL_COLOR_TRANSFORM_")
+enum ColorTransform : int32_t {
+    /* Applies no transform to the output color */
+    IDENTITY = 0,
+
+    /* Applies an arbitrary transform defined by a 4x4 affine matrix */
+    ARBITRARY_MATRIX = 1,
+
+    /* Applies a transform that inverts the value or luminance of the color, but
+     * does not modify hue or saturation */
+    VALUE_INVERSE = 2,
+
+    /* Applies a transform that maps all colors to shades of gray */
+    GRAYSCALE = 3,
+
+    /* Applies a transform which corrects for protanopic color blindness */
+    CORRECT_PROTANOPIA = 4,
+
+    /* Applies a transform which corrects for deuteranopic color blindness */
+    CORRECT_DEUTERANOPIA = 5,
+
+    /* Applies a transform which corrects for tritanopic color blindness */
+    CORRECT_TRITANOPIA = 6
+};
+
+/*
+ * Supported HDR formats. Must be kept in sync with equivalents in Display.java.
+ */
+@export(name="android_hdr_t", value_prefix="HAL_HDR_")
+enum Hdr : int32_t {
+    /* Device supports Dolby Vision HDR */
+    DOLBY_VISION = 1,
+
+    /* Device supports HDR10 */
+    HDR10 = 2,
+
+    /* Device supports hybrid log-gamma HDR */
+    HLG = 3
+};
diff --git a/graphics/composer/2.1/Android.bp b/graphics/composer/2.1/Android.bp
new file mode 100644 (file)
index 0000000..fa58dbb
--- /dev/null
@@ -0,0 +1,61 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.graphics.composer@2.1_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.graphics.composer@2.1",
+    srcs: [
+        "types.hal",
+        "IComposer.hal",
+        "IComposerCallback.hal",
+    ],
+    out: [
+        "android/hardware/graphics/composer/2.1/types.cpp",
+        "android/hardware/graphics/composer/2.1/ComposerAll.cpp",
+        "android/hardware/graphics/composer/2.1/ComposerCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.graphics.composer@2.1_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.graphics.composer@2.1",
+    srcs: [
+        "types.hal",
+        "IComposer.hal",
+        "IComposerCallback.hal",
+    ],
+    out: [
+        "android/hardware/graphics/composer/2.1/types.h",
+        "android/hardware/graphics/composer/2.1/IComposer.h",
+        "android/hardware/graphics/composer/2.1/IHwComposer.h",
+        "android/hardware/graphics/composer/2.1/BnComposer.h",
+        "android/hardware/graphics/composer/2.1/BpComposer.h",
+        "android/hardware/graphics/composer/2.1/BsComposer.h",
+        "android/hardware/graphics/composer/2.1/IComposerCallback.h",
+        "android/hardware/graphics/composer/2.1/IHwComposerCallback.h",
+        "android/hardware/graphics/composer/2.1/BnComposerCallback.h",
+        "android/hardware/graphics/composer/2.1/BpComposerCallback.h",
+        "android/hardware/graphics/composer/2.1/BsComposerCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.graphics.composer@2.1",
+    generated_sources: ["android.hardware.graphics.composer@2.1_genc++"],
+    generated_headers: ["android.hardware.graphics.composer@2.1_genc++_headers"],
+    export_generated_headers: ["android.hardware.graphics.composer@2.1_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.graphics.allocator@2.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.graphics.allocator@2.0",
+    ],
+}
diff --git a/graphics/composer/2.1/IComposer.hal b/graphics/composer/2.1/IComposer.hal
new file mode 100644 (file)
index 0000000..7bfa22b
--- /dev/null
@@ -0,0 +1,1166 @@
+/*
+ * 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 android.hardware.graphics.composer@2.1;
+
+import android.hardware.graphics.allocator@2.0::PixelFormat;
+import IComposerCallback;
+
+interface IComposer {
+    /*
+     * Optional capabilities which may be supported by some devices. The
+     * particular set of supported capabilities for a given device may be
+     * retrieved using getCapabilities.
+     */
+    enum Capability : int32_t {
+        INVALID = 0,
+
+        /*
+         * Specifies that the device supports sideband stream layers, for
+         * which buffer content updates and other synchronization will not be
+         * provided through the usual validate/present cycle and must be
+         * handled by an external implementation-defined mechanism. Only
+         * changes to layer state (such as position, size, etc.) need to be
+         * performed through the validate/present cycle.
+         */
+        SIDEBAND_STREAM = 1,
+
+        /*
+         * Specifies that the device will apply a color transform even when
+         * either the client or the device has chosen that all layers should
+         * be composed by the client. This will prevent the client from
+         * applying the color transform during its composition step.
+         */
+        SKIP_CLIENT_COLOR_TRANSFORM = 2,
+    };
+
+    /* Display attributes queryable through getDisplayAttribute. */
+    enum Attribute : int32_t {
+        INVALID = 0,
+
+        /* Dimensions in pixels */
+        WIDTH = 1,
+        HEIGHT = 2,
+
+        /* Vsync period in nanoseconds */
+        VSYNC_PERIOD = 3,
+
+        /*
+         * Dots per thousand inches (DPI * 1000). Scaling by 1000 allows these
+         * numbers to be stored in an int32_t without losing too much
+         * precision. If the DPI for a configuration is unavailable or is
+         * considered unreliable, the device may return UNSUPPORTED instead.
+         */
+        DPI_X = 4,
+        DPI_Y = 5,
+    };
+
+    /* Display requests returned by getDisplayRequests. */
+    enum DisplayRequest : uint32_t {
+        /*
+         * Instructs the client to provide a new client target buffer, even if
+         * no layers are marked for client composition.
+         */
+        FLIP_CLIENT_TARGET = 1 << 0,
+
+        /*
+         * Instructs the client to write the result of client composition
+         * directly into the virtual display output buffer. If any of the
+         * layers are not marked as Composition::CLIENT or the given display
+         * is not a virtual display, this request has no effect.
+         */
+        WRITE_CLIENT_TARGET_TO_OUTPUT = 1 << 1,
+    };
+
+    /* Layer requests returned from getDisplayRequests. */
+    enum LayerRequest : uint32_t {
+        /*
+         * The client should clear its target with transparent pixels where
+         * this layer would be. The client may ignore this request if the
+         * layer must be blended.
+         */
+        CLEAR_CLIENT_TARGET = 1 << 0,
+    };
+
+    /* Power modes for use with setPowerMode. */
+    enum PowerMode : int32_t {
+        /* The display is fully off (blanked). */
+        OFF = 0,
+
+        /*
+         * These are optional low power modes. getDozeSupport may be called to
+         * determine whether a given display supports these modes.
+         */
+
+        /*
+         * The display is turned on and configured in a low power state that
+         * is suitable for presenting ambient information to the user,
+         * possibly with lower fidelity than ON, but with greater efficiency.
+         */
+        DOZE = 1,
+
+        /*
+         * The display is configured as in DOZE but may stop applying display
+         * updates from the client. This is effectively a hint to the device
+         * that drawing to the display has been suspended and that the the
+         * device should remain on in a low power state and continue
+         * displaying its current contents indefinitely until the power mode
+         * changes.
+         *
+         * This mode may also be used as a signal to enable hardware-based
+         * doze functionality. In this case, the device is free to take over
+         * the display and manage it autonomously to implement a low power
+         * always-on display.
+         */
+        DOZE_SUSPEND = 3,
+
+        /* The display is fully on. */
+        ON = 2,
+    };
+
+    /* Vsync values passed to setVsyncEnabled. */
+    enum Vsync : int32_t {
+        INVALID = 0,
+
+        /* Enable vsync. */
+        ENABLE = 1,
+
+        /* Disable vsync. */
+        DISABLE = 2,
+    };
+
+    /* Blend modes, settable per layer. */
+    enum BlendMode : int32_t {
+        INVALID = 0,
+
+        /* colorOut = colorSrc */
+        NONE = 1,
+
+        /* colorOut = colorSrc + colorDst * (1 - alphaSrc) */
+        PREMULTIPLIED = 2,
+
+        /* colorOut = colorSrc * alphaSrc + colorDst * (1 - alphaSrc) */
+        COVERAGE = 3,
+    };
+
+    /* Possible composition types for a given layer. */
+    enum Composition : int32_t {
+        INVALID = 0,
+
+        /*
+         * The client will composite this layer into the client target buffer
+         * (provided to the device through setClientTarget).
+         *
+         * The device must not request any composition type changes for layers
+         * of this type.
+         */
+        CLIENT = 1,
+
+        /*
+         * The device will handle the composition of this layer through a
+         * hardware overlay or other similar means.
+         *
+         * Upon validateDisplay, the device may request a change from this
+         * type to CLIENT.
+         */
+        DEVICE = 2,
+
+        /*
+         * The device will render this layer using the color set through
+         * setLayerColor. If this functionality is not supported on a layer
+         * that the client sets to SOLID_COLOR, the device must request that
+         * the composition type of that layer is changed to CLIENT upon the
+         * next call to validateDisplay.
+         *
+         * Upon validateDisplay, the device may request a change from this
+         * type to CLIENT.
+         */
+        SOLID_COLOR = 3,
+
+        /*
+         * Similar to DEVICE, but the position of this layer may also be set
+         * asynchronously through setCursorPosition. If this functionality is
+         * not supported on a layer that the client sets to CURSOR, the device
+         * must request that the composition type of that layer is changed to
+         * CLIENT upon the next call to validateDisplay.
+         *
+         * Upon validateDisplay, the device may request a change from this
+         * type to either DEVICE or CLIENT.  Changing to DEVICE will prevent
+         * the use of setCursorPosition but still permit the device to
+         * composite the layer.
+         */
+        CURSOR = 4,
+
+        /*
+         * The device will handle the composition of this layer, as well as
+         * its buffer updates and content synchronization. Only supported on
+         * devices which provide Capability::SIDEBAND_STREAM.
+         *
+         * Upon validateDisplay, the device may request a change from this
+         * type to either DEVICE or CLIENT, but it is unlikely that content
+         * will display correctly in these cases.
+         */
+        SIDEBAND = 5,
+    };
+
+    /* Display types returned by getDisplayType. */
+    enum DisplayType : int32_t {
+        INVALID = 0,
+
+        /*
+         * All physical displays, including both internal displays and
+         * hotpluggable external displays.
+         */
+        PHYSICAL = 1,
+
+        /* Virtual displays created by createVirtualDisplay. */
+        VIRTUAL = 2,
+    };
+
+    struct Rect {
+        int32_t left;
+        int32_t top;
+        int32_t right;
+        int32_t bottom;
+    };
+
+    struct FRect {
+        float left;
+        float top;
+        float right;
+        float bottom;
+    };
+
+    struct Color {
+        uint8_t r;
+        uint8_t g;
+        uint8_t b;
+        uint8_t a;
+    };
+
+    /*
+     * Provides a list of supported capabilities (as described in the
+     * definition of Capability above). This list must not change after
+     * initialization.
+     *
+     * @return capabilities is a list of supported capabilities.
+     */
+    getCapabilities() generates (vec<Capability> capabilities);
+
+    /*
+     * Retrieves implementation-defined debug information, which will be
+     * displayed during, for example, `dumpsys SurfaceFlinger`.
+     *
+     * @return debugInfo is a string of debug information.
+     */
+    dumpDebugInfo() generates (string debugInfo);
+
+    /*
+     * Provides a IComposerCallback object for the device to call.
+     *
+     * @param callback is the IComposerCallback object.
+     */
+    registerCallback(IComposerCallback callback);
+
+    /*
+     * Returns the maximum number of virtual displays supported by this device
+     * (which may be 0). The client will not attempt to create more than this
+     * many virtual displays on this device. This number must not change for
+     * the lifetime of the device.
+     */
+    getMaxVirtualDisplayCount() generates (uint32_t count);
+
+    /*
+     * Creates a new virtual display with the given width and height. The
+     * format passed into this function is the default format requested by the
+     * consumer of the virtual display output buffers.
+     *
+     * The display will be assumed to be on from the time the first frame is
+     * presented until the display is destroyed.
+     *
+     * @param width is the width in pixels.
+     * @param height is the height in pixels.
+     * @param formatHint is the default output buffer format selected by
+     *        the consumer.
+     * @return error is NONE upon success. Otherwise,
+     *         UNSUPPORTED when the width or height is too large for the
+     *                     device to be able to create a virtual display.
+     *         NO_RESOURCES when the device is unable to create a new virtual
+     *                      display at this time.
+     * @return display is the newly-created virtual display.
+     * @return format is the format of the buffer the device will produce.
+     */
+    createVirtualDisplay(uint32_t width,
+                         uint32_t height,
+                         PixelFormat formatHint)
+              generates (Error error,
+                         Display display,
+                         PixelFormat format);
+
+    /*
+     * Destroys a virtual display. After this call all resources consumed by
+     * this display may be freed by the device and any operations performed on
+     * this display should fail.
+     *
+     * @param display is the virtual display to destroy.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_PARAMETER when the display handle which was passed in does
+     *                       not refer to a virtual display.
+     */
+    destroyVirtualDisplay(Display display) generates (Error error);
+
+    /*
+     * Accepts the changes required by the device from the previous
+     * validateDisplay call (which may be queried using
+     * getChangedCompositionTypes) and revalidates the display. This function
+     * is equivalent to requesting the changed types from
+     * getChangedCompositionTypes, setting those types on the corresponding
+     * layers, and then calling validateDisplay again.
+     *
+     * After this call it must be valid to present this display. Calling this
+     * after validateDisplay returns 0 changes must succeed with NONE, but
+     * should have no other effect.
+     *
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         NOT_VALIDATED when validateDisplay has not been called.
+     */
+    acceptDisplayChanges(Display display) generates (Error error);
+
+    /*
+     * Creates a new layer on the given display.
+     *
+     * @param display is the display on which to create the layer.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         NO_RESOURCES when the device was unable to create a layer this
+     *                      time.
+     * @return layer is the handle of the new layer.
+     */
+    createLayer(Display display) generates (Error error, Layer layer);
+
+    /*
+     * Destroys the given layer.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to destroy.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    destroyLayer(Display display, Layer layer) generates (Error error);
+
+    /*
+     * Retrieves which display configuration is currently active.
+     *
+     * If no display configuration is currently active, this function must
+     * return BAD_CONFIG. It is the responsibility of the client to call
+     * setActiveConfig with a valid configuration before attempting to present
+     * anything on the display.
+     *
+     * @param display is the display to which the active config is queried.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_CONFIG when no configuration is currently active.
+     * @return config is the currently active display configuration.
+     */
+    getActiveConfig(Display display) generates (Error error, Config config);
+
+    /*
+     * Retrieves the layers for which the device requires a different
+     * composition type than had been set prior to the last call to
+     * validateDisplay. The client will either update its state with these
+     * types and call acceptDisplayChanges, or will set new types and attempt
+     * to validate the display again.
+     *
+     * The number of changed layers must be the same as the value returned in
+     * numTypes from the last call to validateDisplay.
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         NOT_VALIDATED when validateDisplay has not been called.
+     * @return layers is an array of layer handles.
+     * @return types is an array of composition types, each corresponding to
+     *         an element of layers.
+     */
+    getChangedCompositionTypes(Display display)
+                    generates (Error error,
+                               vec<Layer> layers,
+                               vec<Composition> types);
+
+    /*
+     * Returns whether a client target with the given properties can be
+     * handled by the device.
+     *
+     * This function must return true for a client target with width and
+     * height equal to the active display configuration dimensions,
+     * PixelFormat::RGBA_8888, and Dataspace::UNKNOWN. It is not required to
+     * return true for any other configuration.
+     *
+     * @param display is the display to query.
+     * @param width is the client target width in pixels.
+     * @param height is the client target height in pixels.
+     * @param format is the client target format.
+     * @param dataspace is the client target dataspace, as described in
+     *        setLayerDataspace.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         UNSUPPORTED when the given configuration is not supported.
+     */
+    getClientTargetSupport(Display display,
+                           uint32_t width,
+                           uint32_t height,
+                           PixelFormat format,
+                           Dataspace dataspace)
+                generates (Error error);
+
+    /*
+     * Returns the color modes supported on this display.
+     *
+     * All devices must support at least ColorMode::NATIVE.
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return modes is an array of color modes.
+     */
+    getColorModes(Display display)
+       generates (Error error,
+                  vec<ColorMode> modes);
+
+    /*
+     * Returns a display attribute value for a particular display
+     * configuration.
+     *
+     * @param display is the display to query.
+     * @param config is the display configuration for which to return
+     *        attribute values.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_CONFIG when config does not name a valid configuration for
+     *                    this display.
+     *         BAD_PARAMETER when attribute is unrecognized.
+     *         UNSUPPORTED when attribute cannot be queried for the config.
+     * @return value is the value of the attribute.
+     */
+    getDisplayAttribute(Display display,
+                        Config config,
+                        Attribute attribute)
+             generates (Error error,
+                        int32_t value);
+
+    /*
+     * Returns handles for all of the valid display configurations on this
+     * display.
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return configs is an array of configuration handles.
+     */
+    getDisplayConfigs(Display display)
+           generates (Error error,
+                      vec<Config> configs);
+
+    /*
+     * Returns a human-readable version of the display's name.
+     *
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return name is the name of the display.
+     */
+    getDisplayName(Display display) generates (Error error, string name);
+
+    /*
+     * Returns the display requests and the layer requests required for the
+     * last validated configuration.
+     *
+     * Display requests provide information about how the client should handle
+     * the client target. Layer requests provide information about how the
+     * client should handle an individual layer.
+     *
+     * The number of layer requests must be equal to the value returned in
+     * numRequests from the last call to validateDisplay.
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         NOT_VALIDATED when validateDisplay has not been called.
+     * @return displayRequestMask is the display requests for the current
+     *         validated state.
+     * @return layers is an array of layers which all have at least one
+     *         request.
+     * @return layerRequestMasks is the requests corresponding to each element
+     *         of layers.
+     */
+    getDisplayRequests(Display display)
+            generates (Error error,
+                       uint32_t displayRequestMask,
+                       vec<Layer> layers,
+                       vec<uint32_t> layerRequestMasks);
+
+    /*
+     * Returns whether the given display is a physical or virtual display.
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return type is the type of the display.
+     */
+    getDisplayType(Display display) generates (Error error, DisplayType type);
+
+    /*
+     * Returns whether the given display supports PowerMode::DOZE and
+     * PowerMode::DOZE_SUSPEND. DOZE_SUSPEND may not provide any benefit over
+     * DOZE (see the definition of PowerMode for more information), but if
+     * both DOZE and DOZE_SUSPEND are no different from PowerMode::ON, the
+     * device should not claim support.
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return support is true only when the display supports doze modes.
+     */
+    getDozeSupport(Display display) generates (Error error, bool support);
+
+    /*
+     * Returns the high dynamic range (HDR) capabilities of the given display,
+     * which are invariant with regard to the active configuration.
+     *
+     * Displays which are not HDR-capable must return no types.
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return types is an array of HDR types, may have 0 elements if the
+     *         display is not HDR-capable.
+     * @return maxLuminance is the desired content maximum luminance for this
+     *         display in cd/m^2.
+     * @return maxAverageLuminance - the desired content maximum frame-average
+     *         luminance for this display in cd/m^2.
+     * @return minLuminance is the desired content minimum luminance for this
+     *         display in cd/m^2.
+     */
+    getHdrCapabilities(Display display)
+            generates (Error error,
+                       vec<Hdr> types,
+                       float maxLuminance,
+                       float maxAverageLuminance,
+                       float minLuminance);
+
+    /*
+     * Retrieves the release fences for device layers on this display which
+     * will receive new buffer contents this frame.
+     *
+     * A release fence is a file descriptor referring to a sync fence object
+     * which will be signaled after the device has finished reading from the
+     * buffer presented in the prior frame. This indicates that it is safe to
+     * start writing to the buffer again. If a given layer's fence is not
+     * returned from this function, it will be assumed that the buffer
+     * presented on the previous frame is ready to be written.
+     *
+     * The fences returned by this function should be unique for each layer
+     * (even if they point to the same underlying sync object).
+     *
+     * @param display is the display to query.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return layers is an array of layer handles.
+     * @return fences is handle that contains an array of sync fence file
+     *         descriptors as described above, each corresponding to an
+     *         element of layers.
+     */
+    getReleaseFences(Display display)
+          generates (Error error,
+                     vec<Layer> layers,
+                     handle releaseFences);
+
+    /*
+     * Presents the current display contents on the screen (or in the case of
+     * virtual displays, into the output buffer).
+     *
+     * Prior to calling this function, the display must be successfully
+     * validated with validateDisplay. Note that setLayerBuffer and
+     * setLayerSurfaceDamage specifically do not count as layer state, so if
+     * there are no other changes to the layer state (or to the buffer's
+     * properties as described in setLayerBuffer), then it is safe to call
+     * this function without first validating the display.
+     *
+     * If this call succeeds, presentFence will be populated with a file
+     * descriptor referring to a present sync fence object. For physical
+     * displays, this fence will be signaled at the vsync when the result of
+     * composition of this frame starts to appear (for video-mode panels) or
+     * starts to transfer to panel memory (for command-mode panels). For
+     * virtual displays, this fence will be signaled when writes to the output
+     * buffer have completed and it is safe to read from it.
+     *
+     * @param display is the display to present.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         NO_RESOURCES when no valid output buffer has been set for a
+     *                      virtual display.
+     *         NOT_VALIDATED when validateDisplay has not successfully been
+     *                       called for this display.
+     * @return presentFence is a sync fence file descriptor as described
+     *         above.
+     */
+    presentDisplay(Display display)
+        generates (Error error,
+                   handle presentFence);
+
+    /*
+     * Sets the active configuration for this display. Upon returning, the
+     * given display configuration should be active and remain so until either
+     * this function is called again or the display is disconnected.
+     *
+     * @param display is the display to which the active config is set.
+     * @param config is the new display configuration.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_CONFIG when the configuration handle passed in is not valid
+     *                    for this display.
+     */
+    setActiveConfig(Display display, Config config) generates (Error error);
+
+    /*
+     * Sets the buffer handle which will receive the output of client
+     * composition.  Layers marked as Composition::CLIENT will be composited
+     * into this buffer prior to the call to presentDisplay, and layers not
+     * marked as Composition::CLIENT should be composited with this buffer by
+     * the device.
+     *
+     * The buffer handle provided may be empty if no layers are being
+     * composited by the client. This must not result in an error (unless an
+     * invalid display handle is also provided).
+     *
+     * Also provides a file descriptor referring to an acquire sync fence
+     * object, which will be signaled when it is safe to read from the client
+     * target buffer.  If it is already safe to read from this buffer, an
+     * empty handle may be passed instead.
+     *
+     * For more about dataspaces, see setLayerDataspace.
+     *
+     * The damage parameter describes a surface damage region as defined in
+     * the description of setLayerSurfaceDamage.
+     *
+     * Will be called before presentDisplay if any of the layers are marked as
+     * Composition::CLIENT. If no layers are so marked, then it is not
+     * necessary to call this function. It is not necessary to call
+     * validateDisplay after changing the target through this function.
+     *
+     * @param display is the display to which the client target is set.
+     * @param target is the new target buffer.
+     * @param acquireFence is a sync fence file descriptor as described above.
+     * @param dataspace is the dataspace of the buffer, as described in
+     *        setLayerDataspace.
+     * @param damage is the surface damage region.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_PARAMETER when the new target handle was invalid.
+     */
+    setClientTarget(Display display,
+                    handle target,
+                    handle acquireFence,
+                    Dataspace dataspace,
+                    vec<Rect> damage)
+         generates (Error error);
+
+    /*
+     * Sets the color mode of the given display.
+     *
+     * Upon returning from this function, the color mode change must have
+     * fully taken effect.
+     *
+     * All devices must support at least ColorMode::NATIVE, and displays are
+     * assumed to be in this mode upon hotplug.
+     *
+     * @param display is the display to which the color mode is set.
+     * @param mode is the mode to set to.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_PARAMETER when mode is not a valid color mode.
+     *         UNSUPPORTED when mode is not supported on this display.
+     */
+    setColorMode(Display display, ColorMode mode) generates (Error error);
+
+    /*
+     * Sets a color transform which will be applied after composition.
+     *
+     * If hint is not ColorTransform::ARBITRARY, then the device may use the
+     * hint to apply the desired color transform instead of using the color
+     * matrix directly.
+     *
+     * If the device is not capable of either using the hint or the matrix to
+     * apply the desired color transform, it should force all layers to client
+     * composition during validateDisplay.
+     *
+     * If Capability::SKIP_CLIENT_COLOR_TRANSFORM is present, then the client
+     * will never apply the color transform during client composition, even if
+     * all layers are being composed by the client.
+     *
+     * The matrix provided is an affine color transformation of the following
+     * form:
+     *
+     * |r.r r.g r.b 0|
+     * |g.r g.g g.b 0|
+     * |b.r b.g b.b 0|
+     * |Tr  Tg  Tb  1|
+     *
+     * This matrix will be provided in row-major form:
+     *
+     * {r.r, r.g, r.b, 0, g.r, ...}.
+     *
+     * Given a matrix of this form and an input color [R_in, G_in, B_in], the
+     * output color [R_out, G_out, B_out] will be:
+     *
+     * R_out = R_in * r.r + G_in * g.r + B_in * b.r + Tr
+     * G_out = R_in * r.g + G_in * g.g + B_in * b.g + Tg
+     * B_out = R_in * r.b + G_in * g.b + B_in * b.b + Tb
+     *
+     * @param display is the display to which the color transform is set.
+     * @param matrix is a 4x4 transform matrix (16 floats) as described above.
+     * @param hint is a hint value which may be used instead of the given
+     *        matrix unless it is ColorTransform::ARBITRARY.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_PARAMETER when hint is not a valid color transform hint.
+     */
+    setColorTransform(Display display,
+                      vec<float> matrix,
+                      ColorTransform hint)
+           generates (Error error);
+
+    /*
+     * Sets the output buffer for a virtual display. That is, the buffer to
+     * which the composition result will be written.
+     *
+     * Also provides a file descriptor referring to a release sync fence
+     * object, which will be signaled when it is safe to write to the output
+     * buffer. If it is already safe to write to the output buffer, an empty
+     * handle may be passed instead.
+     *
+     * Must be called at least once before presentDisplay, but does not have
+     * any interaction with layer state or display validation.
+     *
+     * @param display is the virtual display to which the output buffer is
+     *        set.
+     * @param buffer is the new output buffer.
+     * @param releaseFence is a sync fence file descriptor as described above.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_PARAMETER when the new output buffer handle was invalid.
+     *         UNSUPPORTED when display does not refer to a virtual display.
+     */
+    setOutputBuffer(Display display,
+                    handle buffer,
+                    handle releaseFence)
+         generates (Error error);
+
+    /*
+     * Sets the power mode of the given display. The transition must be
+     * complete when this function returns. It is valid to call this function
+     * multiple times with the same power mode.
+     *
+     * All displays must support PowerMode::ON and PowerMode::OFF.  Whether a
+     * display supports PowerMode::DOZE or PowerMode::DOZE_SUSPEND may be
+     * queried using getDozeSupport.
+     *
+     * @param display is the display to which the power mode is set.
+     * @param mode is the new power mode.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_PARAMETER when mode was not a valid power mode.
+     *         UNSUPPORTED when mode is not supported on this display.
+     */
+    setPowerMode(Display display, PowerMode mode) generates (Error error);
+
+    /*
+     * Enables or disables the vsync signal for the given display. Virtual
+     * displays never generate vsync callbacks, and any attempt to enable
+     * vsync for a virtual display though this function must succeed and have
+     * no other effect.
+     *
+     * @param display is the display to which the vsync mode is set.
+     * @param enabled indicates whether to enable or disable vsync
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_PARAMETER when enabled was an invalid value.
+     */
+    setVsyncEnabled(Display display, Vsync enabled) generates (Error error);
+
+    /*
+     * Instructs the device to inspect all of the layer state and determine if
+     * there are any composition type changes necessary before presenting the
+     * display. Permitted changes are described in the definition of
+     * Composition above.
+     *
+     * Also returns the number of layer requests required by the given layer
+     * configuration.
+     *
+     * @param display is the display to validate.
+     * @return error is NONE or HAS_CHANGES upon success.
+     *         NONE when no changes are necessary and it is safe to present
+     *              the display using the current layer state.
+     *         HAS_CHANGES when composition type changes are needed.
+     *         Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     * @return numTypes is the number of composition type changes required by
+     *         the device; if greater than 0, the client must either set and
+     *         validate new types, or call acceptDisplayChanges to accept the
+     *         changes returned by getChangedCompositionTypes. It must be the
+     *         same as the number of changes returned by
+     *         getChangedCompositionTypes (see the declaration of that
+     *         function for more information).
+     * @return numRequests is the number of layer requests required by this
+     *         layer configuration. It must be equal to the number of layer
+     *         requests returned by getDisplayRequests (see the declaration of
+     *         that function for more information).
+     */
+    validateDisplay(Display display)
+         generates (Error error,
+                    uint32_t numTypes,
+                    uint32_t numRequests);
+
+    /*
+     * Layer Functions
+     *
+     * These are functions which operate on layers, but which do not modify
+     * state that must be validated before use. See also 'Layer State
+     * Functions' below.
+     */
+
+    /*
+     * Asynchonously sets the position of a cursor layer.
+     *
+     * Prior to validateDisplay, a layer may be marked as Composition::CURSOR.
+     * If validation succeeds (i.e., the device does not request a composition
+     * change for that layer), then once a buffer has been set for the layer
+     * and it has been presented, its position may be set by this function at
+     * any time between presentDisplay and any subsequent validateDisplay
+     * calls for this display.
+     *
+     * Once validateDisplay is called, this function will not be called again
+     * until the validate/present sequence is completed.
+     *
+     * May be called from any thread so long as it is not interleaved with the
+     * validate/present sequence as described above.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the position is set.
+     * @param x is the new x coordinate (in pixels from the left of the
+     *        screen).
+     * @param y is the new y coordinate (in pixels from the top of the
+     *        screen).
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when the layer is invalid or is not currently marked
+     *                   as Composition::CURSOR.
+     *         NOT_VALIDATED when the device is currently in the middle of the
+     *                       validate/present sequence.
+     */
+    setCursorPosition(Display display,
+                      Layer layer,
+                      int32_t x,
+                      int32_t y)
+           generates (Error error);
+
+    /*
+     * Sets the buffer handle to be displayed for this layer. If the buffer
+     * properties set at allocation time (width, height, format, and usage)
+     * have not changed since the previous frame, it is not necessary to call
+     * validateDisplay before calling presentDisplay unless new state needs to
+     * be validated in the interim.
+     *
+     * Also provides a file descriptor referring to an acquire sync fence
+     * object, which will be signaled when it is safe to read from the given
+     * buffer. If it is already safe to read from the buffer, an empty handle
+     * may be passed instead.
+     *
+     * This function must return NONE and have no other effect if called for a
+     * layer with a composition type of Composition::SOLID_COLOR (because it
+     * has no buffer) or Composition::SIDEBAND or Composition::CLIENT (because
+     * synchronization and buffer updates for these layers are handled
+     * elsewhere).
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the buffer is set.
+     * @param buffer is the buffer handle to set.
+     * @param acquireFence is a sync fence file descriptor as described above.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     *         BAD_PARAMETER when the buffer handle passed in was invalid.
+     */
+    setLayerBuffer(Display display,
+                   Layer layer,
+                   handle buffer,
+                   handle acquireFence)
+        generates (Error error);
+
+    /*
+     * Provides the region of the source buffer which has been modified since
+     * the last frame. This region does not need to be validated before
+     * calling presentDisplay.
+     *
+     * Once set through this function, the damage region remains the same
+     * until a subsequent call to this function.
+     *
+     * If damage is non-empty, then it may be assumed that any portion of the
+     * source buffer not covered by one of the rects has not been modified
+     * this frame. If damage is empty, then the whole source buffer must be
+     * treated as if it has been modified.
+     *
+     * If the layer's contents are not modified relative to the prior frame,
+     * damage will contain exactly one empty rect([0, 0, 0, 0]).
+     *
+     * The damage rects are relative to the pre-transformed buffer, and their
+     * origin is the top-left corner. They will not exceed the dimensions of
+     * the latched buffer.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the damage region is set.
+     * @param damage is the new surface damage region.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerSurfaceDamage(Display display,
+                          Layer layer,
+                          vec<Rect> damage)
+               generates (Error error);
+
+    /*
+     * Layer State Functions
+     *
+     * These functions modify the state of a given layer. They do not take
+     * effect until the display configuration is successfully validated with
+     * validateDisplay and the display contents are presented with
+     * presentDisplay.
+     */
+
+    /*
+     * Sets the blend mode of the given layer.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the blend mode is set.
+     * @param mode is the new blend mode.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     *         BAD_PARAMETER when an invalid blend mode was passed in.
+     */
+    setLayerBlendMode(Display display,
+                      Layer layer,
+                      BlendMode mode)
+           generates (Error error);
+
+    /*
+     * Sets the color of the given layer. If the composition type of the layer
+     * is not Composition::SOLID_COLOR, this call must succeed and have no
+     * other effect.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the blend mode is set.
+     * @param color is the new color.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerColor(Display display,
+                  Layer layer,
+                  Color color)
+       generates (Error error);
+
+    /*
+     * Sets the desired composition type of the given layer. During
+     * validateDisplay, the device may request changes to the composition
+     * types of any of the layers as described in the definition of
+     * Composition above.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the blend mode is set.
+     * @param type is the new composition type.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     *         BAD_PARAMETER when an invalid composition type was passed in.
+     *         UNSUPPORTED when a valid composition type was passed in, but it
+     *                     is not supported by this device.
+     */
+    setLayerCompositionType(Display display,
+                            Layer layer,
+                            Composition type)
+                 generates (Error error);
+
+    /*
+     * Sets the dataspace that the current buffer on this layer is in.
+     *
+     * The dataspace provides more information about how to interpret the
+     * buffer contents, such as the encoding standard and color transform.
+     *
+     * See the values of Dataspace for more information.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the dataspace is set.
+     * @param dataspace is the new dataspace.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerDataspace(Display display,
+                      Layer layer,
+                      Dataspace dataspace)
+           generates (Error error);
+
+    /*
+     * Sets the display frame (the portion of the display covered by a layer)
+     * of the given layer. This frame will not exceed the display dimensions.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the frame is set.
+     * @param frame is the new display frame.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerDisplayFrame(Display display,
+                         Layer layer,
+                         Rect frame)
+              generates (Error error);
+
+    /*
+     * Sets an alpha value (a floating point value in the range [0.0, 1.0])
+     * which will be applied to the whole layer. It can be conceptualized as a
+     * preprocessing step which applies the following function:
+     *   if (blendMode == BlendMode::PREMULTIPLIED)
+     *       out.rgb = in.rgb * planeAlpha
+     *   out.a = in.a * planeAlpha
+     *
+     * If the device does not support this operation on a layer which is
+     * marked Composition::DEVICE, it must request a composition type change
+     * to Composition::CLIENT upon the next validateDisplay call.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the plane alpha is set.
+     * @param alpha is the plane alpha value to apply.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerPlaneAlpha(Display display,
+                       Layer layer,
+                       float alpha)
+            generates (Error error);
+
+    /*
+     * Sets the sideband stream for this layer. If the composition type of the
+     * given layer is not Composition::SIDEBAND, this call must succeed and
+     * have no other effect.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the sideband stream is set.
+     * @param stream is the new sideband stream.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     *         BAD_PARAMETER when an invalid sideband stream was passed in.
+     */
+    setLayerSidebandStream(Display display,
+                           Layer layer,
+                           handle stream)
+                generates (Error error);
+
+    /*
+     * Sets the source crop (the portion of the source buffer which will fill
+     * the display frame) of the given layer. This crop rectangle will not
+     * exceed the dimensions of the latched buffer.
+     *
+     * If the device is not capable of supporting a true float source crop
+     * (i.e., it will truncate or round the floats to integers), it should set
+     * this layer to Composition::CLIENT when crop is non-integral for the
+     * most accurate rendering.
+     *
+     * If the device cannot support float source crops, but still wants to
+     * handle the layer, it should use the following code (or similar) to
+     * convert to an integer crop:
+     *   intCrop.left = (int) ceilf(crop.left);
+     *   intCrop.top = (int) ceilf(crop.top);
+     *   intCrop.right = (int) floorf(crop.right);
+     *   intCrop.bottom = (int) floorf(crop.bottom);
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the source crop is set.
+     * @param crop is the new source crop.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerSourceCrop(Display display,
+                       Layer layer,
+                       FRect crop)
+            generates (Error error);
+
+    /*
+     * Sets the transform (rotation/flip) of the given layer.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the transform is set.
+     * @param transform is the new transform.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     *         BAD_PARAMETER when an invalid transform was passed in.
+     */
+    setLayerTransform(Display display,
+                      Layer layer,
+                      Transform transform)
+           generates (Error error);
+
+    /*
+     * Specifies the portion of the layer that is visible, including portions
+     * under translucent areas of other layers. The region is in screen space,
+     * and will not exceed the dimensions of the screen.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the visible region is set.
+     * @param visible is the new visible region, in screen space.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerVisibleRegion(Display display,
+                          Layer layer,
+                          vec<Rect> visible)
+               generates (Error error);
+
+    /*
+     * Sets the desired Z order (height) of the given layer. A layer with a
+     * greater Z value occludes a layer with a lesser Z value.
+     *
+     * @param display is the display on which the layer was created.
+     * @param layer is the layer to which the Z order is set.
+     * @param z is the new Z order.
+     * @return error is NONE upon success. Otherwise,
+     *         BAD_DISPLAY when an invalid display handle was passed in.
+     *         BAD_LAYER when an invalid layer handle was passed in.
+     */
+    setLayerZOrder(Display display,
+                   Layer layer,
+                   uint32_t z)
+        generates (Error error);
+};
diff --git a/graphics/composer/2.1/IComposerCallback.hal b/graphics/composer/2.1/IComposerCallback.hal
new file mode 100644 (file)
index 0000000..a8ca168
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * 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 android.hardware.graphics.composer@2.1;
+
+interface IComposerCallback {
+    enum Connection : int32_t {
+        INVALID = 0,
+
+        /* The display has been connected */
+        CONNECTED = 1,
+        /* The display has been disconnected */
+        DISCONNECTED = 2,
+    };
+
+    /*
+     * Notifies the client that the given display has either been connected or
+     * disconnected. Every active display (even a built-in physical display)
+     * must trigger at least one hotplug notification, even if it only occurs
+     * immediately after callback registration.
+     *
+     * Displays which have been connected are assumed to be in PowerMode::OFF,
+     * and the onVsync callback should not be called for a display until vsync
+     * has been enabled with setVsyncEnabled.
+     *
+     * The client may call back into the device while the callback is in
+     * progress. The device must serialize calls to this callback such that
+     * only one thread is calling it at a time.
+     *
+     * @param display is the display that triggers the hotplug event.
+     * @param connected indicates whether the display is connected or
+     *        disconnected.
+     */
+    onHotplug(Display display, Connection connected);
+
+    /*
+     * Notifies the client to trigger a screen refresh. This forces all layer
+     * state for this display to be resent, and the display to be validated
+     * and presented, even if there have been no changes.
+
+     * This refresh will occur some time after the callback is initiated, but
+     * not necessarily before it returns.  It is safe to trigger this callback
+     * from other functions which call into the device.
+     *
+     * @param display is the display to refresh.
+     */
+    oneway onRefresh(Display display);
+
+    /*
+     * Notifies the client that a vsync event has occurred. This callback must
+     * only be triggered when vsync is enabled for this display (through
+     * setVsyncEnabled).
+     *
+     * @param display is the display which has received a vsync event
+     * @param timestamp is the CLOCK_MONOTONIC time at which the vsync event
+     *        occurred, in nanoseconds.
+     */
+    oneway onVsync(Display display, int64_t timestamp);
+};
diff --git a/graphics/composer/2.1/default/Android.bp b/graphics/composer/2.1/default/Android.bp
new file mode 100644 (file)
index 0000000..6936347
--- /dev/null
@@ -0,0 +1,37 @@
+cc_library_shared {
+    name: "android.hardware.graphics.composer@2.1-impl",
+    relative_install_path: "hw",
+    srcs: ["Hwc.cpp"],
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.composer@2.1",
+        "libbase",
+        "libcutils",
+        "libhardware",
+        "libhidl",
+        "libhwbinder",
+        "liblog",
+        "libutils",
+    ],
+}
+
+cc_binary {
+    name: "android.hardware.graphics.composer@2.1-service",
+    relative_install_path: "hw",
+    srcs: ["service.cpp", "Hwc.cpp"],
+    cppflags: ["-DBINDERIZED"],
+    init_rc: ["android.hardware.graphics.composer@2.1-service.rc"],
+
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.composer@2.1",
+        "libbase",
+        "libbinder",
+        "libcutils",
+        "libhardware",
+        "libhidl",
+        "libhwbinder",
+        "liblog",
+        "libutils",
+    ],
+}
diff --git a/graphics/composer/2.1/default/Hwc.cpp b/graphics/composer/2.1/default/Hwc.cpp
new file mode 100644 (file)
index 0000000..d45a955
--- /dev/null
@@ -0,0 +1,1300 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "HwcPassthrough"
+
+#include <mutex>
+#include <type_traits>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include <hardware/gralloc.h>
+#include <hardware/gralloc1.h>
+#include <hardware/hwcomposer2.h>
+#include <log/log.h>
+
+#include "Hwc.h"
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace composer {
+namespace V2_1 {
+namespace implementation {
+
+using android::hardware::graphics::allocator::V2_0::PixelFormat;
+
+namespace {
+
+class HandleImporter {
+public:
+    HandleImporter() : mInitialized(false) {}
+
+    bool initialize()
+    {
+        // allow only one client
+        if (mInitialized) {
+            return false;
+        }
+
+        if (!openGralloc()) {
+            return false;
+        }
+
+        mInitialized = true;
+        return true;
+    }
+
+    void cleanup()
+    {
+        if (!mInitialized) {
+            return;
+        }
+
+        closeGralloc();
+        mInitialized = false;
+    }
+
+    // In IComposer, any buffer_handle_t is owned by the caller and we need to
+    // make a clone for hwcomposer2.  We also need to translate empty handle
+    // to nullptr.  This function does that, in-place.
+    bool importBuffer(buffer_handle_t& handle)
+    {
+        if (!handle->numFds && !handle->numInts) {
+            handle = nullptr;
+            return true;
+        }
+
+        buffer_handle_t clone = cloneBuffer(handle);
+        if (!clone) {
+            return false;
+        }
+
+        handle = clone;
+        return true;
+    }
+
+    void freeBuffer(buffer_handle_t handle)
+    {
+        if (!handle) {
+            return;
+        }
+
+        releaseBuffer(handle);
+    }
+
+    bool importFence(const native_handle_t* handle, int& fd)
+    {
+        if (handle->numFds == 0) {
+            fd = -1;
+        } else if (handle->numFds == 1) {
+            fd = dup(handle->data[0]);
+            if (fd < 0) {
+                ALOGE("failed to dup fence fd %d", handle->data[0]);
+                return false;
+            }
+        } else {
+            ALOGE("invalid fence handle with %d file descriptors",
+                    handle->numFds);
+            return false;
+        }
+
+        return true;
+    }
+
+    void closeFence(int fd)
+    {
+        if (fd >= 0) {
+            close(fd);
+        }
+    }
+
+private:
+    bool mInitialized;
+
+    // Some existing gralloc drivers do not support retaining more than once,
+    // when we are in passthrough mode.
+#ifdef BINDERIZED
+    bool openGralloc()
+    {
+        const hw_module_t* module;
+        int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+        if (err) {
+            ALOGE("failed to get gralloc module");
+            return false;
+        }
+
+        uint8_t major = (module->module_api_version >> 8) & 0xff;
+        if (major > 1) {
+            ALOGE("unknown gralloc module major version %d", major);
+            return false;
+        }
+
+        if (major == 1) {
+            err = gralloc1_open(module, &mDevice);
+            if (err) {
+                ALOGE("failed to open gralloc1 device");
+                return false;
+            }
+
+            mRetain = reinterpret_cast<GRALLOC1_PFN_RETAIN>(
+                    mDevice->getFunction(mDevice, GRALLOC1_FUNCTION_RETAIN));
+            mRelease = reinterpret_cast<GRALLOC1_PFN_RELEASE>(
+                    mDevice->getFunction(mDevice, GRALLOC1_FUNCTION_RELEASE));
+            if (!mRetain || !mRelease) {
+                ALOGE("invalid gralloc1 device");
+                gralloc1_close(mDevice);
+                return false;
+            }
+        } else {
+            mModule = reinterpret_cast<const gralloc_module_t*>(module);
+        }
+
+        return true;
+    }
+
+    void closeGralloc()
+    {
+        if (mDevice) {
+            gralloc1_close(mDevice);
+        }
+    }
+
+    buffer_handle_t cloneBuffer(buffer_handle_t handle)
+    {
+        native_handle_t* clone = native_handle_clone(handle);
+        if (!clone) {
+            ALOGE("failed to clone buffer %p", handle);
+            return nullptr;
+        }
+
+        bool err;
+        if (mDevice) {
+            err = (mRetain(mDevice, clone) != GRALLOC1_ERROR_NONE);
+        } else {
+            err = (mModule->registerBuffer(mModule, clone) != 0);
+        }
+
+        if (err) {
+            ALOGE("failed to retain/register buffer %p", clone);
+            native_handle_close(clone);
+            native_handle_delete(clone);
+            return nullptr;
+        }
+
+        return clone;
+    }
+
+    void releaseBuffer(buffer_handle_t handle)
+    {
+        if (mDevice) {
+            mRelease(mDevice, handle);
+        } else {
+            mModule->unregisterBuffer(mModule, handle);
+            native_handle_close(handle);
+            native_handle_delete(const_cast<native_handle_t*>(handle));
+        }
+    }
+
+    // gralloc1
+    gralloc1_device_t* mDevice;
+    GRALLOC1_PFN_RETAIN mRetain;
+    GRALLOC1_PFN_RELEASE mRelease;
+
+    // gralloc0
+    const gralloc_module_t* mModule;
+#else
+    bool openGralloc() { return true; }
+    void closeGralloc() {}
+    buffer_handle_t cloneBuffer(buffer_handle_t handle) { return handle; }
+    void releaseBuffer(buffer_handle_t) {}
+#endif
+};
+
+HandleImporter sHandleImporter;
+
+class BufferClone {
+public:
+    BufferClone() : mHandle(nullptr) {}
+
+    BufferClone(BufferClone&& other)
+    {
+        mHandle = other.mHandle;
+        other.mHandle = nullptr;
+    }
+
+    BufferClone(const BufferClone& other) = delete;
+    BufferClone& operator=(const BufferClone& other) = delete;
+
+    BufferClone& operator=(buffer_handle_t handle)
+    {
+        clear();
+        mHandle = handle;
+        return *this;
+    }
+
+    ~BufferClone()
+    {
+        clear();
+    }
+
+private:
+    void clear()
+    {
+        if (mHandle) {
+            sHandleImporter.freeBuffer(mHandle);
+        }
+    }
+
+    buffer_handle_t mHandle;
+};
+
+} // anonymous namespace
+
+class HwcHal : public IComposer {
+public:
+    HwcHal(const hw_module_t* module);
+    virtual ~HwcHal();
+
+    // IComposer interface
+    Return<void> getCapabilities(getCapabilities_cb hidl_cb) override;
+    Return<void> dumpDebugInfo(dumpDebugInfo_cb hidl_cb) override;
+    Return<void> registerCallback(const sp<IComposerCallback>& callback) override;
+    Return<uint32_t> getMaxVirtualDisplayCount() override;
+    Return<void> createVirtualDisplay(uint32_t width, uint32_t height,
+            PixelFormat formatHint, createVirtualDisplay_cb hidl_cb) override;
+    Return<Error> destroyVirtualDisplay(Display display) override;
+    Return<Error> acceptDisplayChanges(Display display) override;
+    Return<void> createLayer(Display display,
+            createLayer_cb hidl_cb) override;
+    Return<Error> destroyLayer(Display display, Layer layer) override;
+    Return<void> getActiveConfig(Display display,
+            getActiveConfig_cb hidl_cb) override;
+    Return<void> getChangedCompositionTypes(Display display,
+            getChangedCompositionTypes_cb hidl_cb) override;
+    Return<Error> getClientTargetSupport(Display display,
+            uint32_t width, uint32_t height,
+            PixelFormat format, Dataspace dataspace) override;
+    Return<void> getColorModes(Display display,
+            getColorModes_cb hidl_cb) override;
+    Return<void> getDisplayAttribute(Display display,
+            Config config, Attribute attribute,
+            getDisplayAttribute_cb hidl_cb) override;
+    Return<void> getDisplayConfigs(Display display,
+            getDisplayConfigs_cb hidl_cb) override;
+    Return<void> getDisplayName(Display display,
+            getDisplayName_cb hidl_cb) override;
+    Return<void> getDisplayRequests(Display display,
+            getDisplayRequests_cb hidl_cb) override;
+    Return<void> getDisplayType(Display display,
+            getDisplayType_cb hidl_cb) override;
+    Return<void> getDozeSupport(Display display,
+            getDozeSupport_cb hidl_cb) override;
+    Return<void> getHdrCapabilities(Display display,
+            getHdrCapabilities_cb hidl_cb) override;
+    Return<void> getReleaseFences(Display display,
+            getReleaseFences_cb hidl_cb) override;
+    Return<void> presentDisplay(Display display,
+            presentDisplay_cb hidl_cb) override;
+    Return<Error> setActiveConfig(Display display, Config config) override;
+    Return<Error> setClientTarget(Display display,
+            const native_handle_t* target,
+            const native_handle_t* acquireFence,
+            Dataspace dataspace, const hidl_vec<Rect>& damage) override;
+    Return<Error> setColorMode(Display display, ColorMode mode) override;
+    Return<Error> setColorTransform(Display display,
+            const hidl_vec<float>& matrix, ColorTransform hint) override;
+    Return<Error> setOutputBuffer(Display display,
+            const native_handle_t* buffer,
+            const native_handle_t* releaseFence) override;
+    Return<Error> setPowerMode(Display display, PowerMode mode) override;
+    Return<Error> setVsyncEnabled(Display display, Vsync enabled) override;
+    Return<void> validateDisplay(Display display,
+            validateDisplay_cb hidl_cb) override;
+    Return<Error> setCursorPosition(Display display,
+            Layer layer, int32_t x, int32_t y) override;
+    Return<Error> setLayerBuffer(Display display,
+            Layer layer, const native_handle_t* buffer,
+            const native_handle_t* acquireFence) override;
+    Return<Error> setLayerSurfaceDamage(Display display,
+            Layer layer, const hidl_vec<Rect>& damage) override;
+    Return<Error> setLayerBlendMode(Display display,
+            Layer layer, BlendMode mode) override;
+    Return<Error> setLayerColor(Display display,
+            Layer layer, const Color& color) override;
+    Return<Error> setLayerCompositionType(Display display,
+            Layer layer, Composition type) override;
+    Return<Error> setLayerDataspace(Display display,
+            Layer layer, Dataspace dataspace) override;
+    Return<Error> setLayerDisplayFrame(Display display,
+            Layer layer, const Rect& frame) override;
+    Return<Error> setLayerPlaneAlpha(Display display,
+            Layer layer, float alpha) override;
+    Return<Error> setLayerSidebandStream(Display display,
+            Layer layer, const native_handle_t* stream) override;
+    Return<Error> setLayerSourceCrop(Display display,
+            Layer layer, const FRect& crop) override;
+    Return<Error> setLayerTransform(Display display,
+            Layer layer, Transform transform) override;
+    Return<Error> setLayerVisibleRegion(Display display,
+            Layer layer, const hidl_vec<Rect>& visible) override;
+    Return<Error> setLayerZOrder(Display display,
+            Layer layer, uint32_t z) override;
+
+private:
+    void initCapabilities();
+
+    template<typename T>
+    void initDispatch(T& func, hwc2_function_descriptor_t desc);
+    void initDispatch();
+
+    bool hasCapability(Capability capability) const;
+
+    static void hotplugHook(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int32_t connected);
+    static void refreshHook(hwc2_callback_data_t callbackData,
+        hwc2_display_t display);
+    static void vsyncHook(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int64_t timestamp);
+
+    hwc2_device_t* mDevice;
+
+    std::unordered_set<Capability> mCapabilities;
+
+    struct {
+        HWC2_PFN_ACCEPT_DISPLAY_CHANGES acceptDisplayChanges;
+        HWC2_PFN_CREATE_LAYER createLayer;
+        HWC2_PFN_CREATE_VIRTUAL_DISPLAY createVirtualDisplay;
+        HWC2_PFN_DESTROY_LAYER destroyLayer;
+        HWC2_PFN_DESTROY_VIRTUAL_DISPLAY destroyVirtualDisplay;
+        HWC2_PFN_DUMP dump;
+        HWC2_PFN_GET_ACTIVE_CONFIG getActiveConfig;
+        HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES getChangedCompositionTypes;
+        HWC2_PFN_GET_CLIENT_TARGET_SUPPORT getClientTargetSupport;
+        HWC2_PFN_GET_COLOR_MODES getColorModes;
+        HWC2_PFN_GET_DISPLAY_ATTRIBUTE getDisplayAttribute;
+        HWC2_PFN_GET_DISPLAY_CONFIGS getDisplayConfigs;
+        HWC2_PFN_GET_DISPLAY_NAME getDisplayName;
+        HWC2_PFN_GET_DISPLAY_REQUESTS getDisplayRequests;
+        HWC2_PFN_GET_DISPLAY_TYPE getDisplayType;
+        HWC2_PFN_GET_DOZE_SUPPORT getDozeSupport;
+        HWC2_PFN_GET_HDR_CAPABILITIES getHdrCapabilities;
+        HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT getMaxVirtualDisplayCount;
+        HWC2_PFN_GET_RELEASE_FENCES getReleaseFences;
+        HWC2_PFN_PRESENT_DISPLAY presentDisplay;
+        HWC2_PFN_REGISTER_CALLBACK registerCallback;
+        HWC2_PFN_SET_ACTIVE_CONFIG setActiveConfig;
+        HWC2_PFN_SET_CLIENT_TARGET setClientTarget;
+        HWC2_PFN_SET_COLOR_MODE setColorMode;
+        HWC2_PFN_SET_COLOR_TRANSFORM setColorTransform;
+        HWC2_PFN_SET_CURSOR_POSITION setCursorPosition;
+        HWC2_PFN_SET_LAYER_BLEND_MODE setLayerBlendMode;
+        HWC2_PFN_SET_LAYER_BUFFER setLayerBuffer;
+        HWC2_PFN_SET_LAYER_COLOR setLayerColor;
+        HWC2_PFN_SET_LAYER_COMPOSITION_TYPE setLayerCompositionType;
+        HWC2_PFN_SET_LAYER_DATASPACE setLayerDataspace;
+        HWC2_PFN_SET_LAYER_DISPLAY_FRAME setLayerDisplayFrame;
+        HWC2_PFN_SET_LAYER_PLANE_ALPHA setLayerPlaneAlpha;
+        HWC2_PFN_SET_LAYER_SIDEBAND_STREAM setLayerSidebandStream;
+        HWC2_PFN_SET_LAYER_SOURCE_CROP setLayerSourceCrop;
+        HWC2_PFN_SET_LAYER_SURFACE_DAMAGE setLayerSurfaceDamage;
+        HWC2_PFN_SET_LAYER_TRANSFORM setLayerTransform;
+        HWC2_PFN_SET_LAYER_VISIBLE_REGION setLayerVisibleRegion;
+        HWC2_PFN_SET_LAYER_Z_ORDER setLayerZOrder;
+        HWC2_PFN_SET_OUTPUT_BUFFER setOutputBuffer;
+        HWC2_PFN_SET_POWER_MODE setPowerMode;
+        HWC2_PFN_SET_VSYNC_ENABLED setVsyncEnabled;
+        HWC2_PFN_VALIDATE_DISPLAY validateDisplay;
+    } mDispatch;
+
+    // cloned buffers for a display
+    struct DisplayBuffers {
+        BufferClone ClientTarget;
+        BufferClone OutputBuffer;
+
+        std::unordered_map<Layer, BufferClone> LayerBuffers;
+        std::unordered_map<Layer, BufferClone> LayerSidebandStreams;
+    };
+
+    std::mutex mCallbackMutex;
+    sp<IComposerCallback> mCallback;
+
+    std::mutex mDisplayMutex;
+    std::unordered_map<Display, DisplayBuffers> mDisplays;
+};
+
+HwcHal::HwcHal(const hw_module_t* module)
+    : mDevice(nullptr), mDispatch()
+{
+    if (!sHandleImporter.initialize()) {
+        LOG_ALWAYS_FATAL("failed to initialize handle importer");
+    }
+
+    int status = hwc2_open(module, &mDevice);
+    if (status) {
+        LOG_ALWAYS_FATAL("failed to open hwcomposer2 device: %s",
+                strerror(-status));
+    }
+
+    initCapabilities();
+    initDispatch();
+}
+
+HwcHal::~HwcHal()
+{
+    hwc2_close(mDevice);
+    mDisplays.clear();
+    sHandleImporter.cleanup();
+}
+
+void HwcHal::initCapabilities()
+{
+    uint32_t count = 0;
+    mDevice->getCapabilities(mDevice, &count, nullptr);
+
+    std::vector<Capability> caps(count);
+    mDevice->getCapabilities(mDevice, &count, reinterpret_cast<
+              std::underlying_type<Capability>::type*>(caps.data()));
+    caps.resize(count);
+
+    mCapabilities.insert(caps.cbegin(), caps.cend());
+}
+
+template<typename T>
+void HwcHal::initDispatch(T& func, hwc2_function_descriptor_t desc)
+{
+    auto pfn = mDevice->getFunction(mDevice, desc);
+    if (!pfn) {
+        LOG_ALWAYS_FATAL("failed to get hwcomposer2 function %d", desc);
+    }
+
+    func = reinterpret_cast<T>(pfn);
+}
+
+void HwcHal::initDispatch()
+{
+    initDispatch(mDispatch.acceptDisplayChanges,
+            HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES);
+    initDispatch(mDispatch.createLayer, HWC2_FUNCTION_CREATE_LAYER);
+    initDispatch(mDispatch.createVirtualDisplay,
+            HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY);
+    initDispatch(mDispatch.destroyLayer, HWC2_FUNCTION_DESTROY_LAYER);
+    initDispatch(mDispatch.destroyVirtualDisplay,
+            HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY);
+    initDispatch(mDispatch.dump, HWC2_FUNCTION_DUMP);
+    initDispatch(mDispatch.getActiveConfig, HWC2_FUNCTION_GET_ACTIVE_CONFIG);
+    initDispatch(mDispatch.getChangedCompositionTypes,
+            HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES);
+    initDispatch(mDispatch.getClientTargetSupport,
+            HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT);
+    initDispatch(mDispatch.getColorModes, HWC2_FUNCTION_GET_COLOR_MODES);
+    initDispatch(mDispatch.getDisplayAttribute,
+            HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE);
+    initDispatch(mDispatch.getDisplayConfigs,
+            HWC2_FUNCTION_GET_DISPLAY_CONFIGS);
+    initDispatch(mDispatch.getDisplayName, HWC2_FUNCTION_GET_DISPLAY_NAME);
+    initDispatch(mDispatch.getDisplayRequests,
+            HWC2_FUNCTION_GET_DISPLAY_REQUESTS);
+    initDispatch(mDispatch.getDisplayType, HWC2_FUNCTION_GET_DISPLAY_TYPE);
+    initDispatch(mDispatch.getDozeSupport, HWC2_FUNCTION_GET_DOZE_SUPPORT);
+    initDispatch(mDispatch.getHdrCapabilities,
+            HWC2_FUNCTION_GET_HDR_CAPABILITIES);
+    initDispatch(mDispatch.getMaxVirtualDisplayCount,
+            HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT);
+    initDispatch(mDispatch.getReleaseFences,
+            HWC2_FUNCTION_GET_RELEASE_FENCES);
+    initDispatch(mDispatch.presentDisplay, HWC2_FUNCTION_PRESENT_DISPLAY);
+    initDispatch(mDispatch.registerCallback, HWC2_FUNCTION_REGISTER_CALLBACK);
+    initDispatch(mDispatch.setActiveConfig, HWC2_FUNCTION_SET_ACTIVE_CONFIG);
+    initDispatch(mDispatch.setClientTarget, HWC2_FUNCTION_SET_CLIENT_TARGET);
+    initDispatch(mDispatch.setColorMode, HWC2_FUNCTION_SET_COLOR_MODE);
+    initDispatch(mDispatch.setColorTransform,
+            HWC2_FUNCTION_SET_COLOR_TRANSFORM);
+    initDispatch(mDispatch.setCursorPosition,
+            HWC2_FUNCTION_SET_CURSOR_POSITION);
+    initDispatch(mDispatch.setLayerBlendMode,
+            HWC2_FUNCTION_SET_LAYER_BLEND_MODE);
+    initDispatch(mDispatch.setLayerBuffer, HWC2_FUNCTION_SET_LAYER_BUFFER);
+    initDispatch(mDispatch.setLayerColor, HWC2_FUNCTION_SET_LAYER_COLOR);
+    initDispatch(mDispatch.setLayerCompositionType,
+            HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE);
+    initDispatch(mDispatch.setLayerDataspace,
+            HWC2_FUNCTION_SET_LAYER_DATASPACE);
+    initDispatch(mDispatch.setLayerDisplayFrame,
+            HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME);
+    initDispatch(mDispatch.setLayerPlaneAlpha,
+            HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA);
+
+    if (hasCapability(Capability::SIDEBAND_STREAM)) {
+        initDispatch(mDispatch.setLayerSidebandStream,
+                HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM);
+    }
+
+    initDispatch(mDispatch.setLayerSourceCrop,
+            HWC2_FUNCTION_SET_LAYER_SOURCE_CROP);
+    initDispatch(mDispatch.setLayerSurfaceDamage,
+            HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE);
+    initDispatch(mDispatch.setLayerTransform,
+            HWC2_FUNCTION_SET_LAYER_TRANSFORM);
+    initDispatch(mDispatch.setLayerVisibleRegion,
+            HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION);
+    initDispatch(mDispatch.setLayerZOrder, HWC2_FUNCTION_SET_LAYER_Z_ORDER);
+    initDispatch(mDispatch.setOutputBuffer, HWC2_FUNCTION_SET_OUTPUT_BUFFER);
+    initDispatch(mDispatch.setPowerMode, HWC2_FUNCTION_SET_POWER_MODE);
+    initDispatch(mDispatch.setVsyncEnabled, HWC2_FUNCTION_SET_VSYNC_ENABLED);
+    initDispatch(mDispatch.validateDisplay, HWC2_FUNCTION_VALIDATE_DISPLAY);
+}
+
+bool HwcHal::hasCapability(Capability capability) const
+{
+    return (mCapabilities.count(capability) > 0);
+}
+
+Return<void> HwcHal::getCapabilities(getCapabilities_cb hidl_cb)
+{
+    std::vector<Capability> caps(
+            mCapabilities.cbegin(), mCapabilities.cend());
+
+    hidl_vec<Capability> caps_reply;
+    caps_reply.setToExternal(caps.data(), caps.size());
+    hidl_cb(caps_reply);
+
+    return Void();
+}
+
+Return<void> HwcHal::dumpDebugInfo(dumpDebugInfo_cb hidl_cb)
+{
+    uint32_t len;
+    mDispatch.dump(mDevice, &len, nullptr);
+
+    std::vector<char> buf(len + 1);
+    mDispatch.dump(mDevice, &len, buf.data());
+    buf.resize(len + 1);
+    buf[len] = '\0';
+
+    hidl_string buf_reply;
+    buf_reply.setToExternal(buf.data(), len);
+    hidl_cb(buf_reply);
+
+    return Void();
+}
+
+void HwcHal::hotplugHook(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int32_t connected)
+{
+    auto hal = reinterpret_cast<HwcHal*>(callbackData);
+
+    {
+        std::lock_guard<std::mutex> lock(hal->mDisplayMutex);
+
+        if (connected == HWC2_CONNECTION_CONNECTED) {
+            hal->mDisplays.emplace(display, DisplayBuffers());
+        } else if (connected == HWC2_CONNECTION_DISCONNECTED) {
+            hal->mDisplays.erase(display);
+        }
+    }
+
+    hal->mCallback->onHotplug(display,
+            static_cast<IComposerCallback::Connection>(connected));
+}
+
+void HwcHal::refreshHook(hwc2_callback_data_t callbackData,
+        hwc2_display_t display)
+{
+    auto hal = reinterpret_cast<HwcHal*>(callbackData);
+    hal->mCallback->onRefresh(display);
+}
+
+void HwcHal::vsyncHook(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int64_t timestamp)
+{
+    auto hal = reinterpret_cast<HwcHal*>(callbackData);
+    hal->mCallback->onVsync(display, timestamp);
+}
+
+Return<void> HwcHal::registerCallback(const sp<IComposerCallback>& callback)
+{
+    std::lock_guard<std::mutex> lock(mCallbackMutex);
+
+    mCallback = callback;
+
+    mDispatch.registerCallback(mDevice, HWC2_CALLBACK_HOTPLUG, this,
+            reinterpret_cast<hwc2_function_pointer_t>(hotplugHook));
+    mDispatch.registerCallback(mDevice, HWC2_CALLBACK_REFRESH, this,
+            reinterpret_cast<hwc2_function_pointer_t>(refreshHook));
+    mDispatch.registerCallback(mDevice, HWC2_CALLBACK_VSYNC, this,
+            reinterpret_cast<hwc2_function_pointer_t>(vsyncHook));
+
+    return Void();
+}
+
+Return<uint32_t> HwcHal::getMaxVirtualDisplayCount()
+{
+    return mDispatch.getMaxVirtualDisplayCount(mDevice);
+}
+
+Return<void> HwcHal::createVirtualDisplay(uint32_t width, uint32_t height,
+        PixelFormat formatHint, createVirtualDisplay_cb hidl_cb)
+{
+    int32_t format = static_cast<int32_t>(formatHint);
+    hwc2_display_t display;
+    auto error = mDispatch.createVirtualDisplay(mDevice, width, height,
+            &format, &display);
+    if (error == HWC2_ERROR_NONE) {
+        std::lock_guard<std::mutex> lock(mDisplayMutex);
+
+        mDisplays.emplace(display, DisplayBuffers());
+    }
+
+    hidl_cb(static_cast<Error>(error), display,
+            static_cast<PixelFormat>(format));
+
+    return Void();
+}
+
+Return<Error> HwcHal::destroyVirtualDisplay(Display display)
+{
+    auto error = mDispatch.destroyVirtualDisplay(mDevice, display);
+    if (error == HWC2_ERROR_NONE) {
+        std::lock_guard<std::mutex> lock(mDisplayMutex);
+
+        mDisplays.erase(display);
+    }
+
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::acceptDisplayChanges(Display display)
+{
+    auto error = mDispatch.acceptDisplayChanges(mDevice, display);
+    return static_cast<Error>(error);
+}
+
+Return<void> HwcHal::createLayer(Display display, createLayer_cb hidl_cb)
+{
+    hwc2_layer_t layer;
+    auto error = mDispatch.createLayer(mDevice, display, &layer);
+
+    hidl_cb(static_cast<Error>(error), layer);
+
+    return Void();
+}
+
+Return<Error> HwcHal::destroyLayer(Display display, Layer layer)
+{
+    auto error = mDispatch.destroyLayer(mDevice, display, layer);
+    if (error == HWC2_ERROR_NONE) {
+        std::lock_guard<std::mutex> lock(mDisplayMutex);
+
+        auto dpy = mDisplays.find(display);
+        dpy->second.LayerBuffers.erase(layer);
+        dpy->second.LayerSidebandStreams.erase(layer);
+    }
+
+    return static_cast<Error>(error);
+}
+
+Return<void> HwcHal::getActiveConfig(Display display,
+        getActiveConfig_cb hidl_cb)
+{
+    hwc2_config_t config;
+    auto error = mDispatch.getActiveConfig(mDevice, display, &config);
+
+    hidl_cb(static_cast<Error>(error), config);
+
+    return Void();
+}
+
+Return<void> HwcHal::getChangedCompositionTypes(Display display,
+        getChangedCompositionTypes_cb hidl_cb)
+{
+    uint32_t count = 0;
+    auto error = mDispatch.getChangedCompositionTypes(mDevice, display,
+            &count, nullptr, nullptr);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+
+    std::vector<hwc2_layer_t> layers(count);
+    std::vector<Composition> types(count);
+    error = mDispatch.getChangedCompositionTypes(mDevice, display,
+            &count, layers.data(),
+            reinterpret_cast<std::underlying_type<Composition>::type*>(
+                types.data()));
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+    layers.resize(count);
+    types.resize(count);
+
+    hidl_vec<Layer> layers_reply;
+    layers_reply.setToExternal(layers.data(), layers.size());
+
+    hidl_vec<Composition> types_reply;
+    types_reply.setToExternal(types.data(), types.size());
+
+    hidl_cb(static_cast<Error>(error), layers_reply, types_reply);
+
+    return Void();
+}
+
+Return<Error> HwcHal::getClientTargetSupport(Display display,
+        uint32_t width, uint32_t height,
+        PixelFormat format, Dataspace dataspace)
+{
+    auto error = mDispatch.getClientTargetSupport(mDevice, display,
+            width, height, static_cast<int32_t>(format),
+            static_cast<int32_t>(dataspace));
+    return static_cast<Error>(error);
+}
+
+Return<void> HwcHal::getColorModes(Display display, getColorModes_cb hidl_cb)
+{
+    uint32_t count = 0;
+    auto error = mDispatch.getColorModes(mDevice, display, &count, nullptr);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+
+    std::vector<ColorMode> modes(count);
+    error = mDispatch.getColorModes(mDevice, display, &count,
+            reinterpret_cast<std::underlying_type<ColorMode>::type*>(
+                modes.data()));
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+    modes.resize(count);
+
+    hidl_vec<ColorMode> modes_reply;
+    modes_reply.setToExternal(modes.data(), modes.size());
+    hidl_cb(static_cast<Error>(error), modes_reply);
+
+    return Void();
+}
+
+Return<void> HwcHal::getDisplayAttribute(Display display,
+        Config config, Attribute attribute,
+        getDisplayAttribute_cb hidl_cb)
+{
+    int32_t value;
+    auto error = mDispatch.getDisplayAttribute(mDevice, display, config,
+            static_cast<int32_t>(attribute), &value);
+
+    hidl_cb(static_cast<Error>(error), value);
+
+    return Void();
+}
+
+Return<void> HwcHal::getDisplayConfigs(Display display,
+        getDisplayConfigs_cb hidl_cb)
+{
+    uint32_t count = 0;
+    auto error = mDispatch.getDisplayConfigs(mDevice, display,
+            &count, nullptr);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+
+    std::vector<hwc2_config_t> configs(count);
+    error = mDispatch.getDisplayConfigs(mDevice, display,
+            &count, configs.data());
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+    configs.resize(count);
+
+    hidl_vec<Config> configs_reply;
+    configs_reply.setToExternal(configs.data(), configs.size());
+    hidl_cb(static_cast<Error>(error), configs_reply);
+
+    return Void();
+}
+
+Return<void> HwcHal::getDisplayName(Display display,
+        getDisplayName_cb hidl_cb)
+{
+    uint32_t count = 0;
+    auto error = mDispatch.getDisplayName(mDevice, display, &count, nullptr);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+
+    std::vector<char> name(count + 1);
+    error = mDispatch.getDisplayName(mDevice, display, &count, name.data());
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+    name.resize(count + 1);
+    name[count] = '\0';
+
+    hidl_string name_reply;
+    name_reply.setToExternal(name.data(), count);
+    hidl_cb(static_cast<Error>(error), name_reply);
+
+    return Void();
+}
+
+Return<void> HwcHal::getDisplayRequests(Display display,
+        getDisplayRequests_cb hidl_cb)
+{
+    int32_t display_reqs;
+    uint32_t count = 0;
+    auto error = mDispatch.getDisplayRequests(mDevice, display,
+            &display_reqs, &count, nullptr, nullptr);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+
+    std::vector<hwc2_layer_t> layers(count);
+    std::vector<int32_t> layer_reqs(count);
+    error = mDispatch.getDisplayRequests(mDevice, display,
+            &display_reqs, &count, layers.data(), layer_reqs.data());
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+    layers.resize(count);
+    layer_reqs.resize(count);
+
+    hidl_vec<Layer> layers_reply;
+    layers_reply.setToExternal(layers.data(), layers.size());
+
+    hidl_vec<uint32_t> layer_reqs_reply;
+    layer_reqs_reply.setToExternal(
+            reinterpret_cast<uint32_t*>(layer_reqs.data()),
+            layer_reqs.size());
+
+    hidl_cb(static_cast<Error>(error), display_reqs,
+            layers_reply, layer_reqs_reply);
+
+    return Void();
+}
+
+Return<void> HwcHal::getDisplayType(Display display,
+        getDisplayType_cb hidl_cb)
+{
+    int32_t type;
+    auto error = mDispatch.getDisplayType(mDevice, display, &type);
+
+    hidl_cb(static_cast<Error>(error), static_cast<DisplayType>(type));
+
+    return Void();
+}
+
+Return<void> HwcHal::getDozeSupport(Display display,
+        getDozeSupport_cb hidl_cb)
+{
+    int32_t support;
+    auto error = mDispatch.getDozeSupport(mDevice, display, &support);
+
+    hidl_cb(static_cast<Error>(error), support);
+
+    return Void();
+}
+
+Return<void> HwcHal::getHdrCapabilities(Display display,
+        getHdrCapabilities_cb hidl_cb)
+{
+    float max_lumi, max_avg_lumi, min_lumi;
+    uint32_t count = 0;
+    auto error = mDispatch.getHdrCapabilities(mDevice, display,
+            &count, nullptr, &max_lumi, &max_avg_lumi, &min_lumi);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+
+    std::vector<Hdr> types(count);
+    error = mDispatch.getHdrCapabilities(mDevice, display, &count,
+            reinterpret_cast<std::underlying_type<Hdr>::type*>(types.data()),
+            &max_lumi, &max_avg_lumi, &min_lumi);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+    types.resize(count);
+
+    hidl_vec<Hdr> types_reply;
+    types_reply.setToExternal(types.data(), types.size());
+    hidl_cb(static_cast<Error>(error), types_reply,
+            max_lumi, max_avg_lumi, min_lumi);
+
+    return Void();
+}
+
+Return<void> HwcHal::getReleaseFences(Display display,
+        getReleaseFences_cb hidl_cb)
+{
+    uint32_t count = 0;
+    auto error = mDispatch.getReleaseFences(mDevice, display,
+            &count, nullptr, nullptr);
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+
+    std::vector<hwc2_layer_t> layers(count);
+    std::vector<int32_t> fences(count);
+    error = mDispatch.getReleaseFences(mDevice, display,
+            &count, layers.data(), fences.data());
+    if (error != HWC2_ERROR_NONE) {
+        count = 0;
+    }
+    layers.resize(count);
+    fences.resize(count);
+
+    // filter out layers with release fence -1
+    std::vector<hwc2_layer_t> filtered_layers;
+    std::vector<int> filtered_fences;
+    for (size_t i = 0; i < layers.size(); i++) {
+        if (fences[i] >= 0) {
+            filtered_layers.push_back(layers[i]);
+            filtered_fences.push_back(fences[i]);
+        }
+    }
+
+    hidl_vec<Layer> layers_reply;
+    native_handle_t* fences_reply =
+        native_handle_create(filtered_fences.size(), 0);
+    if (fences_reply) {
+        layers_reply.setToExternal(filtered_layers.data(),
+                filtered_layers.size());
+        memcpy(fences_reply->data, filtered_fences.data(),
+                sizeof(int) * filtered_fences.size());
+
+        hidl_cb(static_cast<Error>(error), layers_reply, fences_reply);
+
+        native_handle_close(fences_reply);
+        native_handle_delete(fences_reply);
+    } else {
+        NATIVE_HANDLE_DECLARE_STORAGE(fences_storage, 0, 0);
+        fences_reply = native_handle_init(fences_storage, 0, 0);
+
+        hidl_cb(Error::NO_RESOURCES, layers_reply, fences_reply);
+
+        for (auto fence : filtered_fences) {
+            close(fence);
+        }
+    }
+
+    return Void();
+}
+
+Return<void> HwcHal::presentDisplay(Display display,
+        presentDisplay_cb hidl_cb)
+{
+    int32_t fence = -1;
+    auto error = mDispatch.presentDisplay(mDevice, display, &fence);
+
+    NATIVE_HANDLE_DECLARE_STORAGE(fence_storage, 1, 0);
+    native_handle_t* fence_reply;
+    if (fence >= 0) {
+        fence_reply = native_handle_init(fence_storage, 1, 0);
+        fence_reply->data[0] = fence;
+    } else {
+        fence_reply = native_handle_init(fence_storage, 0, 0);
+    }
+
+    hidl_cb(static_cast<Error>(error), fence_reply);
+
+    if (fence >= 0) {
+        close(fence);
+    }
+
+    return Void();
+}
+
+Return<Error> HwcHal::setActiveConfig(Display display, Config config)
+{
+    auto error = mDispatch.setActiveConfig(mDevice, display, config);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setClientTarget(Display display,
+        const native_handle_t* target,
+        const native_handle_t* acquireFence,
+        Dataspace dataspace, const hidl_vec<Rect>& damage)
+{
+    if (!sHandleImporter.importBuffer(target)) {
+        return Error::NO_RESOURCES;
+    }
+
+    int32_t fence;
+    if (!sHandleImporter.importFence(acquireFence, fence)) {
+        sHandleImporter.freeBuffer(target);
+        return Error::NO_RESOURCES;
+    }
+
+    hwc_region_t damage_region = { damage.size(),
+        reinterpret_cast<const hwc_rect_t*>(&damage[0]) };
+
+    int32_t error = mDispatch.setClientTarget(mDevice, display,
+            target, fence, static_cast<int32_t>(dataspace),
+            damage_region);
+    if (error == HWC2_ERROR_NONE) {
+        std::lock_guard<std::mutex> lock(mDisplayMutex);
+
+        auto dpy = mDisplays.find(display);
+        dpy->second.ClientTarget = target;
+    } else {
+        sHandleImporter.freeBuffer(target);
+        sHandleImporter.closeFence(fence);
+    }
+
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setColorMode(Display display, ColorMode mode)
+{
+    auto error = mDispatch.setColorMode(mDevice, display,
+            static_cast<int32_t>(mode));
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setColorTransform(Display display,
+        const hidl_vec<float>& matrix, ColorTransform hint)
+{
+    auto error = mDispatch.setColorTransform(mDevice, display,
+            &matrix[0], static_cast<int32_t>(hint));
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setOutputBuffer(Display display,
+        const native_handle_t* buffer,
+        const native_handle_t* releaseFence)
+{
+    if (!sHandleImporter.importBuffer(buffer)) {
+        return Error::NO_RESOURCES;
+    }
+
+    int32_t fence;
+    if (!sHandleImporter.importFence(releaseFence, fence)) {
+        sHandleImporter.freeBuffer(buffer);
+        return Error::NO_RESOURCES;
+    }
+
+    int32_t error = mDispatch.setOutputBuffer(mDevice,
+            display, buffer, fence);
+    if (error == HWC2_ERROR_NONE) {
+        std::lock_guard<std::mutex> lock(mDisplayMutex);
+
+        auto dpy = mDisplays.find(display);
+        dpy->second.OutputBuffer = buffer;
+    } else {
+        sHandleImporter.freeBuffer(buffer);
+    }
+
+    // unlike in setClientTarget, fence is owned by us and is always closed
+    sHandleImporter.closeFence(fence);
+
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setPowerMode(Display display, PowerMode mode)
+{
+    auto error = mDispatch.setPowerMode(mDevice, display,
+            static_cast<int32_t>(mode));
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setVsyncEnabled(Display display,
+        Vsync enabled)
+{
+    auto error = mDispatch.setVsyncEnabled(mDevice, display,
+            static_cast<int32_t>(enabled));
+    return static_cast<Error>(error);
+}
+
+Return<void> HwcHal::validateDisplay(Display display,
+        validateDisplay_cb hidl_cb)
+{
+    uint32_t types_count = 0;
+    uint32_t reqs_count = 0;
+    auto error = mDispatch.validateDisplay(mDevice, display,
+            &types_count, &reqs_count);
+
+    hidl_cb(static_cast<Error>(error), types_count, reqs_count);
+
+    return Void();
+}
+
+Return<Error> HwcHal::setCursorPosition(Display display,
+        Layer layer, int32_t x, int32_t y)
+{
+    auto error = mDispatch.setCursorPosition(mDevice, display, layer, x, y);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerBuffer(Display display,
+        Layer layer, const native_handle_t* buffer,
+        const native_handle_t* acquireFence)
+{
+    if (!sHandleImporter.importBuffer(buffer)) {
+        return Error::NO_RESOURCES;
+    }
+
+    int32_t fence;
+    if (!sHandleImporter.importFence(acquireFence, fence)) {
+        sHandleImporter.freeBuffer(buffer);
+        return Error::NO_RESOURCES;
+    }
+
+    int32_t error = mDispatch.setLayerBuffer(mDevice,
+            display, layer, buffer, fence);
+    if (error == HWC2_ERROR_NONE) {
+        std::lock_guard<std::mutex> lock(mDisplayMutex);
+
+        auto dpy = mDisplays.find(display);
+        dpy->second.LayerBuffers[layer] = buffer;
+    } else {
+        sHandleImporter.freeBuffer(buffer);
+        sHandleImporter.closeFence(fence);
+    }
+
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerSurfaceDamage(Display display,
+        Layer layer, const hidl_vec<Rect>& damage)
+{
+    hwc_region_t damage_region = { damage.size(),
+        reinterpret_cast<const hwc_rect_t*>(&damage[0]) };
+
+    auto error = mDispatch.setLayerSurfaceDamage(mDevice, display, layer,
+            damage_region);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerBlendMode(Display display,
+        Layer layer, BlendMode mode)
+{
+    auto error = mDispatch.setLayerBlendMode(mDevice, display, layer,
+            static_cast<int32_t>(mode));
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerColor(Display display,
+        Layer layer, const Color& color)
+{
+    hwc_color_t hwc_color{color.r, color.g, color.b, color.a};
+    auto error = mDispatch.setLayerColor(mDevice, display, layer, hwc_color);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerCompositionType(Display display,
+        Layer layer, Composition type)
+{
+    auto error = mDispatch.setLayerCompositionType(mDevice, display, layer,
+            static_cast<int32_t>(type));
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerDataspace(Display display,
+        Layer layer, Dataspace dataspace)
+{
+    auto error = mDispatch.setLayerDataspace(mDevice, display, layer,
+            static_cast<int32_t>(dataspace));
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerDisplayFrame(Display display,
+        Layer layer, const Rect& frame)
+{
+    hwc_rect_t hwc_frame{frame.left, frame.top, frame.right, frame.bottom};
+    auto error = mDispatch.setLayerDisplayFrame(mDevice, display, layer,
+            hwc_frame);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerPlaneAlpha(Display display,
+        Layer layer, float alpha)
+{
+    auto error = mDispatch.setLayerPlaneAlpha(mDevice, display, layer, alpha);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerSidebandStream(Display display,
+        Layer layer, const native_handle_t* stream)
+{
+    if (!sHandleImporter.importBuffer(stream)) {
+        return Error::NO_RESOURCES;
+    }
+
+    int32_t error = mDispatch.setLayerSidebandStream(mDevice,
+            display, layer, stream);
+    if (error == HWC2_ERROR_NONE) {
+        std::lock_guard<std::mutex> lock(mDisplayMutex);
+
+        auto dpy = mDisplays.find(display);
+        dpy->second.LayerSidebandStreams[layer] = stream;
+    } else {
+        sHandleImporter.freeBuffer(stream);
+    }
+
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerSourceCrop(Display display,
+        Layer layer, const FRect& crop)
+{
+    hwc_frect_t hwc_crop{crop.left, crop.top, crop.right, crop.bottom};
+    auto error = mDispatch.setLayerSourceCrop(mDevice, display, layer,
+            hwc_crop);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerTransform(Display display,
+        Layer layer, Transform transform)
+{
+    auto error = mDispatch.setLayerTransform(mDevice, display, layer,
+            static_cast<int32_t>(transform));
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerVisibleRegion(Display display,
+        Layer layer, const hidl_vec<Rect>& visible)
+{
+    hwc_region_t visible_region = { visible.size(),
+        reinterpret_cast<const hwc_rect_t*>(&visible[0]) };
+
+    auto error = mDispatch.setLayerVisibleRegion(mDevice, display, layer,
+            visible_region);
+    return static_cast<Error>(error);
+}
+
+Return<Error> HwcHal::setLayerZOrder(Display display,
+        Layer layer, uint32_t z)
+{
+    auto error = mDispatch.setLayerZOrder(mDevice, display, layer, z);
+    return static_cast<Error>(error);
+}
+
+IComposer* HIDL_FETCH_IComposer(const char*)
+{
+    const hw_module_t* module;
+    int err = hw_get_module(HWC_HARDWARE_MODULE_ID, &module);
+    if (err) {
+        ALOGE("failed to get hwcomposer module");
+        return nullptr;
+    }
+
+    return new HwcHal(module);
+}
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace composer
+} // namespace graphics
+} // namespace hardware
+} // namespace android
diff --git a/graphics/composer/2.1/default/Hwc.h b/graphics/composer/2.1/default/Hwc.h
new file mode 100644 (file)
index 0000000..de69417
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 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.
+ */
+
+#ifndef ANDROID_HARDWARE_GRAPHICS_COMPOSER_V2_1_HWC_H
+#define ANDROID_HARDWARE_GRAPHICS_COMPOSER_V2_1_HWC_H
+
+#include <android/hardware/graphics/composer/2.1/IComposer.h>
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace composer {
+namespace V2_1 {
+namespace implementation {
+
+extern "C" IComposer* HIDL_FETCH_IComposer(const char* name);
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace composer
+} // namespace graphics
+} // namespace hardware
+} // namespace android
+
+#endif  // ANDROID_HARDWARE_GRAPHICS_COMPOSER_V2_1_HWC_H
diff --git a/graphics/composer/2.1/default/android.hardware.graphics.composer@2.1-service.rc b/graphics/composer/2.1/default/android.hardware.graphics.composer@2.1-service.rc
new file mode 100644 (file)
index 0000000..fc21d59
--- /dev/null
@@ -0,0 +1,5 @@
+service hwcomposer-2-1 /system/bin/hw/android.hardware.graphics.composer@2.1-service
+    class hal
+    user system
+    group graphics drmrpc readproc
+    onrestart restart surfaceflinger
diff --git a/graphics/composer/2.1/default/service.cpp b/graphics/composer/2.1/default/service.cpp
new file mode 100644 (file)
index 0000000..0384a53
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "HWComposerService"
+
+#include <binder/ProcessState.h>
+#include <hwbinder/IPCThreadState.h>
+#include <hwbinder/ProcessState.h>
+#include <utils/StrongPointer.h>
+#include "Hwc.h"
+
+using android::sp;
+using android::hardware::IPCThreadState;
+using android::hardware::ProcessState;
+using android::hardware::graphics::composer::V2_1::IComposer;
+using android::hardware::graphics::composer::V2_1::implementation::HIDL_FETCH_IComposer;
+
+int main()
+{
+    const char instance[] = "hwcomposer";
+
+    ALOGI("Service is starting.");
+
+    sp<IComposer> service = HIDL_FETCH_IComposer(instance);
+    if (service == nullptr) {
+        ALOGI("getService returned NULL");
+        return -1;
+    }
+
+    LOG_FATAL_IF(service->isRemote(), "Service is REMOTE!");
+
+    service->registerAsService(instance);
+
+    // the conventional HAL might start binder services
+    android::ProcessState::self()->setThreadPoolMaxThreadCount(4);
+    android::ProcessState::self()->startThreadPool();
+
+    ProcessState::self()->setThreadPoolMaxThreadCount(0);
+    ProcessState::self()->startThreadPool();
+    IPCThreadState::self()->joinThreadPool();
+
+    return 0;
+}
diff --git a/graphics/composer/2.1/types.hal b/graphics/composer/2.1/types.hal
new file mode 100644 (file)
index 0000000..3c591b3
--- /dev/null
@@ -0,0 +1,163 @@
+/*
+ * 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 android.hardware.graphics.composer@2.1;
+
+/* Return codes from all functions. */
+enum Error : int32_t {
+    NONE            = 0, /* no error */
+    BAD_CONFIG      = 1, /* invalid Config */
+    BAD_DISPLAY     = 2, /* invalid Display */
+    BAD_LAYER       = 3, /* invalid Layer */
+    BAD_PARAMETER   = 4, /* invalid width, height, etc. */
+    HAS_CHANGES     = 5,
+    NO_RESOURCES    = 6, /* temporary failure due to resource contention */
+    NOT_VALIDATED   = 7, /* validateDisplay has not been called */
+    UNSUPPORTED     = 8, /* permanent failure */
+};
+
+typedef uint32_t Config;
+typedef uint64_t Display;
+typedef uint64_t Layer;
+
+/*
+ * Copied from android_transform_t
+ *
+ * TODO(olv) copy comments over and generate android_transform_t
+ */
+enum Transform : int32_t {
+    FLIP_H    = 0x1,
+    FLIP_V    = 0x2,
+    ROT_90    = 0x4,
+    ROT_180   = 0x3,
+    ROT_270   = 0x7,
+    RESERVED  = 0x8,
+};
+
+/*
+ * Copied from android_color_mode_t
+ *
+ * TODO(olv) copy comments over and generate android_color_mode_t
+ */
+enum ColorMode : int32_t {
+  NATIVE                        = 0,
+  STANDARD_BT601_625            = 1,
+  STANDARD_BT601_625_UNADJUSTED = 2,
+  STANDARD_BT601_525            = 3,
+  STANDARD_BT601_525_UNADJUSTED = 4,
+  STANDARD_BT709                = 5,
+  DCI_P3                        = 6,
+  SRGB                          = 7,
+  ADOBE_RGB                     = 8,
+};
+
+/*
+ * Copied from android_color_transform_t
+ *
+ * TODO(olv) copy comments over and generate android_color_transform_t
+ */
+enum ColorTransform : int32_t {
+    IDENTITY             = 0,
+    ARBITRARY_MATRIX     = 1,
+    VALUE_INVERSE        = 2,
+    GRAYSCALE            = 3,
+    CORRECT_PROTANOPIA   = 4,
+    CORRECT_DEUTERANOPIA = 5,
+    CORRECT_TRITANOPIA   = 6
+};
+
+/*
+ * Copied from android_dataspace_t
+ *
+ * TODO(olv) copy comments over and generate android_dataspace_t
+ */
+enum Dataspace : int32_t {
+    UNKNOWN                            = 0x0,
+    ARBITRARY                          = 0x1,
+
+    STANDARD_SHIFT                     = 16,
+    STANDARD_MASK                      = 63 << STANDARD_SHIFT,
+    STANDARD_UNSPECIFIED               = 0 << STANDARD_SHIFT,
+    STANDARD_BT709                     = 1 << STANDARD_SHIFT,
+    STANDARD_BT601_625                 = 2 << STANDARD_SHIFT,
+    STANDARD_BT601_625_UNADJUSTED      = 3 << STANDARD_SHIFT,
+    STANDARD_BT601_525                 = 4 << STANDARD_SHIFT,
+    STANDARD_BT601_525_UNADJUSTED      = 5 << STANDARD_SHIFT,
+    STANDARD_BT2020                    = 6 << STANDARD_SHIFT,
+    STANDARD_BT2020_CONSTANT_LUMINANCE = 7 << STANDARD_SHIFT,
+    STANDARD_BT470M                    = 8 << STANDARD_SHIFT,
+    STANDARD_FILM                      = 9 << STANDARD_SHIFT,
+
+    TRANSFER_SHIFT                     = 22,
+    TRANSFER_MASK                      = 31 << TRANSFER_SHIFT,
+    TRANSFER_UNSPECIFIED               = 0 << TRANSFER_SHIFT,
+    TRANSFER_LINEAR                    = 1 << TRANSFER_SHIFT,
+    TRANSFER_SRGB                      = 2 << TRANSFER_SHIFT,
+    TRANSFER_SMPTE_170M                = 3 << TRANSFER_SHIFT,
+    TRANSFER_GAMMA2_2                  = 4 << TRANSFER_SHIFT,
+    TRANSFER_GAMMA2_8                  = 5 << TRANSFER_SHIFT,
+    TRANSFER_ST2084                    = 6 << TRANSFER_SHIFT,
+    TRANSFER_HLG                       = 7 << TRANSFER_SHIFT,
+
+    RANGE_SHIFT                        = 27,
+    RANGE_MASK                         = 7 << RANGE_SHIFT,
+    RANGE_UNSPECIFIED                  = 0 << RANGE_SHIFT,
+    RANGE_FULL                         = 1 << RANGE_SHIFT,
+    RANGE_LIMITED                      = 2 << RANGE_SHIFT,
+
+    SRGB_LINEAR                        = 0x200,
+    V0_SRGB_LINEAR                     = STANDARD_BT709 |
+                                         TRANSFER_LINEAR |
+                                         RANGE_FULL,
+
+    SRGB                               = 0x201,
+    V0_SRGB                            = STANDARD_BT709 |
+                                         TRANSFER_SRGB |
+                                         RANGE_FULL,
+
+    JFIF                               = 0x101,
+    V0_JFIF                            = STANDARD_BT601_625 |
+                                         TRANSFER_SMPTE_170M |
+                                         RANGE_FULL,
+
+    BT601_625                          = 0x102,
+    V0_BT601_625                       = STANDARD_BT601_625 |
+                                         TRANSFER_SMPTE_170M |
+                                         RANGE_LIMITED,
+
+    BT601_525                          = 0x103,
+    V0_BT601_525                       = STANDARD_BT601_525 |
+                                         TRANSFER_SMPTE_170M |
+                                         RANGE_LIMITED,
+
+    BT709                              = 0x104,
+    V0_BT709                           = STANDARD_BT709 |
+                                         TRANSFER_SMPTE_170M |
+                                         RANGE_LIMITED,
+
+    DEPTH                              = 0x1000,
+};
+
+/*
+ * Copied from android_hdr_t
+ *
+ * TODO(olv) copy comments over and generate android_hdr_t
+ */
+enum Hdr : int32_t {
+    DOLBY_VISION = 1,
+    HDR10        = 2,
+    HLG          = 3,
+};
diff --git a/graphics/mapper/2.0/Android.bp b/graphics/mapper/2.0/Android.bp
new file mode 100644 (file)
index 0000000..19b1388
--- /dev/null
@@ -0,0 +1,4 @@
+cc_library_static {
+    name: "android.hardware.graphics.mapper@2.0",
+    export_include_dirs: ["include"],
+}
diff --git a/graphics/mapper/2.0/default/Android.bp b/graphics/mapper/2.0/default/Android.bp
new file mode 100644 (file)
index 0000000..b738ae8
--- /dev/null
@@ -0,0 +1,28 @@
+// 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.
+
+cc_library_shared {
+    name: "android.hardware.graphics.mapper.hallib",
+    relative_install_path: "hw",
+    srcs: ["GrallocMapper.cpp"],
+    cppflags: ["-Wall", "-Wextra"],
+    static_libs: ["android.hardware.graphics.mapper@2.0"],
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "libhardware",
+        "libhidl",
+        "libhwbinder",
+        "liblog",
+    ],
+}
diff --git a/graphics/mapper/2.0/default/GrallocMapper.cpp b/graphics/mapper/2.0/default/GrallocMapper.cpp
new file mode 100644 (file)
index 0000000..2af1d2c
--- /dev/null
@@ -0,0 +1,428 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "GrallocMapperPassthrough"
+
+#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
+#include <hardware/gralloc1.h>
+#include <log/log.h>
+
+#include <unordered_set>
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace mapper {
+namespace V2_0 {
+namespace implementation {
+
+using Capability = allocator::V2_0::IAllocator::Capability;
+
+class GrallocDevice : public Device {
+public:
+    GrallocDevice();
+    ~GrallocDevice();
+
+    // IMapper interface
+    Error retain(const native_handle_t* bufferHandle);
+    Error release(const native_handle_t* bufferHandle);
+    Error getDimensions(const native_handle_t* bufferHandle,
+            uint32_t* outWidth, uint32_t* outHeight);
+    Error getFormat(const native_handle_t* bufferHandle,
+            PixelFormat* outFormat);
+    Error getLayerCount(const native_handle_t* bufferHandle,
+            uint32_t* outLayerCount);
+    Error getProducerUsageMask(const native_handle_t* bufferHandle,
+            uint64_t* outUsageMask);
+    Error getConsumerUsageMask(const native_handle_t* bufferHandle,
+            uint64_t* outUsageMask);
+    Error getBackingStore(const native_handle_t* bufferHandle,
+            BackingStore* outStore);
+    Error getStride(const native_handle_t* bufferHandle, uint32_t* outStride);
+    Error getNumFlexPlanes(const native_handle_t* bufferHandle,
+            uint32_t* outNumPlanes);
+    Error lock(const native_handle_t* bufferHandle,
+            uint64_t producerUsageMask, uint64_t consumerUsageMask,
+            const Rect* accessRegion, int32_t acquireFence, void** outData);
+    Error lockFlex(const native_handle_t* bufferHandle,
+            uint64_t producerUsageMask, uint64_t consumerUsageMask,
+            const Rect* accessRegion, int32_t acquireFence,
+            FlexLayout* outFlexLayout);
+    Error unlock(const native_handle_t* bufferHandle,
+            int32_t* outReleaseFence);
+
+private:
+    void initCapabilities();
+
+    void initDispatch();
+    bool hasCapability(Capability capability) const;
+
+    gralloc1_device_t* mDevice;
+
+    std::unordered_set<Capability> mCapabilities;
+
+    struct {
+        GRALLOC1_PFN_RETAIN retain;
+        GRALLOC1_PFN_RELEASE release;
+        GRALLOC1_PFN_GET_DIMENSIONS getDimensions;
+        GRALLOC1_PFN_GET_FORMAT getFormat;
+        GRALLOC1_PFN_GET_LAYER_COUNT getLayerCount;
+        GRALLOC1_PFN_GET_PRODUCER_USAGE getProducerUsage;
+        GRALLOC1_PFN_GET_CONSUMER_USAGE getConsumerUsage;
+        GRALLOC1_PFN_GET_BACKING_STORE getBackingStore;
+        GRALLOC1_PFN_GET_STRIDE getStride;
+        GRALLOC1_PFN_GET_NUM_FLEX_PLANES getNumFlexPlanes;
+        GRALLOC1_PFN_LOCK lock;
+        GRALLOC1_PFN_LOCK_FLEX lockFlex;
+        GRALLOC1_PFN_UNLOCK unlock;
+    } mDispatch;
+};
+
+GrallocDevice::GrallocDevice()
+{
+    const hw_module_t* module;
+    int status = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+    if (status) {
+        LOG_ALWAYS_FATAL("failed to get gralloc module");
+    }
+
+    uint8_t major = (module->module_api_version >> 8) & 0xff;
+    if (major != 1) {
+        LOG_ALWAYS_FATAL("unknown gralloc module major version %d", major);
+    }
+
+    status = gralloc1_open(module, &mDevice);
+    if (status) {
+        LOG_ALWAYS_FATAL("failed to open gralloc1 device");
+    }
+
+    initCapabilities();
+    initDispatch();
+}
+
+GrallocDevice::~GrallocDevice()
+{
+    gralloc1_close(mDevice);
+}
+
+void GrallocDevice::initCapabilities()
+{
+    uint32_t count;
+    mDevice->getCapabilities(mDevice, &count, nullptr);
+
+    std::vector<Capability> caps(count);
+    mDevice->getCapabilities(mDevice, &count, reinterpret_cast<
+              std::underlying_type<Capability>::type*>(caps.data()));
+    caps.resize(count);
+
+    mCapabilities.insert(caps.cbegin(), caps.cend());
+}
+
+void GrallocDevice::initDispatch()
+{
+#define CHECK_FUNC(func, desc) do {                                   \
+    mDispatch.func = reinterpret_cast<decltype(mDispatch.func)>(      \
+        mDevice->getFunction(mDevice, desc));                         \
+    if (!mDispatch.func) {                                            \
+        LOG_ALWAYS_FATAL("failed to get gralloc1 function %d", desc); \
+    }                                                                 \
+} while (0)
+
+    CHECK_FUNC(retain, GRALLOC1_FUNCTION_RETAIN);
+    CHECK_FUNC(release, GRALLOC1_FUNCTION_RELEASE);
+    CHECK_FUNC(getDimensions, GRALLOC1_FUNCTION_GET_DIMENSIONS);
+    CHECK_FUNC(getFormat, GRALLOC1_FUNCTION_GET_FORMAT);
+    if (hasCapability(Capability::LAYERED_BUFFERS)) {
+        CHECK_FUNC(getLayerCount, GRALLOC1_FUNCTION_GET_LAYER_COUNT);
+    }
+    CHECK_FUNC(getProducerUsage, GRALLOC1_FUNCTION_GET_PRODUCER_USAGE);
+    CHECK_FUNC(getConsumerUsage, GRALLOC1_FUNCTION_GET_CONSUMER_USAGE);
+    CHECK_FUNC(getBackingStore, GRALLOC1_FUNCTION_GET_BACKING_STORE);
+    CHECK_FUNC(getStride, GRALLOC1_FUNCTION_GET_STRIDE);
+    CHECK_FUNC(getNumFlexPlanes, GRALLOC1_FUNCTION_GET_NUM_FLEX_PLANES);
+    CHECK_FUNC(lock, GRALLOC1_FUNCTION_LOCK);
+    CHECK_FUNC(lockFlex, GRALLOC1_FUNCTION_LOCK_FLEX);
+    CHECK_FUNC(unlock, GRALLOC1_FUNCTION_UNLOCK);
+
+#undef CHECK_FUNC
+}
+
+bool GrallocDevice::hasCapability(Capability capability) const
+{
+    return (mCapabilities.count(capability) > 0);
+}
+
+Error GrallocDevice::retain(const native_handle_t* bufferHandle)
+{
+    int32_t error = mDispatch.retain(mDevice, bufferHandle);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::release(const native_handle_t* bufferHandle)
+{
+    int32_t error = mDispatch.release(mDevice, bufferHandle);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::getDimensions(const native_handle_t* bufferHandle,
+        uint32_t* outWidth, uint32_t* outHeight)
+{
+    int32_t error = mDispatch.getDimensions(mDevice, bufferHandle,
+            outWidth, outHeight);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::getFormat(const native_handle_t* bufferHandle,
+        PixelFormat* outFormat)
+{
+    int32_t error = mDispatch.getFormat(mDevice, bufferHandle,
+            reinterpret_cast<int32_t*>(outFormat));
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::getLayerCount(const native_handle_t* bufferHandle,
+        uint32_t* outLayerCount)
+{
+    if (hasCapability(Capability::LAYERED_BUFFERS)) {
+        int32_t error = mDispatch.getLayerCount(mDevice, bufferHandle,
+                outLayerCount);
+        return static_cast<Error>(error);
+    } else {
+        *outLayerCount = 1;
+        return Error::NONE;
+    }
+}
+
+Error GrallocDevice::getProducerUsageMask(const native_handle_t* bufferHandle,
+        uint64_t* outUsageMask)
+{
+    int32_t error = mDispatch.getProducerUsage(mDevice, bufferHandle,
+            outUsageMask);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::getConsumerUsageMask(const native_handle_t* bufferHandle,
+        uint64_t* outUsageMask)
+{
+    int32_t error = mDispatch.getConsumerUsage(mDevice, bufferHandle,
+            outUsageMask);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::getBackingStore(const native_handle_t* bufferHandle,
+        BackingStore* outStore)
+{
+    int32_t error = mDispatch.getBackingStore(mDevice, bufferHandle,
+            outStore);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::getStride(const native_handle_t* bufferHandle,
+        uint32_t* outStride)
+{
+    int32_t error = mDispatch.getStride(mDevice, bufferHandle, outStride);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::getNumFlexPlanes(const native_handle_t* bufferHandle,
+        uint32_t* outNumPlanes)
+{
+    int32_t error = mDispatch.getNumFlexPlanes(mDevice, bufferHandle,
+            outNumPlanes);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::lock(const native_handle_t* bufferHandle,
+        uint64_t producerUsageMask, uint64_t consumerUsageMask,
+        const Rect* accessRegion, int32_t acquireFence,
+        void** outData)
+{
+    int32_t error = mDispatch.lock(mDevice, bufferHandle,
+            producerUsageMask, consumerUsageMask,
+            reinterpret_cast<const gralloc1_rect_t*>(accessRegion),
+            outData, acquireFence);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::lockFlex(const native_handle_t* bufferHandle,
+        uint64_t producerUsageMask, uint64_t consumerUsageMask,
+        const Rect* accessRegion, int32_t acquireFence,
+        FlexLayout* outFlexLayout)
+{
+    int32_t error = mDispatch.lockFlex(mDevice, bufferHandle,
+            producerUsageMask, consumerUsageMask,
+            reinterpret_cast<const gralloc1_rect_t*>(accessRegion),
+            reinterpret_cast<android_flex_layout_t*>(outFlexLayout),
+            acquireFence);
+    return static_cast<Error>(error);
+}
+
+Error GrallocDevice::unlock(const native_handle_t* bufferHandle,
+        int32_t* outReleaseFence)
+{
+    int32_t error = mDispatch.unlock(mDevice, bufferHandle, outReleaseFence);
+    return static_cast<Error>(error);
+}
+
+class GrallocMapper : public IMapper {
+public:
+    GrallocMapper() : IMapper{
+        .createDevice = createDevice,
+        .destroyDevice = destroyDevice,
+        .retain = retain,
+        .release = release,
+        .getDimensions = getDimensions,
+        .getFormat = getFormat,
+        .getLayerCount = getLayerCount,
+        .getProducerUsageMask = getProducerUsageMask,
+        .getConsumerUsageMask = getConsumerUsageMask,
+        .getBackingStore = getBackingStore,
+        .getStride = getStride,
+        .getNumFlexPlanes = getNumFlexPlanes,
+        .lock = lock,
+        .lockFlex = lockFlex,
+        .unlock = unlock,
+    } {}
+
+    const IMapper* getInterface() const
+    {
+        return static_cast<const IMapper*>(this);
+    }
+
+private:
+    static GrallocDevice* cast(Device* device)
+    {
+        return reinterpret_cast<GrallocDevice*>(device);
+    }
+
+    static Error createDevice(Device** outDevice)
+    {
+        *outDevice = new GrallocDevice;
+        return Error::NONE;
+    }
+
+    static Error destroyDevice(Device* device)
+    {
+        delete cast(device);
+        return Error::NONE;
+    }
+
+    static Error retain(Device* device,
+            const native_handle_t* bufferHandle)
+    {
+        return cast(device)->retain(bufferHandle);
+    }
+
+    static Error release(Device* device,
+            const native_handle_t* bufferHandle)
+    {
+        return cast(device)->release(bufferHandle);
+    }
+
+    static Error getDimensions(Device* device,
+            const native_handle_t* bufferHandle,
+            uint32_t* outWidth, uint32_t* outHeight)
+    {
+        return cast(device)->getDimensions(bufferHandle, outWidth, outHeight);
+    }
+
+    static Error getFormat(Device* device,
+            const native_handle_t* bufferHandle, PixelFormat* outFormat)
+    {
+        return cast(device)->getFormat(bufferHandle, outFormat);
+    }
+
+    static Error getLayerCount(Device* device,
+            const native_handle_t* bufferHandle, uint32_t* outLayerCount)
+    {
+        return cast(device)->getLayerCount(bufferHandle, outLayerCount);
+    }
+
+    static Error getProducerUsageMask(Device* device,
+            const native_handle_t* bufferHandle, uint64_t* outUsageMask)
+    {
+        return cast(device)->getProducerUsageMask(bufferHandle, outUsageMask);
+    }
+
+    static Error getConsumerUsageMask(Device* device,
+            const native_handle_t* bufferHandle, uint64_t* outUsageMask)
+    {
+        return cast(device)->getConsumerUsageMask(bufferHandle, outUsageMask);
+    }
+
+    static Error getBackingStore(Device* device,
+            const native_handle_t* bufferHandle, BackingStore* outStore)
+    {
+        return cast(device)->getBackingStore(bufferHandle, outStore);
+    }
+
+    static Error getStride(Device* device,
+            const native_handle_t* bufferHandle, uint32_t* outStride)
+    {
+        return cast(device)->getStride(bufferHandle, outStride);
+    }
+
+    static Error getNumFlexPlanes(Device* device,
+            const native_handle_t* bufferHandle, uint32_t* outNumPlanes)
+    {
+        return cast(device)->getNumFlexPlanes(bufferHandle, outNumPlanes);
+    }
+
+    static Error lock(Device* device,
+            const native_handle_t* bufferHandle,
+            uint64_t producerUsageMask, uint64_t consumerUsageMask,
+            const Device::Rect* accessRegion, int32_t acquireFence,
+            void** outData)
+    {
+        return cast(device)->lock(bufferHandle,
+                producerUsageMask, consumerUsageMask,
+                accessRegion, acquireFence, outData);
+    }
+
+    static Error lockFlex(Device* device,
+            const native_handle_t* bufferHandle,
+            uint64_t producerUsageMask, uint64_t consumerUsageMask,
+            const Device::Rect* accessRegion, int32_t acquireFence,
+            FlexLayout* outFlexLayout)
+    {
+        return cast(device)->lockFlex(bufferHandle,
+                producerUsageMask, consumerUsageMask,
+                accessRegion, acquireFence, outFlexLayout);
+    }
+
+    static Error unlock(Device* device,
+            const native_handle_t* bufferHandle, int32_t* outReleaseFence)
+    {
+        return cast(device)->unlock(bufferHandle, outReleaseFence);
+    }
+};
+
+extern "C" const void* HALLIB_FETCH_Interface(const char* name)
+{
+    if (strcmp(name, "android.hardware.graphics.mapper@2.0::IMapper") == 0) {
+        static GrallocMapper sGrallocMapper;
+        return sGrallocMapper.getInterface();
+    }
+
+    return nullptr;
+}
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace mapper
+} // namespace graphics
+} // namespace hardware
+} // namespace android
diff --git a/graphics/mapper/2.0/include/android/hardware/graphics/mapper/2.0/IMapper.h b/graphics/mapper/2.0/include/android/hardware/graphics/mapper/2.0/IMapper.h
new file mode 100644 (file)
index 0000000..ac8ec45
--- /dev/null
@@ -0,0 +1,404 @@
+/*
+ * Copyright 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.
+ */
+
+#ifndef ANDROID_HARDWARE_GRAPHICS_MAPPER_V2_0_IMAPPER_H
+#define ANDROID_HARDWARE_GRAPHICS_MAPPER_V2_0_IMAPPER_H
+
+#include <type_traits>
+
+#include <android/hardware/graphics/mapper/2.0/types.h>
+
+extern "C" {
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace mapper {
+namespace V2_0 {
+
+struct Device {
+    struct Rect {
+        int32_t left;
+        int32_t top;
+        int32_t width;
+        int32_t height;
+    };
+    static_assert(std::is_pod<Rect>::value, "Device::Rect is not POD");
+
+    /*
+     * Create a mapper device.
+     *
+     * @return error is NONE upon success. Otherwise,
+     *                  NOT_SUPPORTED when creation will never succeed.
+     *                  BAD_RESOURCES when creation failed at this time.
+     * @return device is the newly created mapper device.
+     */
+    typedef Error (*createDevice)(Device** outDevice);
+
+    /*
+     * Destroy a mapper device.
+     *
+     * @return error is always NONE.
+     * @param device is the mapper device to destroy.
+     */
+    typedef Error (*destroyDevice)(Device* device);
+
+    /*
+     * Adds a reference to the given buffer handle.
+     *
+     * A buffer handle received from a remote process or exported by
+     * IAllocator::exportHandle is unknown to this client-side library. There
+     * is also no guarantee that the buffer's backing store will stay alive.
+     * This function must be called at least once in both cases to intrdouce
+     * the buffer handle to this client-side library and to secure the backing
+     * store. It may also be called more than once to increase the reference
+     * count if two components in the same process want to interact with the
+     * buffer independently.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer to which a reference must be added.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid
+     *                  NO_RESOURCES when it is not possible to add a
+     *                               reference to this buffer at this time
+     */
+    typedef Error (*retain)(Device* device,
+                            const native_handle_t* bufferHandle);
+
+    /*
+     * Removes a reference from the given buffer buffer.
+     *
+     * If no references remain, the buffer handle should be freed with
+     * native_handle_close/native_handle_delete. When the last buffer handle
+     * referring to a particular backing store is freed, that backing store
+     * should also be freed.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which a reference must be
+     *        removed.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     */
+    typedef Error (*release)(Device* device,
+                             const native_handle_t* bufferHandle);
+
+    /*
+     * Gets the width and height of the buffer in pixels.
+     *
+     * See IAllocator::BufferDescriptorInfo for more information.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which to get the dimensions.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     * @return width is the width of the buffer in pixels.
+     * @return height is the height of the buffer in pixels.
+     */
+    typedef Error (*getDimensions)(Device* device,
+                                   const native_handle_t* bufferHandle,
+                                   uint32_t* outWidth,
+                                   uint32_t* outHeight);
+
+    /*
+     * Gets the format of the buffer.
+     *
+     * See IAllocator::BufferDescriptorInfo for more information.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which to get format.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     * @return format is the format of the buffer.
+     */
+    typedef Error (*getFormat)(Device* device,
+                               const native_handle_t* bufferHandle,
+                               PixelFormat* outFormat);
+
+    /*
+     * Gets the number of layers of the buffer.
+     *
+     * See IAllocator::BufferDescriptorInfo for more information.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which to get format.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     * @return layerCount is the number of layers of the buffer.
+     */
+    typedef Error (*getLayerCount)(Device* device,
+                               const native_handle_t* bufferHandle,
+                               uint32_t* outLayerCount);
+
+    /*
+     * Gets the producer usage flags which were used to allocate this buffer.
+     *
+     * See IAllocator::BufferDescriptorInfo for more information.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which to get the producer usage
+     *        flags.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     * @return usageMask contains the producer usage flags of the buffer.
+     */
+    typedef Error (*getProducerUsageMask)(Device* device,
+                                          const native_handle_t* bufferHandle,
+                                          uint64_t* outUsageMask);
+
+    /*
+     * Gets the consumer usage flags which were used to allocate this buffer.
+     *
+     * See IAllocator::BufferDescriptorInfo for more information.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which to get the consumer usage
+     *        flags.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     * @return usageMask contains the consumer usage flags of the buffer.
+     */
+    typedef Error (*getConsumerUsageMask)(Device* device,
+                                          const native_handle_t* bufferHandle,
+                                          uint64_t* outUsageMask);
+
+    /*
+     * Gets a value that uniquely identifies the backing store of the given
+     * buffer.
+     *
+     * Buffers which share a backing store should return the same value from
+     * this function. If the buffer is present in more than one process, the
+     * backing store value for that buffer is not required to be the same in
+     * every process.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which to get the backing store
+     *        identifier.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     * @return store is the backing store identifier for this buffer.
+     */
+    typedef Error (*getBackingStore)(Device* device,
+                                     const native_handle_t* bufferHandle,
+                                     BackingStore* outStore);
+
+    /*
+     * Gets the stride of the buffer in pixels.
+     *
+     * The stride is the offset in pixel-sized elements between the same
+     * column in two adjacent rows of pixels. This may not be equal to the
+     * width of the buffer.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer from which to get the stride.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     *                  UNDEFINED when the notion of a stride is not
+     *                            meaningful for the buffer format.
+     * @return store is the stride in pixels.
+     */
+    typedef Error (*getStride)(Device* device,
+                               const native_handle_t* bufferHandle,
+                               uint32_t* outStride);
+
+    /*
+     * Returns the number of flex layout planes which are needed to represent
+     * the given buffer. This may be used to efficiently allocate only as many
+     * plane structures as necessary before calling into lockFlex.
+     *
+     * If the given buffer cannot be locked as a flex format, this function
+     * may return UNSUPPORTED (as lockFlex would).
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer for which the number of planes should
+     *        be queried.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     *                  UNSUPPORTED when the buffer's format cannot be
+     *                              represented in a flex layout.
+     * @return numPlanes is the number of flex planes required to describe the
+     *         given buffer.
+     */
+    typedef Error (*getNumFlexPlanes)(Device* device,
+                                      const native_handle_t* bufferHandle,
+                                      uint32_t* outNumPlanes);
+
+    /*
+     * Locks the given buffer for the specified CPU usage.
+     *
+     * Exactly one of producerUsageMask and consumerUsageMask must be 0. The
+     * usage which is not 0 must be one of the *Usage::CPU* values, as
+     * applicable. Locking a buffer for a non-CPU usage is not supported.
+     *
+     * Locking the same buffer simultaneously from multiple threads is
+     * permitted, but if any of the threads attempt to lock the buffer for
+     * writing, the behavior is undefined, except that it must not cause
+     * process termination or block the client indefinitely. Leaving the
+     * buffer content in an indeterminate state or returning an error are both
+     * acceptable.
+     *
+     * The client must not modify the content of the buffer outside of
+     * accessRegion, and the device need not guarantee that content outside of
+     * accessRegion is valid for reading. The result of reading or writing
+     * outside of accessRegion is undefined, except that it must not cause
+     * process termination.
+     *
+     * data will be filled with a pointer to the locked buffer memory. This
+     * address will represent the top-left corner of the entire buffer, even
+     * if accessRegion does not begin at the top-left corner.
+     *
+     * acquireFence is a file descriptor referring to a acquire sync fence
+     * object, which will be signaled when it is safe for the device to access
+     * the contents of the buffer (prior to locking). If it is already safe to
+     * access the buffer contents, -1 may be passed instead.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer to lock.
+     * @param producerUsageMask contains the producer usage flags to request;
+     *        either this or consumerUsagemask must be 0, and the other must
+     *        be a CPU usage.
+     * @param consumerUsageMask contains the consumer usage flags to request;
+     *        either this or producerUsageMask must be 0, and the other must
+     *        be a CPU usage.
+     * @param accessRegion is the portion of the buffer that the client
+     *        intends to access.
+     * @param acquireFence is a sync fence file descriptor as described above.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     *                  BAD_VALUE when neither or both of producerUsageMask
+     *                            and consumerUsageMask were 0, or the usage
+     *                            which was not 0 was not a CPU usage.
+     *                  NO_RESOURCES when the buffer cannot be locked at this
+     *                               time, but locking may succeed at a future
+     *                               time.
+     *                  UNSUPPORTED when the buffer cannot be locked with the
+     *                              given usage, and any future attempts at
+     *                              locking will also fail.
+     * @return data will be filled with a CPU-accessible pointer to the buffer
+     *         data.
+     */
+    typedef Error (*lock)(Device* device,
+                          const native_handle_t* bufferHandle,
+                          uint64_t producerUsageMask,
+                          uint64_t consumerUsageMask,
+                          const Rect* accessRegion,
+                          int32_t acquireFence,
+                          void** outData);
+
+    /*
+     * This is largely the same as lock(), except that instead of returning a
+     * pointer directly to the buffer data, it returns an FlexLayout struct
+     * describing how to access the data planes.
+     *
+     * This function must work on buffers with PixelFormat::YCbCr_*_888 if
+     * supported by the device, as well as with any other formats requested by
+     * multimedia codecs when they are configured with a
+     * flexible-YUV-compatible color format.
+     *
+     * This function may also be called on buffers of other formats, including
+     * non-YUV formats, but if the buffer format is not compatible with a
+     * flexible representation, it may return UNSUPPORTED.
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer to lock.
+     * @param producerUsageMask contains the producer usage flags to request;
+     *        either this or consumerUsagemask must be 0, and the other must
+     *        be a CPU usage.
+     * @param consumerUsageMask contains the consumer usage flags to request;
+     *        either this or producerUsageMask must be 0, and the other must
+     *        be a CPU usage.
+     * @param accessRegion is the portion of the buffer that the client
+     *        intends to access.
+     * @param acquireFence is a sync fence file descriptor as described in
+     *        lock().
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     *                  BAD_VALUE when neither or both of producerUsageMask
+     *                            and consumerUsageMask were 0, or the usage
+     *                            which was not 0 was not a CPU usage.
+     *                  NO_RESOURCES when the buffer cannot be locked at this
+     *                               time, but locking may succeed at a future
+     *                               time.
+     *                  UNSUPPORTED when the buffer cannot be locked with the
+     *                              given usage, and any future attempts at
+     *                              locking will also fail.
+     * @return flexLayout will be filled with the description of the planes in
+     *         the buffer.
+     */
+    typedef Error (*lockFlex)(Device* device,
+                              const native_handle_t* bufferHandle,
+                              uint64_t producerUsageMask,
+                              uint64_t consumerUsageMask,
+                              const Rect* accessRegion,
+                              int32_t acquireFence,
+                              FlexLayout* outFlexLayout);
+
+    /*
+     * This function indicates to the device that the client will be done with
+     * the buffer when releaseFence signals.
+     *
+     * releaseFence will be filled with a file descriptor referring to a
+     * release sync fence object, which will be signaled when it is safe to
+     * access the contents of the buffer (after the buffer has been unlocked).
+     * If it is already safe to access the buffer contents, then -1 may be
+     * returned instead.
+     *
+     * This function is used to unlock both buffers locked by lock() and those
+     * locked by lockFlex().
+     *
+     * @param device is the mapper device.
+     * @param bufferHandle is the buffer to unlock.
+     * @return error is NONE upon success. Otherwise,
+     *                  BAD_BUFFER when the buffer handle is invalid.
+     * @return releaseFence is a sync fence file descriptor as described
+     *         above.
+     */
+    typedef Error (*unlock)(Device* device,
+                            const native_handle_t* bufferHandle,
+                            int32_t* outReleaseFence);
+};
+static_assert(std::is_pod<Device>::value, "Device is not POD");
+
+struct IMapper {
+    Device::createDevice createDevice;
+    Device::destroyDevice destroyDevice;
+
+    Device::retain retain;
+    Device::release release;
+    Device::getDimensions getDimensions;
+    Device::getFormat getFormat;
+    Device::getLayerCount getLayerCount;
+    Device::getProducerUsageMask getProducerUsageMask;
+    Device::getConsumerUsageMask getConsumerUsageMask;
+    Device::getBackingStore getBackingStore;
+    Device::getStride getStride;
+    Device::getNumFlexPlanes getNumFlexPlanes;
+    Device::lock lock;
+    Device::lockFlex lockFlex;
+    Device::unlock unlock;
+};
+static_assert(std::is_pod<IMapper>::value, "IMapper is not POD");
+
+} // namespace V2_0
+} // namespace mapper
+} // namespace graphics
+} // namespace hardware
+} // namespace android
+
+const void* HALLIB_FETCH_Interface(const char* name);
+
+} // extern "C"
+
+#endif /* ANDROID_HARDWARE_GRAPHICS_MAPPER_V2_0_IMAPPER_H */
diff --git a/graphics/mapper/2.0/include/android/hardware/graphics/mapper/2.0/types.h b/graphics/mapper/2.0/include/android/hardware/graphics/mapper/2.0/types.h
new file mode 100644 (file)
index 0000000..63a6b16
--- /dev/null
@@ -0,0 +1,164 @@
+/*
+ * Copyright 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.
+ */
+
+#ifndef ANDROID_HARDWARE_GRAPHICS_MAPPER_V2_0_TYPES_H
+#define ANDROID_HARDWARE_GRAPHICS_MAPPER_V2_0_TYPES_H
+
+#include <type_traits>
+
+#include <android/hardware/graphics/allocator/2.0/types.h>
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace mapper {
+namespace V2_0 {
+
+using android::hardware::graphics::allocator::V2_0::Error;
+using android::hardware::graphics::allocator::V2_0::PixelFormat;
+using android::hardware::graphics::allocator::V2_0::ProducerUsage;
+using android::hardware::graphics::allocator::V2_0::ConsumerUsage;
+
+/*
+ * Structures for describing flexible YUVA/RGBA formats for consumption by
+ * applications. Such flexible formats contain a plane for each component
+ * (e.g.  red, green, blue), where each plane is laid out in a grid-like
+ * pattern occupying unique byte addresses and with consistent byte offsets
+ * between neighboring pixels.
+ *
+ * The FlexLayout structure is used with any pixel format that can be
+ * represented by it, such as:
+ *
+ *  - PixelFormat::YCbCr_*_888
+ *  - PixelFormat::FLEX_RGB*_888
+ *  - PixelFormat::RGB[AX]_888[8],BGRA_8888,RGB_888
+ *  - PixelFormat::YV12,Y8,Y16,YCbCr_422_SP/I,YCrCb_420_SP
+ *  - even implementation defined formats that can be represented by the
+ *    structures
+ *
+ * Vertical increment (aka. row increment or stride) describes the distance in
+ * bytes from the first pixel of one row to the first pixel of the next row
+ * (below) for the component plane. This can be negative.
+ *
+ * Horizontal increment (aka. column or pixel increment) describes the
+ * distance in bytes from one pixel to the next pixel (to the right) on the
+ * same row for the component plane. This can be negative.
+ *
+ * Each plane can be subsampled either vertically or horizontally by a
+ * power-of-two factor.
+ *
+ * The bit-depth of each component can be arbitrary, as long as the pixels are
+ * laid out on whole bytes, in native byte-order, using the most significant
+ * bits of each unit.
+ */
+
+enum class FlexComponent : int32_t {
+    Y          = 1 << 0,  /* luma */
+    Cb         = 1 << 1,  /* chroma blue */
+    Cr         = 1 << 2,  /* chroma red */
+
+    R          = 1 << 10, /* red */
+    G          = 1 << 11, /* green */
+    B          = 1 << 12, /* blue */
+
+    A          = 1 << 30, /* alpha */
+};
+
+inline FlexComponent operator|(FlexComponent lhs, FlexComponent rhs)
+{
+    return static_cast<FlexComponent>(static_cast<int32_t>(lhs) |
+                                      static_cast<int32_t>(rhs));
+}
+
+inline FlexComponent& operator|=(FlexComponent &lhs, FlexComponent rhs)
+{
+    lhs = static_cast<FlexComponent>(static_cast<int32_t>(lhs) |
+                                     static_cast<int32_t>(rhs));
+    return lhs;
+}
+
+enum class FlexFormat : int32_t {
+    /* not a flexible format */
+    INVALID    = 0x0,
+
+    Y          = static_cast<int32_t>(FlexComponent::Y),
+    YCbCr      = static_cast<int32_t>(FlexComponent::Y) |
+                 static_cast<int32_t>(FlexComponent::Cb) |
+                 static_cast<int32_t>(FlexComponent::Cr),
+    YCbCrA     = static_cast<int32_t>(YCbCr) |
+                 static_cast<int32_t>(FlexComponent::A),
+    RGB        = static_cast<int32_t>(FlexComponent::R) |
+                 static_cast<int32_t>(FlexComponent::G) |
+                 static_cast<int32_t>(FlexComponent::B),
+    RGBA       = static_cast<int32_t>(RGB) |
+                 static_cast<int32_t>(FlexComponent::A),
+};
+
+struct FlexPlane {
+    /* pointer to the first byte of the top-left pixel of the plane. */
+    uint8_t *topLeft;
+
+    FlexComponent component;
+
+    /*
+     * bits allocated for the component in each pixel. Must be a positive
+     * multiple of 8.
+     */
+    int32_t bitsPerComponent;
+
+    /*
+     * number of the most significant bits used in the format for this
+     * component. Must be between 1 and bits_per_component, inclusive.
+     */
+    int32_t bitsUsed;
+
+    /* horizontal increment */
+    int32_t hIncrement;
+    /* vertical increment */
+    int32_t vIncrement;
+
+    /* horizontal subsampling. Must be a positive power of 2. */
+    int32_t hSubsampling;
+    /* vertical subsampling. Must be a positive power of 2. */
+    int32_t vSubsampling;
+};
+static_assert(std::is_pod<FlexPlane>::value, "FlexPlane is not POD");
+
+struct FlexLayout {
+    /* the kind of flexible format */
+    FlexFormat format;
+
+    /* number of planes; 0 for FLEX_FORMAT_INVALID */
+    uint32_t numPlanes;
+
+    /*
+     * a plane for each component; ordered in increasing component value order.
+     * E.g. FLEX_FORMAT_RGBA maps 0 -> R, 1 -> G, etc.
+     * Can be NULL for FLEX_FORMAT_INVALID
+     */
+    FlexPlane* planes;
+};
+static_assert(std::is_pod<FlexLayout>::value, "FlexLayout is not POD");
+
+typedef uint64_t BackingStore;
+
+} // namespace V2_0
+} // namespace mapper
+} // namespace graphics
+} // namespace hardware
+} // namespace android
+
+#endif /* ANDROID_HARDWARE_GRAPHICS_MAPPER_V2_0_TYPES_H */
diff --git a/health/1.0/Android.bp b/health/1.0/Android.bp
new file mode 100644 (file)
index 0000000..fb3d8c0
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.health@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.health@1.0",
+    srcs: [
+        "types.hal",
+        "IHealth.hal",
+    ],
+    out: [
+        "android/hardware/health/1.0/types.cpp",
+        "android/hardware/health/1.0/HealthAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.health@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.health@1.0",
+    srcs: [
+        "types.hal",
+        "IHealth.hal",
+    ],
+    out: [
+        "android/hardware/health/1.0/types.h",
+        "android/hardware/health/1.0/IHealth.h",
+        "android/hardware/health/1.0/IHwHealth.h",
+        "android/hardware/health/1.0/BnHealth.h",
+        "android/hardware/health/1.0/BpHealth.h",
+        "android/hardware/health/1.0/BsHealth.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.health@1.0",
+    generated_sources: ["android.hardware.health@1.0_genc++"],
+    generated_headers: ["android.hardware.health@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.health@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/health/1.0/Android.mk b/health/1.0/Android.mk
new file mode 100644 (file)
index 0000000..776a2c2
--- /dev/null
@@ -0,0 +1,270 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.health@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (BatteryHealth)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/BatteryHealth.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.BatteryHealth
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (BatteryStatus)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/BatteryStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.BatteryStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HealthConfig)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/HealthConfig.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.HealthConfig
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HealthInfo)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/HealthInfo.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.HealthInfo
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Result)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/Result.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.Result
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IHealth.hal
+#
+GEN := $(intermediates)/android/hardware/health/1.0/IHealth.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IHealth.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::IHealth
+
+$(GEN): $(LOCAL_PATH)/IHealth.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.health@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (BatteryHealth)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/BatteryHealth.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.BatteryHealth
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (BatteryStatus)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/BatteryStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.BatteryStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HealthConfig)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/HealthConfig.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.HealthConfig
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HealthInfo)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/HealthInfo.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.HealthInfo
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Result)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/Result.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::types.Result
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IHealth.hal
+#
+GEN := $(intermediates)/android/hardware/health/1.0/IHealth.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IHealth.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0::IHealth
+
+$(GEN): $(LOCAL_PATH)/IHealth.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.health@1.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/health/1.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/IHealth.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.health@1.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/health/1.0/IHealth.hal b/health/1.0/IHealth.hal
new file mode 100644 (file)
index 0000000..3828589
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * 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 android.hardware.health@1.0;
+
+interface IHealth {
+    /**
+     * This function lets you change healthd configuration from default if
+     * desired. It must be called exactly once at startup time.
+     *
+     * The configuration values are described in 'struct HealthConfig'.
+     * To use default configuration, simply return without modifying the
+     * fields of the config parameter.
+     *
+     * @param default healthd configuration.
+     */
+    init(HealthConfig config) generates (HealthConfig configOut);
+
+    /**
+     * This function is a hook to update/change device's HealthInfo (as described
+     * in 'struct HealthInfo').
+     *
+     * 'HealthInfo' describes device's battery and charging status, typically
+     * read from kernel. These values may be modified in this call.
+     *
+     * @param   Device Health info as described in 'struct HealthInfo'.
+     * @return  skipLogging Indication to the caller to add 'or' skip logging the health
+     *          information. Return 'true' to skip logging the update.
+     * @return  infoOut HealthInfo to be sent to client code. (May or may
+     *          not be modified).
+     */
+    update(HealthInfo info) generates (bool skipLogging, HealthInfo infoOut);
+
+    /**
+     * This function is called by healthd when framework queries for remaining
+     * energy in the Battery through BatteryManager APIs.
+     *
+     * @return  result Result of querying enery counter for the battery.
+     * @return  energy Battery remaining energy in nanowatt-hours.
+     *          Must be '0' if result is anything other than Result::SUCCESS.
+     */
+    energyCounter() generates (Result result, int64_t energy);
+};
diff --git a/health/1.0/default/Android.mk b/health/1.0/default/Android.mk
new file mode 100644 (file)
index 0000000..3d9d58a
--- /dev/null
@@ -0,0 +1,56 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.health@1.0-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_C_INCLUDES := system/core/healthd/include system/core/base/include
+LOCAL_SRC_FILES := \
+    Health.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    libcutils \
+    libhidl \
+    libhwbinder \
+    liblog \
+    libutils \
+    android.hardware.health@1.0 \
+
+LOCAL_STATIC_LIBRARIES := android.hardware.health@1.0-convert
+
+LOCAL_HAL_STATIC_LIBRARIES := libhealthd
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.health@1.0-convert
+LOCAL_SRC_FILES := convert.cpp
+LOCAL_C_INCLUDES := system/core/healthd/include system/core/base/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_SHARED_LIBRARIES := \
+    libcutils \
+    libhidl \
+    libutils \
+    android.hardware.health@1.0 \
+
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_MODULE := android.hardware.health@1.0-service
+LOCAL_INIT_RC := android.hardware.health@1.0-service.rc
+LOCAL_SRC_FILES := \
+    HealthService.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libcutils \
+    libdl \
+    libbase \
+    libutils \
+    libhwbinder \
+    libhidl \
+    android.hardware.health@1.0 \
+
+include $(BUILD_EXECUTABLE)
+
+include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/health/1.0/default/Health.cpp b/health/1.0/default/Health.cpp
new file mode 100644 (file)
index 0000000..1a02956
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "health-hal"
+
+#include <Health.h>
+#include <include/hal_conversion.h>
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::health::V1_0::hal_conversion::convertToHealthConfig;
+using ::android::hardware::health::V1_0::hal_conversion::convertFromHealthConfig;
+using ::android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
+using ::android::hardware::health::V1_0::hal_conversion::convertFromHealthInfo;
+
+// Methods from ::android::hardware::health::V1_0::IHealth follow.
+Return<void> Health::init(const HealthConfig& config, init_cb _hidl_cb)  {
+    struct healthd_config healthd_config = {};
+    HealthConfig configOut;
+
+    // To keep working with existing healthd static HALs,
+    // convert the new HealthConfig to the old healthd_config
+    // and back.
+
+    convertFromHealthConfig(config, &healthd_config);
+    healthd_board_init(&healthd_config);
+    mGetEnergyCounter = healthd_config.energyCounter;
+    convertToHealthConfig(&healthd_config, configOut);
+
+    _hidl_cb(configOut);
+
+    return Void();
+}
+
+Return<void> Health::update(const HealthInfo& info, update_cb _hidl_cb)  {
+    struct android::BatteryProperties p = {};
+    HealthInfo infoOut;
+
+    // To keep working with existing healthd static HALs,
+    // convert the new HealthInfo to android::Batteryproperties
+    // and back.
+
+    convertFromHealthInfo(info, &p);
+    int skipLogging = healthd_board_battery_update(&p);
+    convertToHealthInfo(&p, infoOut);
+
+    _hidl_cb(!!skipLogging, infoOut);
+
+    return Void();
+}
+
+Return<void> Health::energyCounter(energyCounter_cb _hidl_cb) {
+    int64_t energy = 0;
+    Result result = Result::NOT_SUPPORTED;
+
+    if (mGetEnergyCounter) {
+        int status = mGetEnergyCounter(&energy);
+        if (status == 0) {
+            result = Result::SUCCESS;
+        }
+    }
+
+    _hidl_cb(result, energy);
+
+   return Void();
+}
+
+IHealth* HIDL_FETCH_IHealth(const char* /* name */) {
+    return new Health();
+}
+
+} // namespace implementation
+}  // namespace V1_0
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
diff --git a/health/1.0/default/Health.h b/health/1.0/default/Health.h
new file mode 100644 (file)
index 0000000..c05751f
--- /dev/null
@@ -0,0 +1,42 @@
+#ifndef HIDL_GENERATED_android_hardware_health_V1_0_Health_H_
+#define HIDL_GENERATED_android_hardware_health_V1_0_Health_H_
+
+#include <android/hardware/health/1.0/IHealth.h>
+#include <hidl/Status.h>
+#include <hidl/MQDescriptor.h>
+#include <healthd/healthd.h>
+#include <utils/String8.h>
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::health::V1_0::HealthInfo;
+using ::android::hardware::health::V1_0::HealthConfig;
+using ::android::hardware::health::V1_0::IHealth;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Health : public IHealth {
+    // Methods from ::android::hardware::health::V1_0::IHealth follow.
+    Return<void> init(const HealthConfig& config, init_cb _hidl_cb)  override;
+    Return<void> update(const HealthInfo& info, update_cb _hidl_cb)  override;
+    Return<void> energyCounter(energyCounter_cb _hidl_cb) override;
+private:
+    std::function<int(int64_t *)> mGetEnergyCounter;
+};
+
+extern "C" IHealth* HIDL_FETCH_IHealth(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_health_V1_0_Health_H_
diff --git a/health/1.0/default/HealthService.cpp b/health/1.0/default/HealthService.cpp
new file mode 100644 (file)
index 0000000..107f33d
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "android.hardware.health@1.0-service"
+
+#include <android/hardware/health/1.0/IHealth.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::health::V1_0::IHealth;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IHealth>("health");
+}
diff --git a/health/1.0/default/android.hardware.health@1.0-service.rc b/health/1.0/default/android.hardware.health@1.0-service.rc
new file mode 100644 (file)
index 0000000..a0d6a56
--- /dev/null
@@ -0,0 +1,4 @@
+service health-hal-1-0 /system/bin/hw/android.hardware.health@1.0-service
+    class hal
+    user system
+    group system
diff --git a/health/1.0/default/convert.cpp b/health/1.0/default/convert.cpp
new file mode 100644 (file)
index 0000000..7f1e3c4
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+#include "include/hal_conversion.h"
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V1_0 {
+namespace hal_conversion {
+
+void convertToHealthConfig(const struct healthd_config *hc, HealthConfig& config) {
+    config.periodicChoresIntervalFast = hc->periodic_chores_interval_fast;
+    config.periodicChoresIntervalSlow = hc->periodic_chores_interval_slow;
+
+    config.batteryStatusPath        = hc->batteryStatusPath.string();
+    config.batteryHealthPath        = hc->batteryHealthPath.string();
+    config.batteryPresentPath       = hc->batteryPresentPath.string();
+    config.batteryCapacityPath      = hc->batteryCapacityPath.string();
+    config.batteryVoltagePath       = hc->batteryVoltagePath.string();
+    config.batteryTemperaturePath   = hc->batteryTemperaturePath.string();
+    config.batteryTechnologyPath    = hc->batteryTechnologyPath.string();
+    config.batteryCurrentNowPath    = hc->batteryCurrentNowPath.string();
+    config.batteryCurrentAvgPath    = hc->batteryCurrentAvgPath.string();
+    config.batteryChargeCounterPath = hc->batteryChargeCounterPath.string();
+    config.batteryFullChargePath    = hc->batteryFullChargePath.string();
+    config.batteryCycleCountPath    = hc->batteryCycleCountPath.string();
+
+}
+
+void convertFromHealthConfig(const HealthConfig& c, struct healthd_config *hc) {
+    hc->periodic_chores_interval_fast = c.periodicChoresIntervalFast;
+    hc->periodic_chores_interval_slow = c.periodicChoresIntervalSlow;
+
+    hc->batteryStatusPath =
+        android::String8(c.batteryStatusPath.c_str(),
+                         c.batteryStatusPath.size());
+
+    hc->batteryHealthPath =
+        android::String8(c.batteryHealthPath.c_str(),
+                         c.batteryHealthPath.size());
+
+    hc->batteryPresentPath =
+        android::String8(c.batteryPresentPath.c_str(),
+                         c.batteryPresentPath.size());
+
+    hc->batteryCapacityPath =
+        android::String8(c.batteryCapacityPath.c_str(),
+                         c.batteryCapacityPath.size());
+
+    hc->batteryVoltagePath =
+        android::String8(c.batteryVoltagePath.c_str(),
+                         c.batteryVoltagePath.size());
+
+    hc->batteryTemperaturePath =
+        android::String8(c.batteryTemperaturePath.c_str(),
+                         c.batteryTemperaturePath.size());
+
+    hc->batteryTechnologyPath =
+        android::String8(c.batteryTechnologyPath.c_str(),
+                         c.batteryTechnologyPath.size());
+
+    hc->batteryCurrentNowPath =
+        android::String8(c.batteryCurrentNowPath.c_str(),
+                         c.batteryCurrentNowPath.size());
+
+    hc->batteryCurrentAvgPath =
+        android::String8(c.batteryCurrentAvgPath.c_str(),
+                         c.batteryCurrentNowPath.size());
+
+    hc->batteryChargeCounterPath =
+        android::String8(c.batteryChargeCounterPath.c_str(),
+                         c.batteryChargeCounterPath.size());
+
+    hc->batteryFullChargePath =
+        android::String8(c.batteryFullChargePath.c_str(),
+                         c.batteryFullChargePath.size());
+
+    hc->batteryCycleCountPath =
+        android::String8(c.batteryCycleCountPath.c_str(),
+                         c.batteryCycleCountPath.size());
+
+    // energyCounter is handled through special means so all calls to
+    // the function go across the HALs
+
+    // boot_min_cap - never used in Android (only in charger-mode).
+
+    // screen_on - never used in Android (only in charger mode).
+}
+
+void convertToHealthInfo(const struct android::BatteryProperties *p,
+                                 HealthInfo& info) {
+    info.chargerAcOnline        = p->chargerAcOnline;
+    info.chargerUsbOnline       = p->chargerUsbOnline;
+    info.chargerWirelessOnline  = p->chargerWirelessOnline;
+    info.maxChargingCurrent     = p->maxChargingCurrent;
+    info.maxChargingVoltage     = p->maxChargingVoltage;
+    info.batteryStatus          = static_cast<BatteryStatus>(p->batteryStatus);
+    info.batteryHealth          = static_cast<BatteryHealth>(p->batteryHealth);
+    info.batteryPresent         = p->batteryPresent;
+    info.batteryLevel           = p->batteryLevel;
+    info.batteryVoltage         = p->batteryVoltage;
+    info.batteryTemperature     = p->batteryTemperature;
+    info.batteryCurrent         = p->batteryCurrent;
+    info.batteryCycleCount      = p->batteryCycleCount;
+    info.batteryFullCharge      = p->batteryFullCharge;
+    info.batteryChargeCounter   = p->batteryChargeCounter;
+    info.batteryTechnology      = p->batteryTechnology;
+}
+
+void convertFromHealthInfo(const HealthInfo& info,
+                                   struct android::BatteryProperties *p) {
+    p->chargerAcOnline          = info.chargerAcOnline;
+    p->chargerUsbOnline         = info.chargerUsbOnline;
+    p->chargerWirelessOnline    = info.chargerWirelessOnline;
+    p->maxChargingCurrent       = info.maxChargingCurrent;
+    p->maxChargingVoltage       = info.maxChargingVoltage;
+    p->batteryStatus            = static_cast<int>(info.batteryStatus);
+    p->batteryHealth            = static_cast<int>(info.batteryHealth);
+    p->batteryPresent           = info.batteryPresent;
+    p->batteryLevel             = info.batteryLevel;
+    p->batteryVoltage           = info.batteryVoltage;
+    p->batteryTemperature       = info.batteryTemperature;
+    p->batteryCurrent           = info.batteryCurrent;
+    p->batteryCycleCount        = info.batteryCycleCount;
+    p->batteryFullCharge        = info.batteryFullCharge;
+    p->batteryChargeCounter     = info.batteryChargeCounter;
+    p->batteryTechnology        = android::String8(info.batteryTechnology.c_str());
+}
+
+} // namespace hal_conversion
+} // namespace V1_0
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/health/1.0/default/include/hal_conversion.h b/health/1.0/default/include/hal_conversion.h
new file mode 100644 (file)
index 0000000..a92b208
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+#ifndef HARDWARE_INTERFACES_HEALTH_V1_0_DEFAULT_INCLUDE_HAL_CONVERSION_H_
+#define HARDWARE_INTERFACES_HEALTH_V1_0_DEFAULT_INCLUDE_HAL_CONVERSION_H_
+
+#include <android/hardware/health/1.0/IHealth.h>
+#include <healthd/healthd.h>
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V1_0 {
+namespace hal_conversion {
+
+void convertToHealthConfig(const struct healthd_config *hc,
+                            HealthConfig& config);
+void convertFromHealthConfig(const HealthConfig& c, struct healthd_config *hc);
+
+void convertToHealthInfo(const struct android::BatteryProperties *p,
+                                 HealthInfo& info);
+void convertFromHealthInfo(const HealthInfo& info,
+                                 struct android::BatteryProperties *p);
+
+}  // namespace hal_conversion
+}  // namespace V1_0
+}  // namespace sensors
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HARDWARE_INTERFACES_HEALTH_V1_0_DEFAULT_INCLUDE_HAL_CONVERSION_H_
diff --git a/health/1.0/default/libhealthd/Android.mk b/health/1.0/default/libhealthd/Android.mk
new file mode 100644 (file)
index 0000000..a5f4445
--- /dev/null
@@ -0,0 +1,10 @@
+# Copyright 2016 The Android Open Source Project
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := healthd_board_default.cpp
+LOCAL_MODULE := libhealthd.default
+LOCAL_CFLAGS := -Werror
+LOCAL_C_INCLUDES := system/core/healthd/include system/core/base/include
+include $(BUILD_STATIC_LIBRARY)
diff --git a/health/1.0/default/libhealthd/healthd_board_default.cpp b/health/1.0/default/libhealthd/healthd_board_default.cpp
new file mode 100644 (file)
index 0000000..127f98e
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <healthd/healthd.h>
+
+void healthd_board_init(struct healthd_config*)
+{
+    // use defaults
+}
+
+int healthd_board_battery_update(struct android::BatteryProperties*)
+{
+    // return 0 to log periodic polled battery status to kernel log
+    return 0;
+}
diff --git a/health/1.0/types.hal b/health/1.0/types.hal
new file mode 100644 (file)
index 0000000..c5b5cc1
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ * 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 android.hardware.health@1.0;
+
+/*
+ * Possible return values for optional HAL method(s) like
+ * IHealth::energyCounter()
+ */
+enum Result : int32_t {
+    SUCCESS,
+    NOT_SUPPORTED,
+    UNKNOWN,
+};
+
+/*
+ * Possible values for Battery Status.
+ * Note: These are currently in sync with BatteryManager and must not
+ * be extended / altered.
+ */
+@export(name="", value_prefix="BATTERY_STATUS_")
+enum BatteryStatus : int32_t {
+    UNKNOWN = 1,
+    CHARGING = 2,
+    DISCHARGING = 3,
+    /*
+     * Battery is *not* charging - special case when charger is present
+     * but battery isn't charging
+     */
+    NOT_CHARGING = 4,
+    FULL = 5,
+};
+
+/*
+ * Possible values for Battery Health.
+ * Note: These are currently in sync with BatteryManager and must not
+ * be extended / altered.
+ */
+@export(name="", value_prefix="BATTERY_HEALTH_")
+enum BatteryHealth : int32_t {
+    UNKNOWN = 1,
+    GOOD = 2,
+    OVERHEAT = 3,
+    DEAD = 4,
+    OVER_VOLTAGE = 5,
+    /*
+     * Battery experienced an unknown/unspecifid failure.
+     */
+    UNSPECIFIED_FAILURE = 6,
+    COLD = 7,
+};
+
+struct HealthConfig {
+
+    /*
+     * periodicChoresIntervalFast is used while the device is not in
+     * suspend, or in suspend and connected to a charger (to watch for battery
+     * overheat due to charging)
+     */
+    int32_t periodicChoresIntervalFast;
+
+    /*
+     * periodicChoresIntervalSlow is used when the device is in suspend and
+     * not connected to a charger (to watch for a battery drained to zero
+     * remaining capacity).
+     */
+    int32_t periodicChoresIntervalSlow;
+
+    /*
+     * power_supply sysfs attribute file paths. Set these to specific paths
+     * to use for the associated battery parameters. Clients must search
+     * for appropriate power_supply attribute files to use, for any paths
+     * left empty after the HAL is initialized.
+     */
+
+    /*
+     * batteryStatusPath - file path to read battery charging status.
+     * (POWER_SUPPLY_PROP_STATUS)
+     */
+    string batteryStatusPath;
+
+
+    /*
+     * batteryHealthPath - file path to read battery health.
+     * (POWER_SUPPLY_PROP_HEALTH)
+     */
+    string batteryHealthPath;
+
+    /*
+     * batteryPresentPath - file path to read battery present status.
+     * (POWER_SUPPLY_PROP_PRESENT)
+     */
+    string batteryPresentPath;
+
+
+    /*
+     * batteryCapacityPath - file path to read remaining battery capacity.
+     * (POWER_SUPPLY_PROP_CAPACITY)
+     */
+    string batteryCapacityPath;
+
+    /*
+     * batteryVoltagePath - file path to read battery voltage.
+     * (POWER_SUPPLY_PROP_VOLTAGE_NOW)
+     */
+    string batteryVoltagePath;
+
+    /*
+     * batteryTemperaturePath - file path to read battery temperature in tenths
+     * of degree celcius. (POWER_SUPPLY_PROP_TEMP)
+     */
+    string batteryTemperaturePath;
+
+    /*
+     * batteryTechnologyPath - file path to read battery technology.
+     * (POWER_SUPPLY_PROP_TECHNOLOGY)
+     */
+    string batteryTechnologyPath;
+
+    /*
+     * batteryCurrentNowPath - file path to read battery instantaneous current.
+     * (POWER_SUPPLY_PROP_CURRENT_NOW)
+     */
+    string batteryCurrentNowPath;
+
+    /*
+     * batteryCurrentAvgPath - file path to read battery average current.
+     * (POWER_SUPPLY_PROP_CURRENT_AVG)
+     */
+    string batteryCurrentAvgPath;
+
+    /*
+     * batteryChargeCounterPath - file path to read battery accumulated charge.
+     * (POWER_SUPPLY_PROP_CHARGE_COUNTER)
+     */
+    string batteryChargeCounterPath;
+
+    /*
+     * batteryFullChargerPath - file path to read battery charge value when it
+     * is considered to be full. (POWER_SUPPLY_PROP_CHARGE_FULL)
+     */
+    string batteryFullChargePath;
+
+    /*
+     * batteryCycleCountPath - file path to read battery charge cycle count.
+     * (POWER_SUPPLY_PROP_CYCLE_COUNT)
+     */
+    string batteryCycleCountPath;
+};
+
+/*
+ * The parameter to healthd mainloop update calls
+ */
+struct HealthInfo {
+    /* AC charger state - 'true' if online */
+    bool chargerAcOnline;
+
+    /* USB charger state - 'true' if online */
+    bool chargerUsbOnline;
+
+    /* Wireless charger state - 'true' if online */
+    bool chargerWirelessOnline;
+
+    /* Maximum charging current supported by charger in uA */
+    int32_t maxChargingCurrent;
+
+    /* Maximum charging voltage supported by charger in uV */
+    int32_t maxChargingVoltage;
+
+    BatteryStatus batteryStatus;
+
+    BatteryHealth batteryHealth;
+
+    /* 'true' if battery is present */
+    bool batteryPresent;
+
+    /* Remaining battery capacity in percent */
+    int32_t batteryLevel;
+
+    /* Instantaneous battery voltage in uV */
+    int32_t batteryVoltage;
+
+    /* Instantaneous battery temperature in tenths of degree celcius */
+    int32_t batteryTemperature;
+
+    /* Instantaneous battery current in uA */
+    int32_t batteryCurrent;
+
+    /* Battery charge cycle count */
+    int32_t batteryCycleCount;
+
+    /* Battery charge value when it is considered to be "full" in uA-h */
+    int32_t batteryFullCharge;
+
+    /* Instantaneous battery capacity in uA-h */
+    int32_t batteryChargeCounter;
+
+    /* Battery technology, e.g. "Li-ion, Li-Poly" etc. */
+    string batteryTechnology;
+};
diff --git a/health/Android.bp b/health/Android.bp
new file mode 100644 (file)
index 0000000..bbb3e4b
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+]
diff --git a/light/2.0/Android.bp b/light/2.0/Android.bp
new file mode 100644 (file)
index 0000000..b762cc1
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.light@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.light@2.0",
+    srcs: [
+        "types.hal",
+        "ILight.hal",
+    ],
+    out: [
+        "android/hardware/light/2.0/types.cpp",
+        "android/hardware/light/2.0/LightAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.light@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.light@2.0",
+    srcs: [
+        "types.hal",
+        "ILight.hal",
+    ],
+    out: [
+        "android/hardware/light/2.0/types.h",
+        "android/hardware/light/2.0/ILight.h",
+        "android/hardware/light/2.0/IHwLight.h",
+        "android/hardware/light/2.0/BnLight.h",
+        "android/hardware/light/2.0/BpLight.h",
+        "android/hardware/light/2.0/BsLight.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.light@2.0",
+    generated_sources: ["android.hardware.light@2.0_genc++"],
+    generated_headers: ["android.hardware.light@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.light@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/light/2.0/Android.mk b/light/2.0/Android.mk
new file mode 100644 (file)
index 0000000..8dc83f0
--- /dev/null
@@ -0,0 +1,238 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.light@2.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (Brightness)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Brightness.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Brightness
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Flash)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Flash.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Flash
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (LightState)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/LightState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.LightState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Status)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Status.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Status
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Type)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Type.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Type
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build ILight.hal
+#
+GEN := $(intermediates)/android/hardware/light/2.0/ILight.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/ILight.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::ILight
+
+$(GEN): $(LOCAL_PATH)/ILight.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.light@2.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (Brightness)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Brightness.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Brightness
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Flash)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Flash.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Flash
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (LightState)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/LightState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.LightState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Status)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Status.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Status
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Type)
+#
+GEN := $(intermediates)/android/hardware/light/2.0/Type.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::types.Type
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build ILight.hal
+#
+GEN := $(intermediates)/android/hardware/light/2.0/ILight.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/ILight.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.light@2.0::ILight
+
+$(GEN): $(LOCAL_PATH)/ILight.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/light/2.0/ILight.hal b/light/2.0/ILight.hal
new file mode 100644 (file)
index 0000000..a7cd684
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * 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 android.hardware.light@2.0;
+
+interface ILight {
+
+    /**
+     * Set the provided lights to the provided values.
+     *
+     * @param type logical light to set
+     * @param state describes what the light should look like.
+     * @return status result of applying state transformation.
+     */
+    setLight(Type type, LightState state) generates (Status status);
+
+    /**
+     * Discover what indicator lights are available.
+     *
+     * @return types list of available lights
+     */
+    getSupportedTypes() generates (vec<Type> types);
+
+};
diff --git a/light/2.0/default/Android.mk b/light/2.0/default/Android.mk
new file mode 100644 (file)
index 0000000..61f4cc9
--- /dev/null
@@ -0,0 +1,43 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.light@2.0-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    Light.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    libhidl \
+    libhwbinder \
+    libutils \
+    liblog \
+    libcutils \
+    libhardware \
+    libbase \
+    libcutils \
+    android.hardware.light@2.0 \
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_MODULE := android.hardware.light@2.0-service
+LOCAL_INIT_RC := android.hardware.light@2.0-service.rc
+LOCAL_SRC_FILES := \
+    service.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libcutils \
+    libdl \
+    libbase \
+    libutils \
+    libhardware_legacy \
+    libhardware \
+
+LOCAL_SHARED_LIBRARIES += \
+    libhwbinder \
+    libhidl \
+    android.hardware.light@2.0 \
+
+include $(BUILD_EXECUTABLE)
diff --git a/light/2.0/default/Light.cpp b/light/2.0/default/Light.cpp
new file mode 100644 (file)
index 0000000..fe94e91
--- /dev/null
@@ -0,0 +1,140 @@
+#include "Light.h"
+
+namespace android {
+namespace hardware {
+namespace light {
+namespace V2_0 {
+namespace implementation {
+
+static_assert(LIGHT_FLASH_NONE == static_cast<int>(Flash::NONE),
+    "Flash::NONE must match legacy value.");
+static_assert(LIGHT_FLASH_TIMED == static_cast<int>(Flash::TIMED),
+    "Flash::TIMED must match legacy value.");
+static_assert(LIGHT_FLASH_HARDWARE == static_cast<int>(Flash::HARDWARE),
+    "Flash::HARDWARE must match legacy value.");
+
+static_assert(BRIGHTNESS_MODE_USER == static_cast<int>(Brightness::USER),
+    "Brightness::USER must match legacy value.");
+static_assert(BRIGHTNESS_MODE_SENSOR == static_cast<int>(Brightness::SENSOR),
+    "Brightness::SENSOR must match legacy value.");
+static_assert(BRIGHTNESS_MODE_LOW_PERSISTENCE ==
+    static_cast<int>(Brightness::LOW_PERSISTENCE),
+    "Brightness::LOW_PERSISTENCE must match legacy value.");
+
+Light::Light(std::map<Type, light_device_t*> &&lights)
+  : mLights(std::move(lights)) {}
+
+// Methods from ::android::hardware::light::V2_0::ILight follow.
+Return<Status> Light::setLight(Type type, const LightState& state)  {
+    auto it = mLights.find(type);
+
+    if (it == mLights.end()) {
+        return Status::LIGHT_NOT_SUPPORTED;
+    }
+
+    light_device_t* hwLight = it->second;
+
+    light_state_t legacyState {
+        .color = state.color,
+        .flashMode = static_cast<int>(state.flashMode),
+        .flashOnMS = state.flashOnMs,
+        .flashOffMS = state.flashOffMs,
+        .brightnessMode = static_cast<int>(state.brightnessMode),
+    };
+
+    int ret = hwLight->set_light(hwLight, &legacyState);
+
+    switch (ret) {
+        case -ENOSYS:
+            return Status::BRIGHTNESS_NOT_SUPPORTED;
+        case 0:
+            return Status::SUCCESS;
+        default:
+            return Status::UNKNOWN;
+    }
+}
+
+Return<void> Light::getSupportedTypes(getSupportedTypes_cb _hidl_cb)  {
+    Type *types = new Type[mLights.size()];
+
+    int idx = 0;
+    for(auto const &pair : mLights) {
+        Type type = pair.first;
+
+        types[idx++] = type;
+    }
+
+    {
+        hidl_vec<Type> hidl_types{};
+        hidl_types.setToExternal(types, mLights.size());
+
+        _hidl_cb(hidl_types);
+    }
+
+    delete[] types;
+
+    return Void();
+}
+
+const static std::map<Type, const char*> kLogicalLights = {
+    {Type::BACKLIGHT,     LIGHT_ID_BACKLIGHT},
+    {Type::KEYBOARD,      LIGHT_ID_KEYBOARD},
+    {Type::BUTTONS,       LIGHT_ID_BUTTONS},
+    {Type::BATTERY,       LIGHT_ID_BATTERY},
+    {Type::NOTIFICATIONS, LIGHT_ID_NOTIFICATIONS},
+    {Type::ATTENTION,     LIGHT_ID_ATTENTION},
+    {Type::BLUETOOTH,     LIGHT_ID_BLUETOOTH},
+    {Type::WIFI,          LIGHT_ID_WIFI}
+};
+
+light_device_t* getLightDevice(const char* name) {
+    light_device_t* lightDevice;
+    const hw_module_t* hwModule = NULL;
+
+    int ret = hw_get_module (LIGHTS_HARDWARE_MODULE_ID, &hwModule);
+    if (ret == 0) {
+        ret = hwModule->methods->open(hwModule, name,
+            reinterpret_cast<hw_device_t**>(&lightDevice));
+        if (ret != 0) {
+            ALOGE("light_open %s %s failed: %d", LIGHTS_HARDWARE_MODULE_ID, name, ret);
+        }
+    } else {
+        ALOGE("hw_get_module %s %s failed: %d", LIGHTS_HARDWARE_MODULE_ID, name, ret);
+    }
+
+    if (ret == 0) {
+        return lightDevice;
+    } else {
+        ALOGE("Light passthrough failed to load legacy HAL.");
+        return nullptr;
+    }
+}
+
+ILight* HIDL_FETCH_ILight(const char* /* name */) {
+    std::map<Type, light_device_t*> lights;
+
+    for(auto const &pair : kLogicalLights) {
+        Type type = pair.first;
+        const char* name = pair.second;
+
+        light_device_t* light = getLightDevice(name);
+
+        if (light != nullptr) {
+            lights[type] = light;
+        }
+    }
+
+    if (lights.size() == 0) {
+        // Log information, but still return new Light.
+        // Some devices may not have any lights.
+        ALOGI("Could not open any lights.");
+    }
+
+    return new Light(std::move(lights));
+}
+
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace light
+}  // namespace hardware
+}  // namespace android
diff --git a/light/2.0/default/Light.h b/light/2.0/default/Light.h
new file mode 100644 (file)
index 0000000..b32a09a
--- /dev/null
@@ -0,0 +1,46 @@
+#ifndef HIDL_GENERATED_android_hardware_light_V2_0_Light_H_
+#define HIDL_GENERATED_android_hardware_light_V2_0_Light_H_
+
+#include <android/hardware/light/2.0/ILight.h>
+#include <hardware/hardware.h>
+#include <hardware/lights.h>
+#include <hidl/Status.h>
+#include <hidl/MQDescriptor.h>
+#include <map>
+
+namespace android {
+namespace hardware {
+namespace light {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::light::V2_0::ILight;
+using ::android::hardware::light::V2_0::LightState;
+using ::android::hardware::light::V2_0::Status;
+using ::android::hardware::light::V2_0::Type;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Light : public ILight {
+    Light(std::map<Type, light_device_t*> &&lights);
+
+    // Methods from ::android::hardware::light::V2_0::ILight follow.
+    Return<Status> setLight(Type type, const LightState& state)  override;
+    Return<void> getSupportedTypes(getSupportedTypes_cb _hidl_cb)  override;
+
+private:
+    std::map<Type, light_device_t*> mLights;
+};
+
+extern "C" ILight* HIDL_FETCH_ILight(const char* name);
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace light
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_light_V2_0_Light_H_
diff --git a/light/2.0/default/android.hardware.light@2.0-service.rc b/light/2.0/default/android.hardware.light@2.0-service.rc
new file mode 100644 (file)
index 0000000..3ba97d8
--- /dev/null
@@ -0,0 +1,4 @@
+service light-hal-2-0 /system/bin/hw/android.hardware.light@2.0-service
+    class hal
+    user system
+    group system
\ No newline at end of file
diff --git a/light/2.0/default/service.cpp b/light/2.0/default/service.cpp
new file mode 100644 (file)
index 0000000..b3848e9
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright 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.
+ */
+
+#define LOG_TAG "android.hardware.light@2.0-service"
+
+#include <android/hardware/light/2.0/ILight.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::light::V2_0::ILight;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<ILight>("light");
+}
diff --git a/light/2.0/types.hal b/light/2.0/types.hal
new file mode 100644 (file)
index 0000000..f065ce0
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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 android.hardware.light@2.0;
+
+enum Status : int32_t {
+    SUCCESS,
+    LIGHT_NOT_SUPPORTED,
+    BRIGHTNESS_NOT_SUPPORTED,
+    UNKNOWN,
+};
+
+enum Flash : int32_t {
+    /*
+     * Keep the light steady on or off.
+     */
+    NONE,
+
+    /*
+     * Flash the light at specified rate.
+     */
+    TIMED,
+
+    /*
+     * Flash the light using hardware assist.
+     */
+    HARDWARE,
+};
+
+enum Brightness : int32_t {
+    /**
+     * Light brightness is managed by a user setting.
+     */
+    USER,
+
+    /**
+     * Light brightness is managed by a light sensor.
+     */
+    SENSOR,
+
+    /**
+     * Use a low-persistence mode for display backlights.
+     *
+     * When set, the device driver must switch to a mode optimized for low display
+     * persistence that is intended to be used when the device is being treated as a
+     * head mounted display (HMD). The actual display brightness in this mode is
+     * implementation dependent, and any value set for color in light_state may be
+     * overridden by the HAL implementation.
+     *
+     * For an optimal HMD viewing experience, the display must meet the following
+     * criteria in this mode:
+     * - Gray-to-Gray, White-to-Black, and Black-to-White switching time must be ≤ 3 ms.
+     * - The display must support low-persistence with ≤ 3.5 ms persistence.
+     *   Persistence is defined as the amount of time for which a pixel is
+     *   emitting light for a single frame.
+     * - Any "smart panel" or other frame buffering options that increase display
+     *   latency are disabled.
+     * - Display brightness is set so that the display is still visible to the user
+     *   under normal indoor lighting.
+     * - The display must update at 60 Hz at least, but higher refresh rates are
+     *   recommended for low latency.
+     *
+     */
+    LOW_PERSISTENCE,
+};
+
+/*
+ * These light IDs correspond to logical lights, not physical.
+ * So for example, if your INDICATOR light is in line with your
+ * BUTTONS, it might make sense to also light the INDICATOR
+ * light to a reasonable color when the BUTTONS are lit.
+ */
+enum Type : int32_t {
+    BACKLIGHT,
+    KEYBOARD,
+    BUTTONS,
+    BATTERY,
+    NOTIFICATIONS,
+    ATTENTION,
+    BLUETOOTH,
+    WIFI,
+
+    COUNT,
+};
+
+/**
+ * The parameters that can be set for a given light.
+ *
+ * Not all lights must support all parameters. If you
+ * can do something backward-compatible, do it.
+ */
+struct LightState {
+    /**
+     * The color of the LED in ARGB.
+     *
+     * Do your best here.
+     *   - If your light can only do red or green, if they ask for blue,
+     *     you should do green.
+     *   - If you can only do a brightness ramp, then use this formula:
+     *      unsigned char brightness = ((77*((color>>16)&0x00ff))
+     *              + (150*((color>>8)&0x00ff)) + (29*(color&0x00ff))) >> 8;
+     *   - If you can only do on or off, 0 is off, anything else is on.
+     *
+     * The high byte should be ignored. Callers will set it to 0xff (which
+     * would correspond to 255 alpha).
+     */
+    uint32_t color;
+
+    /**
+     * To flash the light at a given rate, set flashMode to LIGHT_FLASH_TIMED,
+     * and then flashOnMS should be set to the number of milliseconds to turn
+     * the light on, followed by the number of milliseconds to turn the light
+     * off.
+     */
+    Flash flashMode;
+
+    int32_t flashOnMs;
+    int32_t flashOffMs;
+
+    Brightness brightnessMode;
+};
diff --git a/light/2.0/vts/Android.mk b/light/2.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..a8c8c20
--- /dev/null
@@ -0,0 +1,48 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for Light v2.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_light@2.0
+
+LOCAL_SRC_FILES := \
+    Light.vts \
+    types.vts \
+
+LOCAL_SHARED_LIBRARIES += \
+    android.hardware.light@2.0 \
+    libbase \
+    libutils \
+    libcutils \
+    liblog \
+    libhidl \
+    libhwbinder \
+    libprotobuf-cpp-full \
+    libvts_common \
+    libvts_datatype \
+    libvts_measurement \
+    libvts_multidevice_proto
+
+LOCAL_CFLAGS += -DENABLE_TREBLE
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/light/2.0/vts/Light.vts b/light/2.0/vts/Light.vts
new file mode 100644 (file)
index 0000000..5d49822
--- /dev/null
@@ -0,0 +1,37 @@
+component_class: HAL_HIDL
+component_type_version: 2.0
+component_name: "ILight"
+
+package: "android.hardware.light"
+
+import: "android.hardware.light@2.0::types"
+
+interface: {
+    api: {
+        name: "setLight"
+        return_type_hidl: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::light::V2_0::Status"
+        }
+        arg: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::light::V2_0::Type"
+        }
+        arg: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::light::V2_0::LightState"
+        }
+    }
+
+    api: {
+        name: "getSupportedTypes"
+        return_type_hidl: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_ENUM
+                predefined_type: "::android::hardware::light::V2_0::Type"
+            }
+        }
+    }
+
+}
diff --git a/light/2.0/vts/types.vts b/light/2.0/vts/types.vts
new file mode 100644 (file)
index 0000000..a9c8cab
--- /dev/null
@@ -0,0 +1,149 @@
+component_class: HAL_HIDL
+component_type_version: 2.0
+component_name: "types"
+
+package: "android.hardware.light"
+
+
+attribute: {
+    name: "::android::hardware::light::V2_0::Status"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "SUCCESS"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "LIGHT_NOT_SUPPORTED"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "BRIGHTNESS_NOT_SUPPORTED"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "UNKNOWN"
+        scalar_value: {
+            int32_t: 3
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::light::V2_0::Flash"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "NONE"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "TIMED"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "HARDWARE"
+        scalar_value: {
+            int32_t: 2
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::light::V2_0::Brightness"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "USER"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "SENSOR"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "LOW_PERSISTENCE"
+        scalar_value: {
+            int32_t: 2
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::light::V2_0::Type"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "int32_t"
+
+        enumerator: "BACKLIGHT"
+        scalar_value: {
+            int32_t: 0
+        }
+        enumerator: "KEYBOARD"
+        scalar_value: {
+            int32_t: 1
+        }
+        enumerator: "BUTTONS"
+        scalar_value: {
+            int32_t: 2
+        }
+        enumerator: "BATTERY"
+        scalar_value: {
+            int32_t: 3
+        }
+        enumerator: "NOTIFICATIONS"
+        scalar_value: {
+            int32_t: 4
+        }
+        enumerator: "ATTENTION"
+        scalar_value: {
+            int32_t: 5
+        }
+        enumerator: "BLUETOOTH"
+        scalar_value: {
+            int32_t: 6
+        }
+        enumerator: "WIFI"
+        scalar_value: {
+            int32_t: 7
+        }
+        enumerator: "COUNT"
+        scalar_value: {
+            int32_t: 8
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::light::V2_0::LightState"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "color"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+    struct_value: {
+        name: "flashMode"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::light::V2_0::Flash"
+    }
+    struct_value: {
+        name: "flashOnMs"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "flashOffMs"
+        type: TYPE_SCALAR
+        scalar_type: "int32_t"
+    }
+    struct_value: {
+        name: "brightnessMode"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::light::V2_0::Brightness"
+    }
+}
+
diff --git a/light/Android.bp b/light/Android.bp
new file mode 100644 (file)
index 0000000..c12cd4f
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "2.0",
+]
diff --git a/media/1.0/Android.bp b/media/1.0/Android.bp
new file mode 100644 (file)
index 0000000..c8bdd82
--- /dev/null
@@ -0,0 +1,45 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.media@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.media@1.0",
+    srcs: [
+        "types.hal",
+    ],
+    out: [
+        "android/hardware/media/1.0/types.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.media@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.media@1.0",
+    srcs: [
+        "types.hal",
+    ],
+    out: [
+        "android/hardware/media/1.0/types.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.media@1.0",
+    generated_sources: ["android.hardware.media@1.0_genc++"],
+    generated_headers: ["android.hardware.media@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.media@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.graphics.common@1.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.graphics.common@1.0",
+    ],
+}
diff --git a/media/1.0/types.hal b/media/1.0/types.hal
new file mode 100644 (file)
index 0000000..25931f8
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * 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 android.hardware.media@1.0;
+
+import android.hardware.graphics.common@1.0::PixelFormat;
+
+/**
+ * Aliases
+ */
+typedef handle FileDescriptor; // This must have no more than one fd.
+typedef FileDescriptor Fence;
+typedef int32_t Status; // TODO: convert to an enum
+typedef vec<uint8_t> Bytes;
+
+/**
+ * Ref: frameworks/native/include/ui/GraphicBuffer.h
+ * Ref: system/core/include/system/window.h
+ */
+
+/**
+ * This struct contains attributes for a gralloc buffer that can be put into a
+ * union.
+ */
+struct GraphicBufferAttributes {
+    uint32_t width;
+    uint32_t height;
+    uint32_t stride;
+    PixelFormat format;
+    uint32_t usage; // TODO: convert to an enum
+    uint32_t generationNumber;
+};
+
+/**
+ * A GraphicBuffer is simply GraphicBufferAttributes plus a native handle.
+ */
+struct GraphicBuffer {
+    handle nativeHandle;
+    GraphicBufferAttributes attr;
+};
+
+/**
+ * Ref: frameworks/native/include/binder/IMemory.h
+ * Ref: frameworks/native/libs/binder/IMemory.cpp
+ */
+
+/**
+ * This struct contains attributes for a shared memory buffer that can be put
+ * into a union.
+ */
+struct SharedMemoryAttributes {
+    uint32_t size;
+    uint32_t flags; // TODO: convert to an enum
+    uint32_t offset;
+};
+
+/**
+ * A SharedMemory is simply SharedMemoryAttributes plus a native handle.
+ */
+struct SharedMemory {
+    handle nativeHandle;
+    SharedMemoryAttributes attr;
+};
+
diff --git a/media/Android.bp b/media/Android.bp
new file mode 100644 (file)
index 0000000..f2abc67
--- /dev/null
@@ -0,0 +1,5 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+    "omx/1.0",
+]
diff --git a/media/omx/1.0/Android.bp b/media/omx/1.0/Android.bp
new file mode 100644 (file)
index 0000000..95d88a6
--- /dev/null
@@ -0,0 +1,87 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.media.omx@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.media.omx@1.0",
+    srcs: [
+        "types.hal",
+        "IGraphicBufferSource.hal",
+        "IOmx.hal",
+        "IOmxBufferSource.hal",
+        "IOmxNode.hal",
+        "IOmxObserver.hal",
+    ],
+    out: [
+        "android/hardware/media/omx/1.0/types.cpp",
+        "android/hardware/media/omx/1.0/GraphicBufferSourceAll.cpp",
+        "android/hardware/media/omx/1.0/OmxAll.cpp",
+        "android/hardware/media/omx/1.0/OmxBufferSourceAll.cpp",
+        "android/hardware/media/omx/1.0/OmxNodeAll.cpp",
+        "android/hardware/media/omx/1.0/OmxObserverAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.media.omx@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.media.omx@1.0",
+    srcs: [
+        "types.hal",
+        "IGraphicBufferSource.hal",
+        "IOmx.hal",
+        "IOmxBufferSource.hal",
+        "IOmxNode.hal",
+        "IOmxObserver.hal",
+    ],
+    out: [
+        "android/hardware/media/omx/1.0/types.h",
+        "android/hardware/media/omx/1.0/IGraphicBufferSource.h",
+        "android/hardware/media/omx/1.0/IHwGraphicBufferSource.h",
+        "android/hardware/media/omx/1.0/BnGraphicBufferSource.h",
+        "android/hardware/media/omx/1.0/BpGraphicBufferSource.h",
+        "android/hardware/media/omx/1.0/BsGraphicBufferSource.h",
+        "android/hardware/media/omx/1.0/IOmx.h",
+        "android/hardware/media/omx/1.0/IHwOmx.h",
+        "android/hardware/media/omx/1.0/BnOmx.h",
+        "android/hardware/media/omx/1.0/BpOmx.h",
+        "android/hardware/media/omx/1.0/BsOmx.h",
+        "android/hardware/media/omx/1.0/IOmxBufferSource.h",
+        "android/hardware/media/omx/1.0/IHwOmxBufferSource.h",
+        "android/hardware/media/omx/1.0/BnOmxBufferSource.h",
+        "android/hardware/media/omx/1.0/BpOmxBufferSource.h",
+        "android/hardware/media/omx/1.0/BsOmxBufferSource.h",
+        "android/hardware/media/omx/1.0/IOmxNode.h",
+        "android/hardware/media/omx/1.0/IHwOmxNode.h",
+        "android/hardware/media/omx/1.0/BnOmxNode.h",
+        "android/hardware/media/omx/1.0/BpOmxNode.h",
+        "android/hardware/media/omx/1.0/BsOmxNode.h",
+        "android/hardware/media/omx/1.0/IOmxObserver.h",
+        "android/hardware/media/omx/1.0/IHwOmxObserver.h",
+        "android/hardware/media/omx/1.0/BnOmxObserver.h",
+        "android/hardware/media/omx/1.0/BpOmxObserver.h",
+        "android/hardware/media/omx/1.0/BsOmxObserver.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.media.omx@1.0",
+    generated_sources: ["android.hardware.media.omx@1.0_genc++"],
+    generated_headers: ["android.hardware.media.omx@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.media.omx@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.graphics.common@1.0",
+        "android.hardware.media@1.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.graphics.common@1.0",
+        "android.hardware.media@1.0",
+    ],
+}
diff --git a/media/omx/1.0/IGraphicBufferSource.hal b/media/omx/1.0/IGraphicBufferSource.hal
new file mode 100644 (file)
index 0000000..bee57ac
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * 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 android.hardware.media.omx@1.0;
+
+import android.hardware.graphics.common@1.0::Dataspace;
+
+import android.hardware.media@1.0::types;
+
+import IOmxNode;
+
+/**
+ * Ref: frameworks/av/media/libmedia/aidl/android/IGraphicBufferSource.aidl
+ *
+ * TODO: Add documentations.
+ */
+interface IGraphicBufferSource {
+
+    configure(IOmxNode omxNode, Dataspace dataspace)
+        generates (Status status);
+
+    setSuspend(bool suspend)
+        generates (Status status);
+
+    setRepeatPreviousFrameDelayUs(int64_t repeatAfterUs)
+        generates (Status status);
+
+    setMaxFps(float maxFps)
+        generates (Status status);
+
+    setTimeLapseConfig(int64_t timePerFrameUs, int64_t timePerCaptureUs)
+        generates (Status status);
+
+    setStartTimeUs(int64_t startTimeUs)
+        generates (Status status);
+
+    setColorAspects(uint32_t aspects) // TODO: Maybe break down aspects.
+        generates (Status status);
+
+    setTimeOffsetUs(int64_t timeOffsetUs)
+        generates (Status status);
+
+    signalEndOfInputStream()
+        generates (Status status);
+
+};
+
diff --git a/media/omx/1.0/IOmx.hal b/media/omx/1.0/IOmx.hal
new file mode 100644 (file)
index 0000000..e9f0b76
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * 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 android.hardware.media.omx@1.0;
+
+import android.hardware.media@1.0::types;
+
+import IOmxNode;
+import IOmxObserver;
+
+/**
+ * Ref: frameworks/av/include/media/IOMX.h: IOMX
+ *
+ * IOmx is the main entry point for communicating with OMX components.
+ */
+interface IOmx {
+
+    /**
+     * Information for an IOmxNode component.
+     */
+    struct ComponentInfo {
+        string mName;       //< Name of the component.
+        vec<string> mRoles; //< Roles of the component.
+    };
+
+    /**
+     * List available components.
+     *
+     * @param[out] status will be the status of the call.
+     * @param[out] nodeList will be a list of ComponentInfo.
+     */
+    listNodes(
+        ) generates (
+            Status status,
+            vec<ComponentInfo> nodeList
+        );
+
+    /**
+     * Allocate an IOmxNode instance with the specified component name.
+     *
+     * @param[in] name is the name of the component to create.
+     * @param[in] observer is an observer object that will receive messages from
+     * the created instance.
+     * @param[out] status will be the status of the call.
+     * @param[out] omxNode will be the allocated instance of IOmxNode.
+     */
+    allocateNode(
+            string name,
+            IOmxObserver observer
+        ) generates (
+            Status status,
+            IOmxNode omxNode
+        );
+
+};
+
diff --git a/media/omx/1.0/IOmxBufferSource.hal b/media/omx/1.0/IOmxBufferSource.hal
new file mode 100644 (file)
index 0000000..94c43fc
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * 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 android.hardware.media.omx@1.0;
+
+import android.hardware.media@1.0::types;
+
+/**
+ * Ref: frameworks/av/media/libmedia/aidl/android/IOMXBufferSource.aidl
+ *
+ * IOmxBufferSource is an interface for a listener for certain events from an
+ * IOmxNode instance. Use IOmxNode::setInputSurface() to attach an
+ * IOmxBufferSource instance to an IOmxNode instance.
+ *
+ * @see OMX_STATETYPE in the OpenMax IL standard.
+ */
+interface IOmxBufferSource {
+
+    /**
+     * onOmxExecuting() is invoked when the node state changes to
+     * OMX_StateExecuting state.
+     */
+    oneway onOmxExecuting();
+
+    /**
+     * onOmxIdle() is invoked when the node transitions from OMX_StateExecuting
+     * to OMX_StateIdle.
+     */
+    oneway onOmxIdle();
+
+    /**
+     * onOmxLoaded() is invoked when the node transitions from OMX_StateIdle or
+     * OMX_StateExecuting to OMX_StateLoaded.
+     */
+    oneway onOmxLoaded();
+
+    /**
+     * onInputBufferAdded() is invoked after a new input buffer is added to the
+     * node. This may happen within IOmxNode::allocateSecureBuffer() or
+     * IOmxNode::useBuffer().
+     *
+     * @param[in] buffer is the id of the added buffer.
+     */
+    oneway onInputBufferAdded(BufferId buffer);
+
+    /**
+     * onInputBufferEmptied() is invoked after an input buffer is emptied. This
+     * may happen within IOmxNode::emptyBuffer().
+     *
+     * @param[in] buffer is the id of the emptied buffer.
+     * @param[in] fence is the fence associated with the buffer.
+     */
+    oneway onInputBufferEmptied(BufferId buffer, Fence fence);
+};
+
diff --git a/media/omx/1.0/IOmxNode.hal b/media/omx/1.0/IOmxNode.hal
new file mode 100644 (file)
index 0000000..9483be4
--- /dev/null
@@ -0,0 +1,358 @@
+/*
+ * 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 android.hardware.media.omx@1.0;
+
+import IOmxBufferSource;
+
+import android.hardware.media@1.0::types;
+
+/**
+ * Ref: frameworks/av/include/media/IOMX.h: IOMXNode
+ * Ref: https://www.khronos.org/registry/omxil/specs/OpenMAX_IL_1_1_2_Specification.pdf
+ */
+
+/**
+ * IOmxNode is an interface for communicating with an OMX component (called
+ * "node" here) that has been previously obtained by calling
+ * IOmx::allocateNode().
+ */
+interface IOmxNode {
+
+    /**
+     * Free the node.
+     *
+     * @param[out] status will be the status of the call.
+     */
+    freeNode(
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Invoke a command on the node.
+     *
+     * @param[in] cmd indicates the type of the command.
+     * @param[in] info holds information about the command.
+     * @param[out] status will be the status of the call.
+     *
+     * @see OMX_SendCommand() in the OpenMax IL standard.
+     */
+    sendCommand(
+            uint32_t cmd,
+            Bytes info // TODO: describe structure better or point at standard
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Retrieve a parameter setting from the node.
+     *
+     * @param[in] index indicates the type of the parameter to retrieve.
+     * @param[in] inParams holds some information about the retrieval.
+     * @param[out] status will be the status of the call.
+     * @param[out] outParams will be the current parameter setting.
+     *
+     * @see OMX_GetParameter() in the OpenMax IL standard.
+     */
+    getParameter(
+            uint32_t index,
+            Bytes inParams // TODO: describe structure better or point at standard
+        ) generates (
+            Status status,
+            Bytes outParams // TODO: describe structure better or point at standard
+        );
+
+    /**
+     * Change a parameter setting of the node.
+     *
+     * @param[in] index indicates the type of the parameter to change.
+     * @param[in] params holds the new parameter setting.
+     * @param[out] status will be the status of the call.
+     *
+     * @see OMX_SetParameter() in the OpenMax IL standard.
+     */
+    setParameter(
+            uint32_t index,
+            Bytes params // TODO: describe structure better or point at standard
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Retrieve a configuration from the node.
+     *
+     * @param[in] index indicates the type of the configuration to retrieve.
+     * @param[in] inConfig holds some information about the retrieval.
+     * @param[out] status will be the status of the call.
+     * @param[out] outConfig will be the current configuration.
+     *
+     * @see OMX_GetConfig() in the OpenMax IL standard.
+     */
+    getConfig(
+            uint32_t index,
+            Bytes inConfig // TODO: describe structure better or point at standard
+        ) generates (
+            Status status,
+            Bytes outConfig // TODO: describe structure better or point at standard
+        );
+
+    /**
+     * Change a configuration of the node.
+     *
+     * @param[in] index indicates the type of the configuration to change.
+     * @param[in] config holds the new configuration.
+     * @param[out] status will be the status of the call.
+     *
+     * @see OMX_SetConfig() in the OpenMax IL standard.
+     */
+    setConfig(
+            uint32_t index,
+            Bytes config // TODO: describe structure better or point at standard
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Set the mode of a port on the node.
+     *
+     * @param[in] portIndex is the index of the port.
+     * @param[in] mode is the target mode on the specified port.
+     */
+    setPortMode(
+            uint32_t portIndex,
+            PortMode mode
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Prepare a port for adaptive playback. This is based on the extension
+     * "OMX.google.android.index.prepareForAdaptivePlayback".
+     *
+     * @param[in] portIndex is the index of the port.
+     * @param[in] enable indicates whether adaptive playback is enabled or not.
+     * @param[in] maxFrameWidth specifies the maximum frame width.
+     * @param[in] maxFrameHeight specifies the maximum frame height.
+     * @param[out] status status will be the status of the call.
+     */
+    prepareForAdaptivePlayback(
+            uint32_t portIndex,
+            bool enable,
+            uint32_t maxFrameWidth,
+            uint32_t maxFrameHeight
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Configure a port for a tunneled playback mode. This is based on the
+     * extension "OMX.google.android.index.configureVideoTunnelMode".
+     *
+     * @param[in] portIndex is the index of the port.
+     * @param[in] tunneled indicates whether the tunneled mode is used or not.
+     * @param[in] audioHwSync is the HW SYNC ID of the audio HAL output stream
+     * to sync the video with.
+     * @param[out] status will be the status of the call.
+     * @param[out] sidebandHandle will contain the codec-allocated sideband
+     * window handle.
+     */
+    configureVideoTunnelMode(
+            uint32_t portIndex,
+            bool tunneled,
+            uint32_t audioHwSync
+        ) generates (
+            Status status,
+            handle sidebandHandle
+        );
+
+    /**
+     * Retrieve the buffer usage on a port. This is based on the extension
+     * "OMX.google.android.index.getAndroidNativeBufferUsage".
+     *
+     * @param[in] portIndex is the index of the port.
+     * @param[out] status will be the status of the call.
+     * @param[out] usage will be the usage.
+     */
+    getGraphicBufferUsage(
+            uint32_t portIndex
+        ) generates (
+            Status status,
+            uint32_t usage // TODO: Ask graphics team to define an enum.
+        );
+
+    /**
+     * Set up a listener to events related to the input surface.
+     *
+     * @param[in] bufferSource is the listener object that implements
+     * IOmxBufferSource.
+     * @param[out] status will be the status of the call.
+     *
+     * @see IOmxBufferSource.
+     */
+    setInputSurface(
+            IOmxBufferSource bufferSource
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Allocate an opaque buffer on a port as a native handle.
+     *
+     * @param[in] portIndex is the index of the port.
+     * @param[in] size is the desired size of the buffer.
+     * @param[out] status will be the status of the call.
+     * @param[out] buffer will be the id of the allocated buffer, which will be
+     * needed in some other buffer-related function calls.
+     * @param[out] nativeHandle will be the native handle of the allocated
+     * buffer.
+     *
+     * @see OMX_AllocateBuffer() in the OpenMax IL standard.
+     */
+    allocateSecureBuffer(
+            uint32_t portIndex,
+            uint64_t size
+        ) generates (
+            Status status,
+            BufferId buffer,
+            handle nativeHandle
+        );
+
+    /**
+     * Assign a buffer to a port.
+     *
+     * @param[in] portIndex is the index of the port.
+     * @param[in] omxBuffer is the buffer to be assigned to the port.
+     * @param[out] status will be the status of the call.
+     * @param[out] buffer will be the id of the assigned buffer, which will be
+     * needed in some other buffer-related function calls.
+     *
+     * @see OMX_UseBuffer() in the OpenMax IL standard.
+     */
+    useBuffer(
+            uint32_t portIndex,
+            CodecBuffer omxBuffer
+        ) generates (
+            Status status,
+            BufferId buffer
+        );
+
+    /**
+     * Free a buffer previously assigned to a port by allocateSecureBuffer() or
+     * useBuffer().
+     *
+     * @param[in] portIndex is the index of the port.
+     * @param[in] buffer is the id of the buffer to be freed.
+     * @param[out] status will be the status of the call.
+     *
+     * @see OMX_FreeBuffer() in the OpenMax IL standard.
+     */
+    freeBuffer(
+            uint32_t portIndex,
+            BufferId buffer
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Pass \p fence to the node if it supports fences. Otherwise, it waits on
+     * \p fence before calling OMX_FillThisBuffer(). The node will take
+     * ownership of the fence even if this call fails.
+     *
+     * If the port is in metadata mode, the buffer will be updated to point to
+     * the new buffer passed in via \p omxBuffer before OMX_FillThisBuffer() is
+     * called. Otherwise, \p omxBuffer is not used.
+     *
+     * @param[in] buffer is the id of the buffer to fill.
+     * @param[in] omxBuffer points to the new buffer in metadata mode.
+     * @param[in] fence is the fence to wait for (if not null).
+     * @param[out] status is the status of the call.
+     *
+     * @see OMX_FillThisBuffer() in the OpenMax IL standard.
+     */
+    fillBuffer(
+            BufferId buffer,
+            CodecBuffer omxBuffer,
+            Fence fence
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Pass \p fence to the node if it supports fences. Otherwise, wait on
+     * \p fence before calling OMX_EmptyThisBuffer(). The node will take
+     * ownership of the fence even if this call fails.
+     *
+     * If the port is in metadata mode, the buffer will be updated to point to
+     * the new buffer passed in via \p omxBuffer before OMX_EmptyThisBuffer() is
+     * called. Otherwise, \p omxBuffer is not used.
+     *
+     * @param[in] buffer is the id of the buffer to fill.
+     * @param[in] omxBuffer points to the new buffer in metadata mode.
+     * @param[in] flags is put into the header information that is passed to
+     * OMX_EmptyBuffer().
+     * @param[in] timestampUs is put into the header information that is passed
+     * to OMX_EmptyBuffer().
+     * @param[in] fence is the fence to wait for (if not null).
+     * @param[out] status is the status of the call.
+     *
+     * @see OMX_EmptyThisBuffer() in the OpenMax IL standard.
+     */
+    emptyBuffer(
+            BufferId buffer,
+            CodecBuffer omxBuffer,
+            uint32_t flags, // TODO: describe structure better or point at standard
+            uint64_t timestampUs,
+            Fence fence
+        ) generates (
+            Status status
+        );
+
+    /**
+     * Request the node to translate an extension string to an index.
+     *
+     * @param[in] parameterName is the requested extension string.
+     * @param[out] status is the status of the call.
+     * @param[out] index is the translated index.
+     *
+     * @see OMX_GetExtensionIndex() in the OpenMax IL standard.
+     */
+    getExtensionIndex(
+            string parameterName
+        ) generates (
+            Status status,
+            uint32_t index
+        );
+
+    /**
+     * Add an OMX message on the node's message queue. The instance of
+     * IOmxObserver that was obtained during the creation of the node will
+     * receive the message in batches by the callback
+     * IOmxObserver::onMessages().
+     *
+     * @param[in] msg is the message to send.
+     * @param[out] status is the status of the call.
+     *
+     * @see IOmxObserver::onMessages().
+     */
+    dispatchMessage(
+            Message msg
+        ) generates (
+            Status status
+        );
+
+};
+
diff --git a/media/omx/1.0/IOmxObserver.hal b/media/omx/1.0/IOmxObserver.hal
new file mode 100644 (file)
index 0000000..c26a937
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * 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 android.hardware.media.omx@1.0;
+
+/**
+ * Ref: frameworks/av/include/media/IOMX.h: IOMXObserver
+ */
+
+/**
+ * IOmxObserver is a listener interface for OMX messages sent from an IOmxNode
+ * stance.
+ */
+interface IOmxObserver {
+
+    /**
+     * Invoked to process messages from an IOmxNode instance. Note that messages
+     * come in batches.
+     */
+    oneway onMessages(vec<Message> messages);
+};
+
diff --git a/media/omx/1.0/types.hal b/media/omx/1.0/types.hal
new file mode 100644 (file)
index 0000000..c0350de
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * 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 android.hardware.media.omx@1.0;
+
+import android.hardware.media@1.0::types;
+
+// Aliases
+typedef uint32_t BufferId;
+
+/**
+ * Ref: frameworks/av/include/media/IOMX.h: omx_message
+ *
+ * Data structure for an OMX message. This is essentially a union of different
+ * message types.
+ */
+struct Message {
+
+    /**
+     * There are four main types of messages.
+     */
+    enum Type : uint32_t {
+        EVENT,
+        EMPTY_BUFFER_DONE,
+        FILL_BUFFER_DONE,
+        FRAME_RENDERED,
+    };
+
+    /**
+     * @see OMX_EVENTTYPE in the OpenMax IL standard.
+     */
+    struct EventData {
+        uint32_t event; // TODO: if there are common core events, convert to an enum or point to std
+        uint32_t data1;
+        uint32_t data2;
+        uint32_t data3;
+        uint32_t data4;
+    };
+
+    struct BufferData {
+        BufferId buffer;
+    };
+
+    struct ExtendedBufferData {
+        BufferId buffer;
+        uint32_t rangeOffset;
+        uint32_t rangeLength;
+        uint32_t flags; // TODO: if common flags exist, define an enum of point to std
+        uint64_t timestampUs;
+    };
+
+    struct RenderData {
+        uint64_t timestampUs;
+        int64_t systemTimeNs;
+    };
+
+    union Data {
+        // if type == EVENT
+        EventData eventData;
+
+        // if type == EMPTY_BUFFER_DONE
+        BufferData bufferData;
+
+        // if type == FILL_BUFFER_DONE
+        ExtendedBufferData extendedBufferData;
+
+        // if type == FRAME_RENDERED
+        RenderData renderData;
+    };
+
+    /**
+     * The type of the message.
+     */
+    Type type;
+
+    /**
+     * The fence associated with the message.
+     */
+    Fence fence;
+
+    /**
+     * The union of data, discriminated by type.
+     */
+    Data data;
+};
+
+/**
+ * Ref: frameworks/native/include/ui/GraphicBuffer.h
+ * Ref: system/core/include/system/window.h
+ * Ref: frameworks/native/include/binder/IMemory.h
+ * Ref: frameworks/native/libs/binder/IMemory.cpp
+ * Ref: frameworks/av/include/media/OMXBuffer.h
+ *
+ * Data structure for buffer information. This is essentially a union of
+ * different buffer types.
+ */
+struct CodecBuffer {
+
+    /**
+     * There are four main types of buffers.
+     */
+    enum Type {
+        INVALID = 0,
+        PRESET,
+        SHARED_MEM,
+        ANW_BUFFER,
+        NATIVE_HANDLE
+    };
+
+    struct PresetAttributes {
+        uint32_t rangeLength;
+    };
+
+    union Attributes {
+        // if bufferType == PRESET
+        PresetAttributes preset;
+
+        // if bufferType == SHARED_MEM
+        SharedMemoryAttributes sharedMem;
+
+        // if bufferType == ANW_BUFFER
+        GraphicBufferAttributes anwBuffer;
+
+        // if bufferType == NATIVE_HANDLE
+        // No additional attributes.
+    };
+
+    /**
+     * Type of the buffer.
+     */
+    Type type;
+
+    /**
+     * Attributes that can be put into a union.
+     */
+    Attributes attr;
+
+    /**
+     * \p nativeHandle is used only for types SHARED_MEM, ANW_BUFFER and
+     * NATIVE_HANDLE.
+     *
+     * (A native handle cannot be put into a union as HIDL currently does not
+     * support discriminated unions.)
+     */
+    handle nativeHandle;
+
+};
+
+/**
+ * Ref: frameworks/av/include/media/IOMX.h
+ *
+ * Enumeration of port modes.
+ */
+enum PortMode {
+    PRESET_START = 0,
+    PRESET_BYTE_BUFFER,
+    PRESET_ANW_BUFFER,
+    PRESET_SECURE_BUFFER,
+    PRESET_END,
+    DYNAMIC_START = 100,
+    DYNAMIC_ANW_BUFFER,
+    DYNAMIC_NATIVE_HANDLE,
+    DYNAMIC_END
+};
+
diff --git a/memtrack/1.0/Android.bp b/memtrack/1.0/Android.bp
new file mode 100644 (file)
index 0000000..83c09cf
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.memtrack@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.memtrack@1.0",
+    srcs: [
+        "types.hal",
+        "IMemtrack.hal",
+    ],
+    out: [
+        "android/hardware/memtrack/1.0/types.cpp",
+        "android/hardware/memtrack/1.0/MemtrackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.memtrack@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.memtrack@1.0",
+    srcs: [
+        "types.hal",
+        "IMemtrack.hal",
+    ],
+    out: [
+        "android/hardware/memtrack/1.0/types.h",
+        "android/hardware/memtrack/1.0/IMemtrack.h",
+        "android/hardware/memtrack/1.0/IHwMemtrack.h",
+        "android/hardware/memtrack/1.0/BnMemtrack.h",
+        "android/hardware/memtrack/1.0/BpMemtrack.h",
+        "android/hardware/memtrack/1.0/BsMemtrack.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.memtrack@1.0",
+    generated_sources: ["android.hardware.memtrack@1.0_genc++"],
+    generated_headers: ["android.hardware.memtrack@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.memtrack@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/memtrack/1.0/Android.mk b/memtrack/1.0/Android.mk
new file mode 100644 (file)
index 0000000..4abe505
--- /dev/null
@@ -0,0 +1,204 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.memtrack@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (MemtrackFlag)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemtrackRecord)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackRecord.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackRecord
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemtrackStatus)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemtrackType)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IMemtrack.hal
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/IMemtrack.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IMemtrack.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::IMemtrack
+
+$(GEN): $(LOCAL_PATH)/IMemtrack.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.memtrack@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (MemtrackFlag)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemtrackRecord)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackRecord.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackRecord
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemtrackStatus)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MemtrackType)
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/MemtrackType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::types.MemtrackType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IMemtrack.hal
+#
+GEN := $(intermediates)/android/hardware/memtrack/1.0/IMemtrack.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IMemtrack.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.memtrack@1.0::IMemtrack
+
+$(GEN): $(LOCAL_PATH)/IMemtrack.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/memtrack/1.0/IMemtrack.hal b/memtrack/1.0/IMemtrack.hal
new file mode 100644 (file)
index 0000000..ae9d960
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * 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 android.hardware.memtrack@1.0;
+
+/*
+ * The Memory Tracker HAL is designed to return information about
+ * device-specific memory usage.
+ * The primary goal is to be able to track memory that is not
+ * trackable in any other way, for example texture memory that is allocated by
+ * a process, but not mapped in to that process's address space.
+ * A secondary goal is to be able to categorize memory used by a process into
+ * GL, graphics, etc. All memory sizes must be in real memory usage,
+ * accounting for stride, bit depth, rounding up to page size, etc.
+ *
+ * Constructor for the interface should be used to perform memtrack management
+ * setup actions and is called once before any calls to getMemory().
+ */
+interface IMemtrack {
+    /*
+     * getMemory() populates MemtrackRecord vector with the sizes of memory
+     * plus associated flags for that memory.
+     *
+     * This function must be thread-safe, it may get called from multiple
+     * threads at the same time.
+     *
+     * A process collecting memory statistics will call getMemory for each
+     * combination of pid and memory type. For each memory type that it
+     * recognizes, the HAL must fill out an array of memtrack_record
+     * structures breaking down the statistics of that memory type as much as
+     * possible. For example,
+     * getMemory(<pid>, GL) might return:
+     * { { 4096,  ACCOUNTED | PRIVATE | SYSTEM },
+     *   { 40960, UNACCOUNTED | PRIVATE | SYSTEM },
+     *   { 8192,  ACCOUNTED | PRIVATE | DEDICATED },
+     *   { 8192,  UNACCOUNTED | PRIVATE | DEDICATED } }
+     * If the HAL cannot differentiate between SYSTEM and DEDICATED memory, it
+     * could return:
+     * { { 12288,  ACCOUNTED | PRIVATE },
+     *   { 49152,  UNACCOUNTED | PRIVATE } }
+     *
+     * Memory must not overlap between types. For example, a graphics buffer
+     * that has been mapped into the GPU as a surface must show up when
+     * GRAPHICS is requested and not when GL
+     * is requested.
+     *
+     * @param pid process for which memory information is requested
+     * @param type memory type that information is being requested about
+     * @return records vector of MemtrackRecord containing memory information
+     * @return retval SUCCESS on success, TYPE_NOT_FOUND if the type is not
+     * supported.
+     */
+    getMemory(int32_t pid, MemtrackType type)
+            generates (MemtrackStatus retval, vec<MemtrackRecord> records);
+};
diff --git a/memtrack/1.0/default/Android.bp b/memtrack/1.0/default/Android.bp
new file mode 100644 (file)
index 0000000..50d2318
--- /dev/null
@@ -0,0 +1,49 @@
+// 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.
+
+cc_library_shared {
+    name: "android.hardware.memtrack@1.0-impl",
+    relative_install_path: "hw",
+    srcs: ["Memtrack.cpp"],
+
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libhidl",
+        "libhardware",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.memtrack@1.0",
+    ],
+
+}
+
+cc_binary {
+    relative_install_path: "hw",
+    name: "android.hardware.memtrack@1.0-service",
+    init_rc: ["android.hardware.memtrack@1.0-service.rc"],
+    srcs: ["service.cpp"],
+
+    shared_libs: [
+        "liblog",
+        "libbase",
+        "libdl",
+        "libutils",
+        "libhardware",
+        "libhidl",
+        "libhwbinder",
+        "android.hardware.memtrack@1.0",
+    ],
+
+}
diff --git a/memtrack/1.0/default/Memtrack.cpp b/memtrack/1.0/default/Memtrack.cpp
new file mode 100644 (file)
index 0000000..b953e7c
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.memtrack@1.0-impl"
+#include <hardware/hardware.h>
+#include <hardware/memtrack.h>
+
+#include "Memtrack.h"
+namespace android {
+namespace hardware {
+namespace memtrack {
+namespace V1_0 {
+namespace implementation {
+
+Memtrack::Memtrack(memtrack_module_t *module) : mModule(module) {
+    if (mModule)
+        mModule->init(mModule);
+}
+
+Memtrack::~Memtrack() {
+    delete(mModule);
+}
+
+Return<void> Memtrack::getMemory(int32_t pid, MemtrackType type,
+        getMemory_cb _hidl_cb)  {
+    hidl_vec<MemtrackRecord> records;
+    size_t temp = 0;
+    size_t *size = &temp;
+    int ret = 0;
+
+    if (mModule->getMemory == nullptr)
+    {
+        _hidl_cb(MemtrackStatus::SUCCESS, records);
+        return Void();
+    }
+    ret = mModule->getMemory(mModule, pid, static_cast<memtrack_type>(type),
+            NULL, size);
+    if (ret == 0)
+    {
+        memtrack_record *legacy_records = new memtrack_record[*size];
+        ret = mModule->getMemory(mModule, pid,
+                static_cast<memtrack_type>(type), legacy_records, size);
+        if (ret == 0)
+        {
+            records.resize(*size);
+            for(size_t i = 0; i < *size; i++)
+            {
+                records[i].sizeInBytes = legacy_records[i].size_in_bytes;
+                records[i].flags = legacy_records[i].flags;
+            }
+        }
+        delete[] legacy_records;
+    }
+    _hidl_cb(MemtrackStatus::SUCCESS, records);
+    return Void();
+}
+
+
+IMemtrack* HIDL_FETCH_IMemtrack(const char* name) {
+    int ret = 0;
+    const hw_module_t* hw_module = NULL;
+    memtrack_module_t *memtrack_module = NULL;
+
+    ret = hw_get_module(name, &hw_module);
+    if (ret == 0 && hw_module->methods->open > 0)
+    {
+        ret = hw_module->methods->open(hw_module, name,
+                reinterpret_cast<hw_device_t**>(&memtrack_module));
+        if (ret == 0)
+                return new Memtrack(memtrack_module);
+        else {
+            ALOGE("Passthrough failed to load legacy HAL.");
+        }
+    }
+    else {
+        ALOGE ("hw_get_module %s failed: %d", name, ret);
+    }
+    return nullptr;
+}
+
+} // namespace implementation
+}  // namespace V1_0
+}  // namespace memtrack
+}  // namespace hardware
+}  // namespace android
diff --git a/memtrack/1.0/default/Memtrack.h b/memtrack/1.0/default/Memtrack.h
new file mode 100644 (file)
index 0000000..86dae72
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_memtrack_V1_0_Memtrack_H_
+#define HIDL_GENERATED_android_hardware_memtrack_V1_0_Memtrack_H_
+
+#include <android/hardware/memtrack/1.0/IMemtrack.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+namespace android {
+namespace hardware {
+namespace memtrack {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::memtrack::V1_0::IMemtrack;
+using ::android::hardware::memtrack::V1_0::MemtrackRecord;
+using ::android::hardware::memtrack::V1_0::MemtrackStatus;
+using ::android::hardware::memtrack::V1_0::MemtrackType;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Memtrack : public IMemtrack {
+    Memtrack(memtrack_module_t* module);
+    ~Memtrack();
+    Return<void> getMemory(int32_t pid, MemtrackType type, getMemory_cb _hidl_cb)  override;
+
+  private:
+    memtrack_module_t* mModule;
+};
+
+extern "C" IMemtrack* HIDL_FETCH_IMemtrack(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace memtrack
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_memtrack_V1_0_Memtrack_H_
diff --git a/memtrack/1.0/default/android.hardware.memtrack@1.0-service.rc b/memtrack/1.0/default/android.hardware.memtrack@1.0-service.rc
new file mode 100644 (file)
index 0000000..14e7d00
--- /dev/null
@@ -0,0 +1,4 @@
+service memtrack-hal-1-0 /system/bin/hw/android.hardware.memtrack@1.0-service
+    class hal
+    user system
+    group system
diff --git a/memtrack/1.0/default/service.cpp b/memtrack/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..f705b15
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.memtrack@1.0-service"
+
+#include <android/hardware/memtrack/1.0/IMemtrack.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::memtrack::V1_0::IMemtrack;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IMemtrack>("memtrack");
+}
diff --git a/memtrack/1.0/types.hal b/memtrack/1.0/types.hal
new file mode 100644 (file)
index 0000000..3d702b3
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * 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 android.hardware.memtrack@1.0;
+
+/*
+ * SMAPS_ACCOUNTED/SMAPS_UNACCOUNTED
+ * Flags to differentiate memory that can already be accounted for in
+ * /proc/<pid>/smaps,
+ * (Shared_Clean + Shared_Dirty + Private_Clean + Private_Dirty = Size).
+ * In general, memory mapped in to a userspace process is accounted unless
+ * it was mapped with remap_pfn_range.
+ * Exactly one of these must be set.
+ *
+ * SHARED/SHARED_PSS/PRIVATE
+ * Flags to differentiate memory shared across multiple processes vs. memory
+ * used by a single process.
+ * If SHARED_PSS flags is used, the memory must be divided by the number of
+ * processes holding reference to it (shared / num_processes).
+ * Only zero or one of these may be set in a record.
+ * If none are set, record is assumed to count shared + private memory.
+ *
+ * SYSTEM/DEDICATED
+ * Flags to differentiate memory taken from the kernel's allocation pool vs.
+ * memory that is dedicated to non-kernel allocations, for example a carveout
+ * or separate video memory.  Only zero or one of these may be set in a record.
+ * If none are set, record is assumed to count system + dedicated memory.
+ *
+ * NONSECURE/SECURE
+ * Flags to differentiate memory accessible by the CPU in non-secure mode vs.
+ * memory that is protected.  Only zero or one of these may be set in a record.
+ * If none are set, record is assumed to count secure + nonsecure memory.
+ */
+enum MemtrackFlag : uint32_t {
+    SMAPS_ACCOUNTED = 1 << 1,
+    SMAPS_UNACCOUNTED = 1 << 2,
+    SHARED = 1 << 3,
+    SHARED_PSS = 1 << 4,
+    PRIVATE = 1 << 5,
+    SYSTEM = 1 << 6,
+    DEDICATED = 1 << 7,
+    NONSECURE = 1 << 8,
+    SECURE = 1 << 9,
+};
+
+/* Tags which define the usage of the memory buffers. */
+enum MemtrackType : uint32_t {
+    OTHER = 0,
+    GL = 1,
+    GRAPHICS = 2,
+    MULTIMEDIA = 3,
+    CAMERA = 4,
+    NUM_TYPES,
+};
+
+enum MemtrackStatus : uint32_t {
+    SUCCESS = 0,
+    MEMORY_TRACKING_NOT_SUPPORTED = 1,
+    TYPE_NOT_SUPPORTED = 2,
+};
+
+/* A vector of MemtrackRecord is returned by the function getMemory().
+ * Each record consists of the size of the memory used by the process and
+ * flags indicate the all the MemtrackFlag that are valid for this record.
+ * see getMemory() comments for further details.
+ */
+struct MemtrackRecord {
+    uint64_t sizeInBytes;
+    /*
+     * This is the bitfield for the MemtrackFlag indicating all the flags that
+     * are valid for this record.
+     */
+    uint32_t flags;
+};
diff --git a/memtrack/1.0/vts/Android.mk b/memtrack/1.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..c0fe968
--- /dev/null
@@ -0,0 +1,87 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for memtrack v1.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_memtrack@1.0
+
+LOCAL_SRC_FILES := \
+  Memtrack.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES := \
+  android.hardware.memtrack@1.0 \
+  system/core/base/include \
+  system/core/include \
+
+LOCAL_SHARED_LIBRARIES += \
+  android.hardware.memtrack@1.0 \
+  libbase \
+  libutils \
+  libcutils \
+  liblog \
+  libhidl \
+  libhwbinder \
+  libprotobuf-cpp-full \
+  libvts_common \
+  libvts_datatype \
+  libvts_measurement \
+  libvts_multidevice_proto \
+
+LOCAL_CFLAGS += -DENABLE_TREBLE
+
+LOCAL_STATIC_LIBRARIES := \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for memtrack.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_memtrack@1.0
+
+LOCAL_SRC_FILES := \
+  Memtrack.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.memtrack@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
+
diff --git a/memtrack/1.0/vts/Memtrack.vts b/memtrack/1.0/vts/Memtrack.vts
new file mode 100644 (file)
index 0000000..9fce2a0
--- /dev/null
@@ -0,0 +1,33 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "IMemtrack"
+
+package: "android.hardware.memtrack"
+
+import: "android.hardware.memtrack@1.0::types"
+
+interface: {
+    api: {
+        name: "getMemory"
+        return_type_hidl: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::memtrack::V1_0::MemtrackStatus"
+        }
+        return_type_hidl: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_STRUCT
+                predefined_type: "::android::hardware::memtrack::V1_0::MemtrackRecord"
+            }
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        arg: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::memtrack::V1_0::MemtrackType"
+        }
+    }
+
+}
diff --git a/memtrack/1.0/vts/types.vts b/memtrack/1.0/vts/types.vts
new file mode 100644 (file)
index 0000000..bec090f
--- /dev/null
@@ -0,0 +1,121 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "types"
+
+package: "android.hardware.memtrack"
+
+
+attribute: {
+    name: "::android::hardware::memtrack::V1_0::MemtrackFlag"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "SMAPS_ACCOUNTED"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "SMAPS_UNACCOUNTED"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "SHARED"
+        scalar_value: {
+            uint32_t: 8
+        }
+        enumerator: "SHARED_PSS"
+        scalar_value: {
+            uint32_t: 16
+        }
+        enumerator: "PRIVATE"
+        scalar_value: {
+            uint32_t: 32
+        }
+        enumerator: "SYSTEM"
+        scalar_value: {
+            uint32_t: 64
+        }
+        enumerator: "DEDICATED"
+        scalar_value: {
+            uint32_t: 128
+        }
+        enumerator: "NONSECURE"
+        scalar_value: {
+            uint32_t: 256
+        }
+        enumerator: "SECURE"
+        scalar_value: {
+            uint32_t: 512
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::memtrack::V1_0::MemtrackType"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "OTHER"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "GL"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "GRAPHICS"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "MULTIMEDIA"
+        scalar_value: {
+            uint32_t: 3
+        }
+        enumerator: "CAMERA"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "NUM_TYPES"
+        scalar_value: {
+            uint32_t: 5
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::memtrack::V1_0::MemtrackStatus"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "SUCCESS"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "MEMORY_TRACKING_NOT_SUPPORTED"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "TYPE_NOT_SUPPORTED"
+        scalar_value: {
+            uint32_t: 2
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::memtrack::V1_0::MemtrackRecord"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "sizeInBytes"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+    struct_value: {
+        name: "flags"
+        type: TYPE_SCALAR
+        scalar_type: "uint32_t"
+    }
+}
+
diff --git a/memtrack/Android.bp b/memtrack/Android.bp
new file mode 100644 (file)
index 0000000..ba90f2c
--- /dev/null
@@ -0,0 +1,5 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+    "1.0/default",
+]
diff --git a/nfc/1.0/vts/Android.mk b/nfc/1.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..6f63e03
--- /dev/null
@@ -0,0 +1,118 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for Nfc v1.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_nfc@1.0
+
+LOCAL_SRC_FILES := \
+  Nfc.vts \
+  NfcClientCallback.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES := \
+  android.hardware.nfc@1.0 \
+  system/core/base/include \
+  system/core/include \
+
+LOCAL_SHARED_LIBRARIES += \
+  android.hardware.nfc@1.0 \
+  libbase \
+  libutils \
+  libcutils \
+  liblog \
+  libhidl \
+  libhwbinder \
+  libprotobuf-cpp-full \
+  libvts_common \
+  libvts_datatype \
+  libvts_measurement \
+  libvts_multidevice_proto \
+
+LOCAL_CFLAGS += -DENABLE_TREBLE
+
+LOCAL_STATIC_LIBRARIES := \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for Nfc.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_nfc@1.0
+
+LOCAL_SRC_FILES := \
+   Nfc.vts \
+   types.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.nfc@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for NfcClientCallback.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_nfc_client_callback_@1.0
+
+LOCAL_SRC_FILES := \
+   NfcClientCallback.vts \
+   types.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.nfc@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/nfc/1.0/vts/Nfc.vts b/nfc/1.0/vts/Nfc.vts
new file mode 100644 (file)
index 0000000..c2313d5
--- /dev/null
@@ -0,0 +1,133 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "INfc"
+
+package: "android.hardware.nfc"
+
+import: "android.hardware.nfc@1.0::INfcClientCallback"
+import: "android.hardware.nfc@1.0::types"
+
+interface: {
+    api: {
+        name: "open"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        arg: {
+            type: TYPE_HIDL_CALLBACK
+            predefined_type: "INfcClientCallback"
+            is_callback: true
+        }
+        callflow: {
+            entry: true
+        }
+        callflow: {
+            next: "write"
+            next: "coreInitialized"
+            next: "prediscover"
+            next: "powerCycle"
+            next: "controlGranted"
+        }
+    }
+
+    api: {
+        name: "write"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        arg: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_SCALAR
+                scalar_type: "uint8_t"
+            }
+        }
+        callflow: {
+            next: "write"
+            next: "prediscover"
+            next: "coreInitialized"
+            next: "close"
+            next: "powerCycle"
+            next: "controlGranted"
+        }
+    }
+
+    api: {
+        name: "coreInitialized"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        arg: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_SCALAR
+                scalar_type: "uint8_t"
+            }
+        }
+        callflow: {
+            next: "write"
+            next: "prediscover"
+            next: "close"
+        }
+    }
+
+    api: {
+        name: "prediscover"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        callflow: {
+            next: "write"
+            next: "close"
+            next: "coreInitialized"
+            next: "powerCycle"
+            next: "controlGranted"
+        }
+    }
+
+    api: {
+        name: "close"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        callflow: {
+            exit: true
+        }
+    }
+
+    api: {
+        name: "controlGranted"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        callflow: {
+            next: "write"
+            next: "close"
+            next: "prediscover"
+            next: "coreInitialized"
+            next: "powerCycle"
+        }
+    }
+
+    api: {
+        name: "powerCycle"
+        return_type_hidl: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+        callflow: {
+            next: "write"
+            next: "coreInitialized"
+            next: "prediscover"
+            next: "controlGranted"
+            next: "close"
+        }
+    }
+
+}
diff --git a/nfc/1.0/vts/NfcClientCallback.vts b/nfc/1.0/vts/NfcClientCallback.vts
new file mode 100644 (file)
index 0000000..e39ea7c
--- /dev/null
@@ -0,0 +1,33 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "INfcClientCallback"
+
+package: "android.hardware.nfc"
+
+import: "android.hardware.nfc@1.0::types"
+
+interface: {
+    api: {
+        name: "sendEvent"
+        arg: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::nfc::V1_0::NfcEvent"
+        }
+        arg: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::nfc::V1_0::NfcStatus"
+        }
+    }
+
+    api: {
+        name: "sendData"
+        arg: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_SCALAR
+                scalar_type: "uint8_t"
+            }
+        }
+    }
+
+}
diff --git a/nfc/1.0/vts/functional/Android.bp b/nfc/1.0/vts/functional/Android.bp
new file mode 100644 (file)
index 0000000..0f1afbd
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// 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.
+//
+
+cc_test {
+    name: "nfc_hidl_hal_test",
+    gtest: true,
+    srcs: ["nfc_hidl_hal_test.cpp"],
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libcutils",
+        "libhidl",
+        "libhwbinder",
+        "libnativehelper",
+        "libutils",
+        "android.hardware.nfc@1.0",
+    ],
+    static_libs: ["libgtest"],
+    cflags: [
+        "-O0",
+        "-g",
+    ],
+}
\ No newline at end of file
diff --git a/nfc/1.0/vts/functional/nfc_hidl_hal_test.cpp b/nfc/1.0/vts/functional/nfc_hidl_hal_test.cpp
new file mode 100644 (file)
index 0000000..e215704
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "nfc_hidl_hal_test"
+#include <android-base/logging.h>
+
+#include <hardware/nfc.h>
+#include <android/hardware/nfc/1.0/types.h>
+#include <android/hardware/nfc/1.0/INfc.h>
+#include <android/hardware/nfc/1.0/INfcClientCallback.h>
+
+#include <gtest/gtest.h>
+
+using ::android::hardware::nfc::V1_0::INfc;
+using ::android::hardware::nfc::V1_0::INfcClientCallback;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::sp;
+
+#define NFC_NCI_SERVICE_NAME "nfc_nci"
+
+
+// Simple NfcClientCallback used as part of testing.
+class NfcClientCallback : public INfcClientCallback {
+  public:
+   NfcClientCallback() {};
+
+   virtual ~NfcClientCallback() = default;
+
+   // sendEvent callback function - currently no-op.
+   Return<void> sendEvent(
+           ::android::hardware::nfc::V1_0::NfcEvent event,
+           ::android::hardware::nfc::V1_0::NfcStatus event_status) override {
+     return Void();
+   };
+
+   // sendData callback function - currently no-op.
+   Return<void> sendData(const ::android::hardware::nfc::V1_0::NfcData &data ) override {
+     ::android::hardware::nfc::V1_0::NfcData copy = data;
+     return Void();
+   };
+};
+
+
+// The main test class for NFC HIDL HAL.
+class NfcHidlTest : public ::testing::Test {
+ public:
+  virtual void SetUp() override {
+    // currently test passthrough mode only
+    nfc = INfc::getService(NFC_NCI_SERVICE_NAME, true);
+    ASSERT_NE(nfc, nullptr);
+
+    nfc_cb = new NfcClientCallback();
+    ASSERT_NE(nfc_cb, nullptr);
+  }
+
+  virtual void TearDown() override {}
+
+  sp<INfc> nfc;
+  sp<INfcClientCallback> nfc_cb;
+};
+
+
+// A class for test environment setup (kept since this file is a template).
+class NfcHidlEnvironment : public ::testing::Environment {
+ public:
+  virtual void SetUp() {}
+  virtual void TearDown() {}
+
+ private:
+};
+
+TEST_F(NfcHidlTest, OpenAndClose) {
+  EXPECT_EQ(0, (int)nfc->open(nfc_cb));
+  EXPECT_EQ(0, (int)nfc->close());
+}
+
+int main(int argc, char **argv) {
+  ::testing::AddGlobalTestEnvironment(new NfcHidlEnvironment);
+  ::testing::InitGoogleTest(&argc, argv);
+  int status = RUN_ALL_TESTS();
+  ALOGI("Test result = %d", status);
+  return status;
+}
diff --git a/nfc/1.0/vts/types.vts b/nfc/1.0/vts/types.vts
new file mode 100644 (file)
index 0000000..e43db1e
--- /dev/null
@@ -0,0 +1,73 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "types"
+
+package: "android.hardware.nfc"
+
+
+attribute: {
+    name: "::android::hardware::nfc::V1_0::NfcEvent"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "OPEN_CPLT"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "CLOSE_CPLT"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "POST_INIT_CPLT"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "PRE_DISCOVER_CPLT"
+        scalar_value: {
+            uint32_t: 3
+        }
+        enumerator: "REQUEST_CONTROL"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "RELEASE_CONTROL"
+        scalar_value: {
+            uint32_t: 5
+        }
+        enumerator: "ERROR"
+        scalar_value: {
+            uint32_t: 6
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::nfc::V1_0::NfcStatus"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "OK"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "FAILED"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "ERR_TRANSPORT"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "ERR_CMD_TIMEOUT"
+        scalar_value: {
+            uint32_t: 3
+        }
+        enumerator: "REFUSED"
+        scalar_value: {
+            uint32_t: 4
+        }
+    }
+}
+
index ba90f2c..ed19a37 100644 (file)
@@ -2,4 +2,5 @@
 subdirs = [
     "1.0",
     "1.0/default",
+    "1.0/vts/functional",
 ]
diff --git a/power/1.0/Android.bp b/power/1.0/Android.bp
new file mode 100644 (file)
index 0000000..a671474
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.power@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.power@1.0",
+    srcs: [
+        "types.hal",
+        "IPower.hal",
+    ],
+    out: [
+        "android/hardware/power/1.0/types.cpp",
+        "android/hardware/power/1.0/PowerAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.power@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.power@1.0",
+    srcs: [
+        "types.hal",
+        "IPower.hal",
+    ],
+    out: [
+        "android/hardware/power/1.0/types.h",
+        "android/hardware/power/1.0/IPower.h",
+        "android/hardware/power/1.0/IHwPower.h",
+        "android/hardware/power/1.0/BnPower.h",
+        "android/hardware/power/1.0/BpPower.h",
+        "android/hardware/power/1.0/BsPower.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.power@1.0",
+    generated_sources: ["android.hardware.power@1.0_genc++"],
+    generated_headers: ["android.hardware.power@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.power@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/power/1.0/Android.mk b/power/1.0/Android.mk
new file mode 100644 (file)
index 0000000..5f1260b
--- /dev/null
@@ -0,0 +1,238 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.power@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (Feature)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/Feature.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.Feature
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PowerHint)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/PowerHint.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.PowerHint
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PowerStatePlatformSleepState)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/PowerStatePlatformSleepState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.PowerStatePlatformSleepState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PowerStateVoter)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/PowerStateVoter.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.PowerStateVoter
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Status)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/Status.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.Status
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IPower.hal
+#
+GEN := $(intermediates)/android/hardware/power/1.0/IPower.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IPower.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::IPower
+
+$(GEN): $(LOCAL_PATH)/IPower.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.power@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (Feature)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/Feature.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.Feature
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PowerHint)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/PowerHint.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.PowerHint
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PowerStatePlatformSleepState)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/PowerStatePlatformSleepState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.PowerStatePlatformSleepState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (PowerStateVoter)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/PowerStateVoter.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.PowerStateVoter
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Status)
+#
+GEN := $(intermediates)/android/hardware/power/1.0/Status.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::types.Status
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IPower.hal
+#
+GEN := $(intermediates)/android/hardware/power/1.0/IPower.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IPower.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.power@1.0::IPower
+
+$(GEN): $(LOCAL_PATH)/IPower.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/power/1.0/IPower.hal b/power/1.0/IPower.hal
new file mode 100644 (file)
index 0000000..6cba42a
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * 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 android.hardware.power@1.0;
+
+/*
+ * Constructor for the interface performs power management setup actions at
+ * runtime startup, such as to set default cpufreq parameters.
+ */
+interface IPower {
+    /*
+     * setInteractive() performs power management actions upon the
+     * system entering interactive state (that is, the system is awake
+     * and ready for interaction, often with UI devices such as
+     * display and touchscreen enabled) or non-interactive state (the
+     * system appears asleep, display usually turned off). The
+     * non-interactive state may be entered after a period of
+     * inactivity in order to conserve battery power during
+     * such inactive periods.
+     *
+     * Typical actions are to turn on or off devices and adjust
+     * cpufreq parameters. This function may also call the
+     * appropriate interfaces to allow the kernel to suspend the
+     * system to low-power sleep state when entering non-interactive
+     * state, and to disallow low-power suspend when the system is in
+     * interactive state. When low-power suspend state is allowed, the
+     * kernel may suspend the system whenever no wakelocks are held.
+     *
+     * For example,
+     * This function can be called to enter non-interactive state after
+     * turning off the screen (if present) and called to enter
+     * interactive state prior to turning on the screen.
+     *
+     * @param interactive is true when the system is transitioning to an
+     * interactive state and false when transitioning to a
+     * non-interactive state.
+     */
+    setInteractive(bool interactive);
+
+    /*
+     * powerHint() is called to pass hints on power requirements which
+     * may result in adjustment of power/performance parameters of the
+     * cpufreq governor and other controls.
+     *
+     * A particular platform may choose to ignore any hint.
+     *
+     * @param hint PowerHint which is passed
+     * @param data contains additional information about the hint
+     * and is described along with the comments for each of the hints.
+     */
+    powerHint(PowerHint hint, int32_t data);
+
+    /*
+     * setFeature() is called to turn on or off a particular feature
+     * depending on the state parameter.
+     *
+     * @param feature Feature which needs to be set
+     * @param activate true/false to enable/disable the feature
+     */
+    setFeature(Feature feature, bool activate);
+
+    /*
+     * Platform-level sleep state stats:
+     * Report cumulative info on the statistics on platform-level sleep states
+     * since boot.
+     *
+     * Higher the index in the returned <states> vector deeper the state is
+     * i.e. lesser steady-state power is consumed by the platform to be
+     * resident in that state.
+     *
+     * @return states of power states the device supports
+     * @return retval SUCCESS on success or FILESYSTEM_ERROR on filesystem
+     * nodes access error.
+     */
+    getPlatformLowPowerStats()
+            generates (vec<PowerStatePlatformSleepState> states, Status retval);
+};
diff --git a/power/1.0/default/Android.bp b/power/1.0/default/Android.bp
new file mode 100644 (file)
index 0000000..e573186
--- /dev/null
@@ -0,0 +1,47 @@
+// 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.
+
+cc_library_shared {
+    name: "android.hardware.power@1.0-impl",
+    relative_install_path: "hw",
+    srcs: ["Power.cpp"],
+
+    shared_libs: [
+        "liblog",
+        "libhardware",
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.power@1.0",
+    ],
+
+}
+
+cc_binary {
+    relative_install_path: "hw",
+    name: "android.hardware.power@1.0-service",
+    init_rc: ["android.hardware.power@1.0-service.rc"],
+    srcs: ["service.cpp"],
+
+    shared_libs: [
+        "liblog",
+        "libdl",
+        "libutils",
+        "libhardware",
+        "libhidl",
+        "libhwbinder",
+        "android.hardware.power@1.0",
+    ],
+
+}
diff --git a/power/1.0/default/Power.cpp b/power/1.0/default/Power.cpp
new file mode 100644 (file)
index 0000000..5d0593b
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.power@1.0-impl"
+#include <hardware/hardware.h>
+#include <hardware/power.h>
+#include "Power.h"
+
+namespace android {
+namespace hardware {
+namespace power {
+namespace V1_0 {
+namespace implementation {
+
+Power::Power(power_module_t *module) : mModule(module) {
+    if (mModule)
+        mModule->init(mModule);
+}
+
+Power::~Power() {
+    delete(mModule);
+}
+
+// Methods from ::android::hardware::power::V1_0::IPower follow.
+Return<void> Power::setInteractive(bool interactive)  {
+    if (mModule->setInteractive > 0)
+        mModule->setInteractive(mModule, interactive ? 1 : 0);
+    return Void();
+}
+
+Return<void> Power::powerHint(PowerHint hint, int32_t data)  {
+    int32_t param = data;
+    if (mModule->powerHint > 0)
+        mModule->powerHint(mModule, static_cast<power_hint_t>(hint), &param);
+    return Void();
+}
+
+Return<void> Power::setFeature(Feature feature, bool activate)  {
+    if (mModule->setFeature > 0)
+        mModule->setFeature(mModule, static_cast<feature_t>(feature),
+                activate ? 1 : 0);
+    return Void();
+}
+
+Return<void> Power::getPlatformLowPowerStats(getPlatformLowPowerStats_cb _hidl_cb)  {
+    hidl_vec<PowerStatePlatformSleepState> states;
+    ssize_t number_platform_modes;
+    size_t *voters = nullptr;
+    power_state_platform_sleep_state_t *legacy_states = nullptr;
+    int ret;
+
+    if (mModule->get_number_of_platform_modes == nullptr ||
+            mModule->get_voter_list == nullptr ||
+            mModule->get_platform_low_power_stats == nullptr)
+    {
+        _hidl_cb(states, Status::SUCCESS);
+        return Void();
+    }
+
+    number_platform_modes = mModule->get_number_of_platform_modes(mModule);
+    if (number_platform_modes > 0)
+    {
+       voters = new size_t [number_platform_modes];
+       if (voters == nullptr)
+           goto done;
+
+       ret = mModule->get_voter_list(mModule, voters);
+       if (ret != 0)
+           goto done;
+
+       legacy_states = new power_state_platform_sleep_state_t [number_platform_modes];
+       if (legacy_states == nullptr)
+           goto done;
+
+       for (int i = 0; i < number_platform_modes; i++)
+       {
+          legacy_states[i].voters = nullptr;
+          legacy_states[i].voters = new power_state_voter_t [voters[i]];
+          if (legacy_states[i].voters == nullptr)
+              goto done;
+       }
+
+       ret = mModule->get_platform_low_power_stats(mModule, legacy_states);
+       if (ret != 0)
+           goto done;
+
+       states.resize(number_platform_modes);
+       for (int i = 0; i < number_platform_modes; i++)
+       {
+          power_state_platform_sleep_state_t& legacy_state = legacy_states[i];
+          PowerStatePlatformSleepState& state = states[i];
+          state.name = legacy_state.name;
+          state.residencyInMsecSinceBoot = legacy_state.residency_in_msec_since_boot;
+          state.totalTransitions = legacy_state.total_transitions;
+          state.supportedOnlyInSuspend = legacy_state.supported_only_in_suspend;
+          state.voters.resize(voters[i]);
+          for(size_t j = 0; j < voters[i]; j++)
+          {
+              state.voters[j].name = legacy_state.voters[j].name;
+              state.voters[j].totalTimeInMsecVotedForSinceBoot = legacy_state.voters[j].total_time_in_msec_voted_for_since_boot;
+              state.voters[j].totalNumberOfTimesVotedSinceBoot = legacy_state.voters[j].total_number_of_times_voted_since_boot;
+          }
+       }
+    }
+done:
+    if (legacy_states)
+    {
+        for (int i = 0; i < number_platform_modes; i++)
+        {
+            if(legacy_states[i].voters)
+                delete(legacy_states[i].voters);
+        }
+    }
+    delete[] legacy_states;
+    delete[] voters;
+    _hidl_cb(states, Status::SUCCESS);
+    return Void();
+}
+
+IPower* HIDL_FETCH_IPower(const char* name) {
+    int ret = 0;
+    const hw_module_t* hw_module = NULL;
+    power_module_t *power_module;
+    ret = hw_get_module(name, &hw_module);
+    if (ret == 0 && hw_module->methods->open > 0) {
+        ret = hw_module->methods->open(hw_module, name,
+                reinterpret_cast<hw_device_t**>(&power_module));
+        if (ret == 0) {
+            return new Power(power_module);
+        }
+        else {
+            ALOGE("Passthrough failed to load legacy HAL.");
+            return nullptr;
+        }
+    }
+    else {
+        ALOGE ("hw_get_module %s failed: %d", name, ret);
+        return nullptr;
+    }
+}
+
+} // namespace implementation
+}  // namespace V1_0
+}  // namespace power
+}  // namespace hardware
+}  // namespace android
diff --git a/power/1.0/default/Power.h b/power/1.0/default/Power.h
new file mode 100644 (file)
index 0000000..a0495be
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_power_V1_0_Power_H_
+#define HIDL_GENERATED_android_hardware_power_V1_0_Power_H_
+
+#include <android/hardware/power/1.0/IPower.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+namespace android {
+namespace hardware {
+namespace power {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::power::V1_0::Feature;
+using ::android::hardware::power::V1_0::IPower;
+using ::android::hardware::power::V1_0::PowerHint;
+using ::android::hardware::power::V1_0::PowerStatePlatformSleepState;
+using ::android::hardware::power::V1_0::Status;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Power : public IPower {
+    Power(power_module_t* module);
+    ~Power();
+    Return<void> setInteractive(bool interactive)  override;
+    Return<void> powerHint(PowerHint hint, int32_t data)  override;
+    Return<void> setFeature(Feature feature, bool activate)  override;
+    Return<void> getPlatformLowPowerStats(getPlatformLowPowerStats_cb _hidl_cb)  override;
+
+  private:
+    power_module_t* mModule;
+};
+
+extern "C" IPower* HIDL_FETCH_IPower(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace power
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_power_V1_0_Power_H_
diff --git a/power/1.0/default/android.hardware.power@1.0-service.rc b/power/1.0/default/android.hardware.power@1.0-service.rc
new file mode 100644 (file)
index 0000000..6063541
--- /dev/null
@@ -0,0 +1,4 @@
+service power-hal-1-0 /system/bin/hw/android.hardware.power@1.0-service
+    class hal
+    user system
+    group system
diff --git a/power/1.0/default/service.cpp b/power/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..f77ff5b
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.power@1.0-service"
+
+#include <android/hardware/power/1.0/IPower.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::power::V1_0::IPower;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IPower>("power");
+}
diff --git a/power/1.0/types.hal b/power/1.0/types.hal
new file mode 100644 (file)
index 0000000..c27242e
--- /dev/null
@@ -0,0 +1,168 @@
+/*
+ * 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 android.hardware.power@1.0;
+
+/* Power hint identifiers passed to powerHint() */
+enum PowerHint : uint32_t {
+   /*
+    * Foreground app has started or stopped requesting a VSYNC pulse
+    * from SurfaceFlinger. If the app has started requesting VSYNC
+    * then CPU and GPU load is expected soon, and it may be appropriate
+    * to raise speeds of CPU, memory bus, etc. The data parameter is
+    * non-zero to indicate VSYNC pulse is now requested, or zero for
+    * VSYNC pulse no longer requested.
+    */
+    VSYNC = 0x00000001,
+
+
+   /*
+    * User is interacting with the device, for example, touchscreen
+    * events are incoming. CPU and GPU load may be expected soon,
+    * and it may be appropriate to raise speeds of CPU, memory bus,
+    * etc. The data parameter is the estimated length of the interaction
+    * in milliseconds, or 0 if unknown.
+    */
+    INTERACTION = 0x00000002,
+
+
+    /* DO NOT USE VIDEO_ENCODE/_DECODE!  They will be removed in
+     * KLP.
+     */
+    VIDEO_ENCODE = 0x00000003,
+    VIDEO_DECODE = 0x00000004,
+
+   /*
+    * Low power mode is activated or deactivated. Low power mode
+    * is intended to save battery at the cost of performance. The data
+    * parameter is non-zero when low power mode is activated, and zero
+    * when deactivated.
+    */
+    LOW_POWER = 0x00000005,
+
+   /*
+    * Sustained Performance mode is actived or deactivated. Sustained
+    * performance mode is intended to provide a consistent level of
+    * performance for a prolonged amount of time. The data parameter is
+    * non-zero when sustained performance mode is activated, and zero
+    * when deactivated.
+    */
+    SUSTAINED_PERFORMANCE = 0x00000006,
+
+   /*
+    * VR Mode is activated or deactivated. VR mode is intended to
+    * provide minimum guarantee for performance for the amount of time the
+    * device can sustain it. The data parameter is non-zero when the mode
+    * is activated and zero when deactivated.
+    */
+    VR_MODE = 0x00000007,
+
+   /*
+    * This hint indicates that an application has been launched. Can be used
+    * for device specific optimizations during application launch. The data
+    * parameter is non-zero when the application starts to launch and zero when
+    * it has been launched.
+    */
+    LAUNCH = 0x00000008,
+
+   /*
+    * When device enters some special modes, e.g. theater mode in Android
+    * Wear, there is no touch interaction expected between device and user.
+    * Touch controller could be disabled in those modes to save power.
+    * The data parameter is non-zero when touch could be disabled, and zero
+    * when touch needs to be re-enabled.
+    */
+    DISABLE_TOUCH = 0x00000009
+};
+
+enum Feature : uint32_t {
+    /*
+     * Enabling/Disabling this feature will allow/disallow the system
+     * to wake up by tapping the screen twice.
+     */
+    POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 0x00000001
+};
+
+enum Status : uint32_t {
+    SUCCESS = 0,
+    FILESYSTEM_ERROR = 1
+};
+/*
+ * Platform-level sleep state stats:
+ * PowerStateVoter struct is useful for describing the individual voters
+ * when a Platform-level sleep state is chosen by aggregation of votes from
+ * multiple clients/system conditions.
+ *
+ * This helps in attirbuting what in the device is blocking the device from
+ * entering the lowest Platform-level sleep state.
+ */
+struct PowerStateVoter {
+    /*
+     * Name of the voter.
+     */
+     string name;
+
+    /*
+     * Total time in msec the voter voted for the platform sleep state since
+     * boot.
+     */
+     uint64_t totalTimeInMsecVotedForSinceBoot;
+
+    /*
+     * Number of times the voter voted for the platform sleep state since boot.
+     */
+     uint64_t totalNumberOfTimesVotedSinceBoot;
+};
+
+/*
+ * Platform-level sleep state stats:
+ * PowerStatePlatformSleepState represents the Platform-level sleep state
+ * the device is capable of getting into.
+ *
+ * SoCs usually have more than one Platform-level sleep state.
+ */
+struct PowerStatePlatformSleepState {
+    /*
+     * Platform-level Sleep state name.
+     */
+    string name;
+
+    /*
+     * Time spent in msec at this platform-level sleep state since boot.
+     */
+    uint64_t residencyInMsecSinceBoot;
+
+    /*
+     * Total number of times system entered this state.
+     */
+    uint64_t totalTransitions;
+
+    /*
+     * This platform-level sleep state can only be reached during system suspend
+     */
+    bool supportedOnlyInSuspend;
+
+    /*
+     * voters is useful if the Platform-level sleep state
+     * is chosen by aggregation votes from multiple clients/system conditions.
+     * All the voters have to say yes or all the system conditions need to be
+     * met to enter a platform-level sleep state.
+     *
+     * Vector of size zero implies either the info is not available
+     * or the system does not follow a voting mechanism to choose this
+     * Platform-level sleep state.
+     */
+    vec<PowerStateVoter> voters;
+};
diff --git a/power/1.0/vts/Android.mk b/power/1.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..4d5117b
--- /dev/null
@@ -0,0 +1,86 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for Power v1.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_power@1.0
+
+LOCAL_SRC_FILES := \
+  Power.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES := \
+  android.hardware.power@1.0 \
+  system/core/base/include \
+  system/core/include \
+
+LOCAL_SHARED_LIBRARIES += \
+  android.hardware.power@1.0 \
+  libbase \
+  libutils \
+  libcutils \
+  liblog \
+  libhidl \
+  libhwbinder \
+  libprotobuf-cpp-full \
+  libvts_common \
+  libvts_datatype \
+  libvts_measurement \
+  libvts_multidevice_proto \
+
+LOCAL_CFLAGS += -DENABLE_TREBLE
+
+LOCAL_STATIC_LIBRARIES := \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for power.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_power@1.0
+
+LOCAL_SRC_FILES := \
+   Power.vts \
+   types.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.power@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/power/1.0/vts/Power.vts b/power/1.0/vts/Power.vts
new file mode 100644 (file)
index 0000000..1711290
--- /dev/null
@@ -0,0 +1,57 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "IPower"
+
+package: "android.hardware.power"
+
+import: "android.hardware.power@1.0::types"
+
+interface: {
+    api: {
+        name: "setInteractive"
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "bool_t"
+        }
+    }
+
+    api: {
+        name: "powerHint"
+        arg: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::power::V1_0::PowerHint"
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "int32_t"
+        }
+    }
+
+    api: {
+        name: "setFeature"
+        arg: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::power::V1_0::Feature"
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "bool_t"
+        }
+    }
+
+    api: {
+        name: "getPlatformLowPowerStats"
+        return_type_hidl: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_STRUCT
+                predefined_type: "::android::hardware::power::V1_0::PowerStatePlatformSleepState"
+            }
+        }
+        return_type_hidl: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::power::V1_0::Status"
+        }
+    }
+
+}
diff --git a/power/1.0/vts/types.vts b/power/1.0/vts/types.vts
new file mode 100644 (file)
index 0000000..94c003b
--- /dev/null
@@ -0,0 +1,133 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "types"
+
+package: "android.hardware.power"
+
+
+attribute: {
+    name: "::android::hardware::power::V1_0::PowerHint"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "VSYNC"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "INTERACTION"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "VIDEO_ENCODE"
+        scalar_value: {
+            uint32_t: 3
+        }
+        enumerator: "VIDEO_DECODE"
+        scalar_value: {
+            uint32_t: 4
+        }
+        enumerator: "LOW_POWER"
+        scalar_value: {
+            uint32_t: 5
+        }
+        enumerator: "SUSTAINED_PERFORMANCE"
+        scalar_value: {
+            uint32_t: 6
+        }
+        enumerator: "VR_MODE"
+        scalar_value: {
+            uint32_t: 7
+        }
+        enumerator: "LAUNCH"
+        scalar_value: {
+            uint32_t: 8
+        }
+        enumerator: "DISABLE_TOUCH"
+        scalar_value: {
+            uint32_t: 9
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::power::V1_0::Feature"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "POWER_FEATURE_DOUBLE_TAP_TO_WAKE"
+        scalar_value: {
+            uint32_t: 1
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::power::V1_0::Status"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "SUCCESS"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "FILESYSTEM_ERROR"
+        scalar_value: {
+            uint32_t: 1
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::power::V1_0::PowerStateVoter"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "name"
+        type: TYPE_STRING
+    }
+    struct_value: {
+        name: "totalTimeInMsecVotedForSinceBoot"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+    struct_value: {
+        name: "totalNumberOfTimesVotedSinceBoot"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::power::V1_0::PowerStatePlatformSleepState"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "name"
+        type: TYPE_STRING
+    }
+    struct_value: {
+        name: "residencyInMsecSinceBoot"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+    struct_value: {
+        name: "totalTransitions"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+    struct_value: {
+        name: "supportedOnlyInSuspend"
+        type: TYPE_SCALAR
+        scalar_type: "bool_t"
+    }
+    struct_value: {
+        name: "voters"
+        type: TYPE_VECTOR
+        vector_value: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::power::V1_0::PowerStateVoter"
+        }
+    }
+}
+
diff --git a/power/Android.bp b/power/Android.bp
new file mode 100644 (file)
index 0000000..ba90f2c
--- /dev/null
@@ -0,0 +1,5 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+    "1.0/default",
+]
diff --git a/sensors/1.0/Android.bp b/sensors/1.0/Android.bp
new file mode 100644 (file)
index 0000000..2039613
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.sensors@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.sensors@1.0",
+    srcs: [
+        "types.hal",
+        "ISensors.hal",
+    ],
+    out: [
+        "android/hardware/sensors/1.0/types.cpp",
+        "android/hardware/sensors/1.0/SensorsAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.sensors@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.sensors@1.0",
+    srcs: [
+        "types.hal",
+        "ISensors.hal",
+    ],
+    out: [
+        "android/hardware/sensors/1.0/types.h",
+        "android/hardware/sensors/1.0/ISensors.h",
+        "android/hardware/sensors/1.0/IHwSensors.h",
+        "android/hardware/sensors/1.0/BnSensors.h",
+        "android/hardware/sensors/1.0/BpSensors.h",
+        "android/hardware/sensors/1.0/BsSensors.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.sensors@1.0",
+    generated_sources: ["android.hardware.sensors@1.0_genc++"],
+    generated_headers: ["android.hardware.sensors@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.sensors@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/sensors/1.0/Android.mk b/sensors/1.0/Android.mk
new file mode 100644 (file)
index 0000000..dd9e21b
--- /dev/null
@@ -0,0 +1,38 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.sensors@1.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/sensors/1.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/ISensors.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.sensors@1.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/sensors/1.0/ISensors.hal b/sensors/1.0/ISensors.hal
new file mode 100644 (file)
index 0000000..adacfe0
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * 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 android.hardware.sensors@1.0;
+
+interface ISensors {
+    /**
+     * Enumerate all available (static) sensors.
+     */
+    getSensorsList() generates (vec<SensorInfo> list);
+
+    /**
+     *  Place the module in a specific mode. The following modes are defined
+     *
+     *  SENSOR_HAL_NORMAL_MODE - Normal operation. Default state of the module.
+     *
+     *  SENSOR_HAL_DATA_INJECTION_MODE - Loopback mode.
+     *    Data is injected for the supported sensors by the sensor service in
+     *    this mode.
+     *
+     * @return OK on success
+     *         BAD_VALUE if requested mode is not supported
+     *         PERMISSION_DENIED if operation is not allowed
+     */
+    setOperationMode(OperationMode mode) generates (Result result);
+
+    /* Activate/de-activate one sensor.
+     *
+     * sensorHandle is the handle of the sensor to change.
+     * enabled set to true to enable, or false to disable the sensor.
+     *
+     * After sensor de-activation, existing sensor events that have not
+     * been picked up by poll() should be abandoned immediately so that
+     * subsequent activation will not get stale sensor events (events
+     * that are generated prior to the latter activation).
+     *
+     * Returns OK on success, BAD_VALUE if sensorHandle is invalid.
+     */
+    activate(int32_t sensorHandle, bool enabled) generates (Result result);
+
+    /**
+     * Set the sampling period in nanoseconds for a given sensor.
+     * If samplingPeriodNs > maxDelay it will be truncated to
+     * maxDelay and if samplingPeriodNs < minDelay it will be
+     * replaced by minDelay.
+     *
+     * Returns OK on success, BAD_VALUE if sensorHandle is invalid.
+     */
+    setDelay(int32_t sensorHandle, int64_t samplingPeriodNs)
+        generates (Result result);
+
+    /**
+     * Generate a vector of sensor events containing at most "maxCount"
+     * entries.
+     *
+     * Additionally a vector of SensorInfos is returned for any dynamic sensors
+     * connected as notified by returned events of type DYNAMIC_SENSOR_META.
+     *
+     * This function should block if there is no sensor event
+     * available when being called.
+     *
+     * Returns OK on success or BAD_VALUE if maxCount <= 0.
+     */
+    poll(int32_t maxCount)
+        generates (
+                Result result,
+                vec<Event> data,
+                vec<SensorInfo> dynamicSensorsAdded);
+
+    /*
+     * Sets a sensor’s parameters, including sampling frequency and maximum
+     * report latency. This function can be called while the sensor is
+     * activated, in which case it must not cause any sensor measurements to
+     * be lost: transitioning from one sampling rate to the other cannot cause
+     * lost events, nor can transitioning from a high maximum report latency to
+     * a low maximum report latency.
+     * See the Batching sensor results page for details:
+     * http://source.android.com/devices/sensors/batching.html
+     *
+     * Returns OK on success, BAD_VALUE if any parameters are invalid.
+     */
+    batch(int32_t sensorHandle,
+          int32_t flags,
+          int64_t samplingPeriodNs,
+          int64_t maxReportLatencyNs) generates (Result result);
+
+    /*
+     * Flush adds a FLUSH_COMPLETE metadata event to the end of the "batch mode"
+     * FIFO for the specified sensor and flushes the FIFO.
+     * If the FIFO is empty or if the sensor doesn't support batching
+     * (FIFO size zero), it should return SUCCESS along with a trivial
+     * FLUSH_COMPLETE event added to the event stream.
+     * This applies to all sensors other than one-shot sensors.
+     * If the sensor is a one-shot sensor, flush must return BAD_VALUE and not
+     * generate any flush complete metadata.
+     * If the sensor is not active at the time flush() is called, flush() should
+     * return BAD_VALUE.
+     * Returns OK on success and BAD_VALUE if sensorHandle is invalid.
+     */
+    flush(int32_t sensorHandle) generates (Result result);
+
+    /*
+     * Inject a single sensor sample to this device.
+     * data points to the sensor event to be injected
+     * Returns OK on success
+     *         PERMISSION_DENIED if operation is not allowed
+     *         INVALID_OPERATION, if this functionality is unsupported
+     *         BAD_VALUE if sensor event cannot be injected
+     */
+    injectSensorData(Event event) generates (Result result);
+};
diff --git a/sensors/1.0/default/Android.bp b/sensors/1.0/default/Android.bp
new file mode 100644 (file)
index 0000000..d8d0c82
--- /dev/null
@@ -0,0 +1,40 @@
+cc_library_shared {
+    name: "android.hardware.sensors@1.0-impl",
+    relative_install_path: "hw",
+    srcs: ["Sensors.cpp"],
+    shared_libs: [
+        "liblog",
+        "libcutils",
+        "libhardware",
+        "libhwbinder",
+        "libbase",
+        "libcutils",
+        "libutils",
+        "libhidl",
+        "android.hardware.sensors@1.0",
+    ],
+    static_libs: [
+        "android.hardware.sensors@1.0-convert",
+    ],
+    local_include_dirs: ["include/sensors"],
+}
+
+cc_library_static {
+    name: "android.hardware.sensors@1.0-convert",
+    srcs: ["convert.cpp"],
+    export_include_dirs: ["include"],
+    shared_libs: [
+        "liblog",
+        "libcutils",
+        "libhardware",
+        "libhwbinder",
+        "libbase",
+        "libcutils",
+        "libutils",
+        "libhidl",
+        "android.hardware.sensors@1.0",
+    ],
+    local_include_dirs: ["include/sensors"],
+}
+
+
diff --git a/sensors/1.0/default/Android.mk b/sensors/1.0/default/Android.mk
new file mode 100644 (file)
index 0000000..4f418cb
--- /dev/null
@@ -0,0 +1,24 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_MODULE := android.hardware.sensors@1.0-service
+LOCAL_INIT_RC := android.hardware.sensors@1.0-service.rc
+LOCAL_SRC_FILES := \
+       service.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+       liblog \
+       libcutils \
+       libdl \
+       libbase \
+       libutils \
+       libhardware_legacy \
+       libhardware \
+
+LOCAL_SHARED_LIBRARIES += \
+       libhwbinder \
+       libhidl \
+       android.hardware.sensors@1.0 \
+
+include $(BUILD_EXECUTABLE)
diff --git a/sensors/1.0/default/Sensors.cpp b/sensors/1.0/default/Sensors.cpp
new file mode 100644 (file)
index 0000000..ef052c3
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ * 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.
+ */
+
+#include "Sensors.h"
+
+#include "convert.h"
+
+#include <android-base/logging.h>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V1_0 {
+namespace implementation {
+
+static Result ResultFromStatus(status_t err) {
+    switch (err) {
+        case OK:
+            return Result::OK;
+        case BAD_VALUE:
+            return Result::BAD_VALUE;
+        case PERMISSION_DENIED:
+            return Result::PERMISSION_DENIED;
+        default:
+            return Result::INVALID_OPERATION;
+    }
+}
+
+Sensors::Sensors()
+    : mInitCheck(NO_INIT),
+      mSensorModule(nullptr),
+      mSensorDevice(nullptr) {
+    status_t err = hw_get_module(
+            SENSORS_HARDWARE_MODULE_ID,
+            (hw_module_t const **)&mSensorModule);
+
+    if (mSensorModule == NULL) {
+        err = UNKNOWN_ERROR;
+    }
+
+    if (err != OK) {
+        LOG(ERROR) << "Couldn't load "
+                   << SENSORS_HARDWARE_MODULE_ID
+                   << " module ("
+                   << strerror(-err)
+                   << ")";
+
+        mInitCheck = err;
+        return;
+    }
+
+    err = sensors_open_1(&mSensorModule->common, &mSensorDevice);
+
+    if (err != OK) {
+        LOG(ERROR) << "Couldn't open device for module "
+                   << SENSORS_HARDWARE_MODULE_ID
+                   << " ("
+                   << strerror(-err)
+                   << ")";
+
+        mInitCheck = err;
+        return;
+    }
+
+    // Require all the old HAL APIs to be present except for injection, which
+    // is considered optional.
+    CHECK_GE(getHalDeviceVersion(), SENSORS_DEVICE_API_VERSION_1_3);
+
+    mInitCheck = OK;
+}
+
+status_t Sensors::initCheck() const {
+    return mInitCheck;
+}
+
+Return<void> Sensors::getSensorsList(getSensorsList_cb _aidl_cb) {
+    sensor_t const *list;
+    size_t count = mSensorModule->get_sensors_list(mSensorModule, &list);
+
+    hidl_vec<SensorInfo> out;
+    out.resize(count);
+
+    for (size_t i = 0; i < count; ++i) {
+        const sensor_t *src = &list[i];
+        SensorInfo *dst = &out[i];
+
+        convertFromSensor(*src, dst);
+    }
+
+    _aidl_cb(out);
+
+    return Void();
+}
+
+int Sensors::getHalDeviceVersion() const {
+    if (!mSensorDevice) {
+        return -1;
+    }
+
+    return mSensorDevice->common.version;
+}
+
+Return<Result> Sensors::setOperationMode(OperationMode mode) {
+    return ResultFromStatus(mSensorModule->set_operation_mode((uint32_t)mode));
+}
+
+Return<Result> Sensors::activate(
+        int32_t sensor_handle, bool enabled) {
+    return ResultFromStatus(
+            mSensorDevice->activate(
+                reinterpret_cast<sensors_poll_device_t *>(mSensorDevice),
+                sensor_handle,
+                enabled));
+}
+
+Return<Result> Sensors::setDelay(
+        int32_t sensor_handle, int64_t sampling_period_ns) {
+    return ResultFromStatus(
+            mSensorDevice->setDelay(
+                reinterpret_cast<sensors_poll_device_t *>(mSensorDevice),
+                sensor_handle,
+                sampling_period_ns));
+}
+
+Return<void> Sensors::poll(int32_t maxCount, poll_cb _aidl_cb) {
+    hidl_vec<Event> out;
+    hidl_vec<SensorInfo> dynamicSensorsAdded;
+
+    if (maxCount <= 0) {
+        _aidl_cb(Result::BAD_VALUE, out, dynamicSensorsAdded);
+        return Void();
+    }
+
+    std::unique_ptr<sensors_event_t[]> data(new sensors_event_t[maxCount]);
+
+    int err = mSensorDevice->poll(
+            reinterpret_cast<sensors_poll_device_t *>(mSensorDevice),
+            data.get(),
+            maxCount);
+
+    if (err < 0) {
+        _aidl_cb(ResultFromStatus(err), out, dynamicSensorsAdded);
+        return Void();
+    }
+
+    const size_t count = (size_t)err;
+
+    for (size_t i = 0; i < count; ++i) {
+        if (data[i].type != SENSOR_TYPE_DYNAMIC_SENSOR_META) {
+            continue;
+        }
+
+        const dynamic_sensor_meta_event_t *dyn = &data[i].dynamic_sensor_meta;
+
+        if (!dyn->connected) {
+            continue;
+        }
+
+        CHECK(dyn->sensor != nullptr);
+        CHECK_EQ(dyn->sensor->handle, dyn->handle);
+
+        SensorInfo info;
+        convertFromSensor(*dyn->sensor, &info);
+
+        size_t numDynamicSensors = dynamicSensorsAdded.size();
+        dynamicSensorsAdded.resize(numDynamicSensors + 1);
+        dynamicSensorsAdded[numDynamicSensors] = info;
+    }
+
+    out.resize(count);
+    convertFromSensorEvents(err, data.get(), &out);
+
+    _aidl_cb(Result::OK, out, dynamicSensorsAdded);
+
+    return Void();
+}
+
+Return<Result> Sensors::batch(
+        int32_t sensor_handle,
+        int32_t flags,
+        int64_t sampling_period_ns,
+        int64_t max_report_latency_ns) {
+    return ResultFromStatus(
+            mSensorDevice->batch(
+                mSensorDevice,
+                sensor_handle,
+                flags,
+                sampling_period_ns,
+                max_report_latency_ns));
+}
+
+Return<Result> Sensors::flush(int32_t sensor_handle) {
+    return ResultFromStatus(mSensorDevice->flush(mSensorDevice, sensor_handle));
+}
+
+Return<Result> Sensors::injectSensorData(const Event& event) {
+    if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_4) {
+        return Result::INVALID_OPERATION;
+    }
+
+    sensors_event_t out;
+    convertToSensorEvent(event, &out);
+
+    return ResultFromStatus(
+            mSensorDevice->inject_sensor_data(mSensorDevice, &out));
+}
+
+// static
+void Sensors::convertFromSensorEvents(
+        size_t count,
+        const sensors_event_t *srcArray,
+        hidl_vec<Event> *dstVec) {
+    for (size_t i = 0; i < count; ++i) {
+        const sensors_event_t &src = srcArray[i];
+        Event *dst = &(*dstVec)[i];
+
+        convertFromSensorEvent(src, dst);
+    }
+}
+
+ISensors *HIDL_FETCH_ISensors(const char * /* hal */) {
+    Sensors *sensors = new Sensors;
+    if (sensors->initCheck() != OK) {
+        delete sensors;
+        sensors = nullptr;
+
+        return nullptr;
+    }
+
+    return sensors;
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace sensors
+}  // namespace hardware
+}  // namespace android
diff --git a/sensors/1.0/default/Sensors.h b/sensors/1.0/default/Sensors.h
new file mode 100644 (file)
index 0000000..f9b837d
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+
+#ifndef HARDWARE_INTERFACES_SENSORS_V1_0_DEFAULT_SENSORS_H_
+
+#define HARDWARE_INTERFACES_SENSORS_V1_0_DEFAULT_SENSORS_H_
+
+#include <android/hardware/sensors/1.0/ISensors.h>
+#include <hardware/sensors.h>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V1_0 {
+namespace implementation {
+
+struct Sensors : public ::android::hardware::sensors::V1_0::ISensors {
+    Sensors();
+
+    status_t initCheck() const;
+
+    Return<void> getSensorsList(getSensorsList_cb _aidl_cb) override;
+
+    Return<Result> setOperationMode(OperationMode mode) override;
+
+    Return<Result> activate(
+            int32_t sensor_handle, bool enabled) override;
+
+    Return<Result> setDelay(
+            int32_t sensor_handle, int64_t sampling_period_ns) override;
+
+    Return<void> poll(int32_t maxCount, poll_cb _hidl_cb) override;
+
+    Return<Result> batch(
+            int32_t sensor_handle,
+            int32_t flags,
+            int64_t sampling_period_ns,
+            int64_t max_report_latency_ns) override;
+
+    Return<Result> flush(int32_t sensor_handle) override;
+
+    Return<Result> injectSensorData(const Event& event) override;
+
+private:
+    status_t mInitCheck;
+    sensors_module_t *mSensorModule;
+    sensors_poll_device_1_t *mSensorDevice;
+
+    int getHalDeviceVersion() const;
+
+    static void convertFromSensorEvents(
+            size_t count, const sensors_event_t *src, hidl_vec<Event> *dst);
+
+    DISALLOW_COPY_AND_ASSIGN(Sensors);
+};
+
+extern "C" ISensors *HIDL_FETCH_ISensors(const char *name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace sensors
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HARDWARE_INTERFACES_SENSORS_V1_0_DEFAULT_SENSORS_H_
diff --git a/sensors/1.0/default/android.hardware.sensors@1.0-service.rc b/sensors/1.0/default/android.hardware.sensors@1.0-service.rc
new file mode 100644 (file)
index 0000000..2cba0fc
--- /dev/null
@@ -0,0 +1,4 @@
+service sensors-hal-1-0 /system/bin/hw/android.hardware.sensors@1.0-service
+    class main
+    user system
+    group system readproc
diff --git a/sensors/1.0/default/convert.cpp b/sensors/1.0/default/convert.cpp
new file mode 100644 (file)
index 0000000..18725e7
--- /dev/null
@@ -0,0 +1,346 @@
+/*
+ * 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.
+ */
+
+#include "convert.h"
+
+#include <android-base/logging.h>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V1_0 {
+namespace implementation {
+
+void convertFromSensor(const sensor_t &src, SensorInfo *dst) {
+    dst->name = src.name;
+    dst->vendor = src.vendor;
+    dst->version = src.version;
+    dst->sensorHandle = src.handle;
+    dst->type = (SensorType)src.type;
+    dst->maxRange = src.maxRange;
+    dst->resolution = src.resolution;
+    dst->power = src.power;
+    dst->minDelay = src.minDelay;
+    dst->fifoReservedEventCount = src.fifoReservedEventCount;
+    dst->fifoMaxEventCount = src.fifoMaxEventCount;
+    dst->typeAsString = src.stringType;
+    dst->requiredPermission = src.requiredPermission;
+    dst->maxDelay = src.maxDelay;
+    dst->flags = src.flags;
+}
+
+void convertToSensor(
+        const ::android::hardware::sensors::V1_0::SensorInfo &src,
+        sensor_t *dst) {
+    dst->name = strdup(src.name.c_str());
+    dst->vendor = strdup(src.vendor.c_str());
+    dst->version = src.version;
+    dst->handle = src.sensorHandle;
+    dst->type = (int)src.type;
+    dst->maxRange = src.maxRange;
+    dst->resolution = src.resolution;
+    dst->power = src.power;
+    dst->minDelay = src.minDelay;
+    dst->fifoReservedEventCount = src.fifoReservedEventCount;
+    dst->fifoMaxEventCount = src.fifoMaxEventCount;
+    dst->stringType = strdup(src.typeAsString.c_str());
+    dst->requiredPermission = strdup(src.requiredPermission.c_str());
+    dst->maxDelay = src.maxDelay;
+    dst->flags = src.flags;
+    dst->reserved[0] = dst->reserved[1] = 0;
+}
+
+void convertFromSensorEvent(const sensors_event_t &src, Event *dst) {
+    typedef ::android::hardware::sensors::V1_0::SensorType SensorType;
+    typedef ::android::hardware::sensors::V1_0::MetaDataEventType MetaDataEventType;
+
+    dst->sensorHandle = src.sensor;
+    dst->sensorType = (SensorType)src.type;
+    dst->timestamp = src.timestamp;
+
+    switch (dst->sensorType) {
+        case SensorType::SENSOR_TYPE_META_DATA:
+        {
+            dst->u.meta.what = (MetaDataEventType)src.meta_data.what;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_ACCELEROMETER:
+        case SensorType::SENSOR_TYPE_GEOMAGNETIC_FIELD:
+        case SensorType::SENSOR_TYPE_ORIENTATION:
+        case SensorType::SENSOR_TYPE_GYROSCOPE:
+        case SensorType::SENSOR_TYPE_GRAVITY:
+        case SensorType::SENSOR_TYPE_LINEAR_ACCELERATION:
+        {
+            dst->u.vec3.x = src.acceleration.x;
+            dst->u.vec3.y = src.acceleration.y;
+            dst->u.vec3.z = src.acceleration.z;
+            dst->u.vec3.status = (SensorStatus)src.acceleration.status;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_ROTATION_VECTOR:
+        case SensorType::SENSOR_TYPE_GAME_ROTATION_VECTOR:
+        case SensorType::SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
+        {
+            dst->u.vec4.x = src.data[0];
+            dst->u.vec4.y = src.data[1];
+            dst->u.vec4.z = src.data[2];
+            dst->u.vec4.w = src.data[3];
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
+        case SensorType::SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
+        {
+            dst->u.uncal.x = src.uncalibrated_gyro.x_uncalib;
+            dst->u.uncal.y = src.uncalibrated_gyro.y_uncalib;
+            dst->u.uncal.z = src.uncalibrated_gyro.z_uncalib;
+            dst->u.uncal.x_bias = src.uncalibrated_gyro.x_bias;
+            dst->u.uncal.y_bias = src.uncalibrated_gyro.y_bias;
+            dst->u.uncal.z_bias = src.uncalibrated_gyro.z_bias;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_DEVICE_ORIENTATION:
+        case SensorType::SENSOR_TYPE_LIGHT:
+        case SensorType::SENSOR_TYPE_PRESSURE:
+        case SensorType::SENSOR_TYPE_TEMPERATURE:
+        case SensorType::SENSOR_TYPE_PROXIMITY:
+        case SensorType::SENSOR_TYPE_RELATIVE_HUMIDITY:
+        case SensorType::SENSOR_TYPE_AMBIENT_TEMPERATURE:
+        case SensorType::SENSOR_TYPE_SIGNIFICANT_MOTION:
+        case SensorType::SENSOR_TYPE_STEP_DETECTOR:
+        case SensorType::SENSOR_TYPE_TILT_DETECTOR:
+        case SensorType::SENSOR_TYPE_WAKE_GESTURE:
+        case SensorType::SENSOR_TYPE_GLANCE_GESTURE:
+        case SensorType::SENSOR_TYPE_PICK_UP_GESTURE:
+        case SensorType::SENSOR_TYPE_WRIST_TILT_GESTURE:
+        case SensorType::SENSOR_TYPE_STATIONARY_DETECT:
+        case SensorType::SENSOR_TYPE_MOTION_DETECT:
+        case SensorType::SENSOR_TYPE_HEART_BEAT:
+        {
+            dst->u.scalar = src.data[0];
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_STEP_COUNTER:
+        {
+            dst->u.stepCount = src.u64.step_counter;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_HEART_RATE:
+        {
+            dst->u.heartRate.bpm = src.heart_rate.bpm;
+            dst->u.heartRate.status = (SensorStatus)src.heart_rate.status;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_POSE_6DOF:  // 15 floats
+        {
+            for (size_t i = 0; i < 15; ++i) {
+                dst->u.pose6DOF[i] = src.data[i];
+            }
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_DYNAMIC_SENSOR_META:
+        {
+            dst->u.dynamic.connected = src.dynamic_sensor_meta.connected;
+            dst->u.dynamic.sensorHandle = src.dynamic_sensor_meta.handle;
+
+            memcpy(dst->u.dynamic.uuid.data(),
+                   src.dynamic_sensor_meta.uuid,
+                   16);
+
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_ADDITIONAL_INFO:
+        {
+            ::android::hardware::sensors::V1_0::AdditionalInfo *dstInfo =
+                &dst->u.additional;
+
+            const additional_info_event_t &srcInfo = src.additional_info;
+
+            dstInfo->type =
+                (::android::hardware::sensors::V1_0::AdditionalInfoType)
+                    srcInfo.type;
+
+            dstInfo->serial = srcInfo.serial;
+
+            CHECK_EQ(sizeof(dstInfo->u), sizeof(srcInfo.data_int32));
+            memcpy(&dstInfo->u, srcInfo.data_int32, sizeof(srcInfo.data_int32));
+            break;
+        }
+
+        default:
+        {
+            CHECK_GE((int32_t)dst->sensorType,
+                     (int32_t)SensorType::SENSOR_TYPE_DEVICE_PRIVATE_BASE);
+
+            memcpy(dst->u.data.data(), src.data, 16 * sizeof(float));
+            break;
+        }
+    }
+}
+
+void convertToSensorEvent(const Event &src, sensors_event_t *dst) {
+    dst->version = sizeof(sensors_event_t);
+    dst->sensor = src.sensorHandle;
+    dst->type = (int32_t)src.sensorType;
+    dst->reserved0 = 0;
+    dst->timestamp = src.timestamp;
+    dst->flags = 0;
+    dst->reserved1[0] = dst->reserved1[1] = dst->reserved1[2] = 0;
+
+    switch (src.sensorType) {
+        case SensorType::SENSOR_TYPE_META_DATA:
+        {
+            dst->meta_data.what = (int32_t)src.u.meta.what;
+            dst->meta_data.sensor = dst->sensor;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_ACCELEROMETER:
+        case SensorType::SENSOR_TYPE_GEOMAGNETIC_FIELD:
+        case SensorType::SENSOR_TYPE_ORIENTATION:
+        case SensorType::SENSOR_TYPE_GYROSCOPE:
+        case SensorType::SENSOR_TYPE_GRAVITY:
+        case SensorType::SENSOR_TYPE_LINEAR_ACCELERATION:
+        {
+            dst->acceleration.x = src.u.vec3.x;
+            dst->acceleration.y = src.u.vec3.y;
+            dst->acceleration.z = src.u.vec3.z;
+            dst->acceleration.status = (int8_t)src.u.vec3.status;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_ROTATION_VECTOR:
+        case SensorType::SENSOR_TYPE_GAME_ROTATION_VECTOR:
+        case SensorType::SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
+        {
+            dst->data[0] = src.u.vec4.x;
+            dst->data[1] = src.u.vec4.y;
+            dst->data[2] = src.u.vec4.z;
+            dst->data[3] = src.u.vec4.w;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
+        case SensorType::SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
+        {
+            dst->uncalibrated_gyro.x_uncalib = src.u.uncal.x;
+            dst->uncalibrated_gyro.y_uncalib = src.u.uncal.y;
+            dst->uncalibrated_gyro.z_uncalib = src.u.uncal.z;
+            dst->uncalibrated_gyro.x_bias = src.u.uncal.x_bias;
+            dst->uncalibrated_gyro.y_bias = src.u.uncal.y_bias;
+            dst->uncalibrated_gyro.z_bias = src.u.uncal.z_bias;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_DEVICE_ORIENTATION:
+        case SensorType::SENSOR_TYPE_LIGHT:
+        case SensorType::SENSOR_TYPE_PRESSURE:
+        case SensorType::SENSOR_TYPE_TEMPERATURE:
+        case SensorType::SENSOR_TYPE_PROXIMITY:
+        case SensorType::SENSOR_TYPE_RELATIVE_HUMIDITY:
+        case SensorType::SENSOR_TYPE_AMBIENT_TEMPERATURE:
+        case SensorType::SENSOR_TYPE_SIGNIFICANT_MOTION:
+        case SensorType::SENSOR_TYPE_STEP_DETECTOR:
+        case SensorType::SENSOR_TYPE_TILT_DETECTOR:
+        case SensorType::SENSOR_TYPE_WAKE_GESTURE:
+        case SensorType::SENSOR_TYPE_GLANCE_GESTURE:
+        case SensorType::SENSOR_TYPE_PICK_UP_GESTURE:
+        case SensorType::SENSOR_TYPE_WRIST_TILT_GESTURE:
+        case SensorType::SENSOR_TYPE_STATIONARY_DETECT:
+        case SensorType::SENSOR_TYPE_MOTION_DETECT:
+        case SensorType::SENSOR_TYPE_HEART_BEAT:
+        {
+            dst->data[0] = src.u.scalar;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_STEP_COUNTER:
+        {
+            dst->u64.step_counter = src.u.stepCount;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_HEART_RATE:
+        {
+            dst->heart_rate.bpm = src.u.heartRate.bpm;
+            dst->heart_rate.status = (int8_t)src.u.heartRate.status;
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_POSE_6DOF:  // 15 floats
+        {
+            for (size_t i = 0; i < 15; ++i) {
+                dst->data[i] = src.u.pose6DOF[i];
+            }
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_DYNAMIC_SENSOR_META:
+        {
+            dst->dynamic_sensor_meta.connected = src.u.dynamic.connected;
+            dst->dynamic_sensor_meta.handle = src.u.dynamic.sensorHandle;
+            dst->dynamic_sensor_meta.sensor = NULL;  // to be filled in later
+
+            memcpy(dst->dynamic_sensor_meta.uuid,
+                   src.u.dynamic.uuid.data(),
+                   16);
+
+            break;
+        }
+
+        case SensorType::SENSOR_TYPE_ADDITIONAL_INFO:
+        {
+            const ::android::hardware::sensors::V1_0::AdditionalInfo &srcInfo =
+                src.u.additional;
+
+            additional_info_event_t *dstInfo = &dst->additional_info;
+            dstInfo->type = (int32_t)srcInfo.type;
+            dstInfo->serial = srcInfo.serial;
+
+            CHECK_EQ(sizeof(srcInfo.u), sizeof(dstInfo->data_int32));
+
+            memcpy(dstInfo->data_int32,
+                   &srcInfo.u,
+                   sizeof(dstInfo->data_int32));
+
+            break;
+        }
+
+        default:
+        {
+            CHECK_GE((int32_t)src.sensorType,
+                     (int32_t)SensorType::SENSOR_TYPE_DEVICE_PRIVATE_BASE);
+
+            memcpy(dst->data, src.u.data.data(), 16 * sizeof(float));
+            break;
+        }
+    }
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace sensors
+}  // namespace hardware
+}  // namespace android
+
diff --git a/sensors/1.0/default/include/sensors/convert.h b/sensors/1.0/default/include/sensors/convert.h
new file mode 100644 (file)
index 0000000..d289a81
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+#ifndef HARDWARE_INTERFACES_SENSORS_V1_0_DEFAULT_INCLUDE_CONVERT_H_
+
+#define HARDWARE_INTERFACES_SENSORS_V1_0_DEFAULT_INCLUDE_CONVERT_H_
+
+#include <android/hardware/sensors/1.0/ISensors.h>
+#include <hardware/sensors.h>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V1_0 {
+namespace implementation {
+
+void convertFromSensor(const sensor_t &src, SensorInfo *dst);
+void convertToSensor(const SensorInfo &src, sensor_t *dst);
+
+void convertFromSensorEvent(const sensors_event_t &src, Event *dst);
+void convertToSensorEvent(const Event &src, sensors_event_t *dst);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace sensors
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HARDWARE_INTERFACES_SENSORS_V1_0_DEFAULT_INCLUDE_CONVERT_H_
diff --git a/sensors/1.0/default/service.cpp b/sensors/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..230ead3
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.nfc@1.0-service"
+
+#include <android/hardware/sensors/1.0/ISensors.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::sensors::V1_0::ISensors;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<ISensors>("sensors");
+}
diff --git a/sensors/1.0/types.hal b/sensors/1.0/types.hal
new file mode 100644 (file)
index 0000000..460cef5
--- /dev/null
@@ -0,0 +1,1087 @@
+/*
+ * 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 android.hardware.sensors@1.0;
+
+/**
+ * Please see the Sensors section of source.android.com for an
+ * introduction to and detailed descriptions of Android sensor types:
+ * http://source.android.com/devices/sensors/index.html
+ */
+
+/* Type enumerating various result codes returned from ISensors methods */
+enum Result : int32_t {
+    OK,
+    BAD_VALUE,
+    PERMISSION_DENIED,
+    INVALID_OPERATION,
+};
+
+/*
+ * Sensor HAL modes used in setOperationMode method
+ */
+@export(name="")
+enum OperationMode : int32_t {
+    SENSOR_HAL_NORMAL_MODE              = 0,
+    SENSOR_HAL_DATA_INJECTION_MODE      = 1,
+};
+
+/*
+ * Sensor type
+ *
+ * Each sensor has a type which defines what this sensor measures and how
+ * measures are reported. See the Base sensors and Composite sensors lists
+ * for complete descriptions:
+ * http://source.android.com/devices/sensors/base_triggers.html
+ * http://source.android.com/devices/sensors/composite_sensors.html
+ *
+ * Device manufacturers (OEMs) can define their own sensor types, for
+ * their private use by applications or services provided by them. Such
+ * sensor types are specific to an OEM and can't be exposed in the SDK.
+ * These types must start at SENSOR_TYPE_DEVICE_PRIVATE_BASE.
+ *
+ * All sensors defined outside of the device private range must correspond to
+ * a type defined in this file, and must satisfy the characteristics listed in
+ * the description of the sensor type.
+ *
+ * Each sensor also has a "typeAsString".
+ *  - StringType of sensors inside of the device private range MUST be prefixed
+ *    by the sensor provider's or OEM reverse domain name. In particular, they
+ *    cannot use the "android.sensor" prefix.
+ *  - StringType of sensors outside of the device private range MUST correspond
+ *    to the one defined in this file (starting with "android.sensor").
+ *    For example, accelerometers must have
+ *      type=SENSOR_TYPE_ACCELEROMETER and
+ *      stringType=SENSOR_STRING_TYPE_ACCELEROMETER
+ *
+ * When android introduces a new sensor type that can replace an OEM-defined
+ * sensor type, the OEM must use the official sensor type and stringType on
+ * versions of the HAL that support this new official sensor type.
+ *
+ * Example (made up): Suppose Google's Glass team wants to surface a sensor
+ * detecting that Glass is on a head.
+ *  - Such a sensor is not officially supported in android KitKat
+ *  - Glass devices launching on KitKat can implement a sensor with
+ *    type = 0x10001 and stringType = "com.google.glass.onheaddetector"
+ *  - In L android release, if android decides to define
+ *    SENSOR_TYPE_ON_HEAD_DETECTOR and STRING_SENSOR_TYPE_ON_HEAD_DETECTOR,
+ *    those types should replace the Glass-team-specific types in all future
+ *    launches.
+ *  - When launching Glass on the L release, Google should now use the official
+ *    type (SENSOR_TYPE_ON_HEAD_DETECTOR) and stringType.
+ *  - This way, all applications can now use this sensor.
+ */
+
+/*
+ * Wake up sensors.
+ * Each sensor may have either or both a wake-up and a non-wake variant.
+ * When registered in batch mode, wake-up sensors will wake up the AP when
+ * their FIFOs are full or when the batch timeout expires. A separate FIFO has
+ * to be maintained for wake up sensors and non wake up sensors. The non
+ * wake-up sensors need to overwrite their FIFOs when they are full till the AP
+ * wakes up and the wake-up sensors will wake-up the AP when their FIFOs are
+ * full or when the batch timeout expires without losing events.
+ * Wake-up and non wake-up variants of each sensor can be activated at
+ * different rates independently of each other.
+ *
+ * Note: Proximity sensor and significant motion sensor which were defined in
+ * previous releases are also wake-up sensors and should be treated as such.
+ * Wake-up one-shot sensors like SIGNIFICANT_MOTION cannot be batched, hence
+ * the text about batch above doesn't apply to them. See the definitions of
+ * SENSOR_TYPE_PROXIMITY and SENSOR_TYPE_SIGNIFICANT_MOTION for more info.
+ *
+ * Set SENSOR_FLAG_WAKE_UP flag for all wake-up sensors.
+ *
+ * For example, A device can have two sensors both of SENSOR_TYPE_ACCELEROMETER
+ * and one of them can be a wake_up sensor (with SENSOR_FLAG_WAKE_UP flag set)
+ * and the other can be a regular non wake_up sensor. Both of these sensors
+ * must be activated/deactivated independently of the other.
+ */
+
+@export(name="")
+enum SensorType : int32_t {
+    /* META_DATA is a special event type used to populate the MetaData
+     * structure. It doesn't correspond to a physical sensor. Events of this
+     * type exist only inside the HAL, their primary purpose is to signal the
+     * completion of a flush request.
+     */
+    SENSOR_TYPE_META_DATA                       = 0,
+
+    /*
+     * SENSOR_TYPE_ACCELEROMETER
+     * reporting-mode: continuous
+     *
+     * All values are in SI units (m/s^2) and measure the acceleration of the
+     * device minus the force of gravity.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_ACCELEROMETER                   = 1,
+
+    /*
+     * SENSOR_TYPE_GEOMAGNETIC_FIELD
+     * reporting-mode: continuous
+     *
+     * All values are in micro-Tesla (uT) and measure the geomagnetic
+     * field in the X, Y and Z axis.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_GEOMAGNETIC_FIELD               = 2,
+
+    /*
+     * SENSOR_TYPE_ORIENTATION
+     * reporting-mode: continuous
+     *
+     * All values are angles in degrees.
+     *
+     * Orientation sensors return sensor events for all 3 axes at a constant
+     * rate defined by setDelay().
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_ORIENTATION                     = 3,
+
+    /*
+     * SENSOR_TYPE_GYROSCOPE
+     * reporting-mode: continuous
+     *
+     * All values are in radians/second and measure the rate of rotation
+     * around the X, Y and Z axis.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_GYROSCOPE                       = 4,
+
+    /*
+     * SENSOR_TYPE_LIGHT
+     * reporting-mode: on-change
+     *
+     * The light sensor value is returned in SI lux units.
+     *
+     * Both wake-up and non wake-up versions are useful.
+     */
+    SENSOR_TYPE_LIGHT                           = 5,
+
+    /*
+     * SENSOR_TYPE_PRESSURE
+     * reporting-mode: continuous
+     *
+     * The pressure sensor return the athmospheric pressure in hectopascal (hPa)
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_PRESSURE                        = 6,
+
+    /* SENSOR_TYPE_TEMPERATURE is deprecated in the HAL */
+    SENSOR_TYPE_TEMPERATURE                     = 7,
+
+    /*
+     * SENSOR_TYPE_PROXIMITY
+     * reporting-mode: on-change
+     *
+     * The proximity sensor which turns the screen off and back on during calls
+     * is the wake-up proximity sensor. Implement wake-up proximity sensor
+     * before implementing a non wake-up proximity sensor. For the wake-up
+     * proximity sensor set the flag SENSOR_FLAG_WAKE_UP.
+     * The value corresponds to the distance to the nearest object in
+     * centimeters.
+     */
+    SENSOR_TYPE_PROXIMITY                       = 8,
+
+    /*
+     * SENSOR_TYPE_GRAVITY
+     * reporting-mode: continuous
+     *
+     * A gravity output indicates the direction of and magnitude of gravity in
+     * the devices's coordinates.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_GRAVITY                         = 9,
+
+    /*
+     * SENSOR_TYPE_LINEAR_ACCELERATION
+     * reporting-mode: continuous
+     *
+     * Indicates the linear acceleration of the device in device coordinates,
+     * not including gravity.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_LINEAR_ACCELERATION             = 10,
+
+    /*
+     * SENSOR_TYPE_ROTATION_VECTOR
+     * reporting-mode: continuous
+     *
+     * The rotation vector symbolizes the orientation of the device relative to
+     * the East-North-Up coordinates frame.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_ROTATION_VECTOR                 = 11,
+
+    /*
+     * SENSOR_TYPE_RELATIVE_HUMIDITY
+     * reporting-mode: on-change
+     *
+     * A relative humidity sensor measures relative ambient air humidity and
+     * returns a value in percent.
+     *
+     * Both wake-up and non wake-up versions are useful.
+     */
+    SENSOR_TYPE_RELATIVE_HUMIDITY               = 12,
+
+    /*
+     * SENSOR_TYPE_AMBIENT_TEMPERATURE
+     * reporting-mode: on-change
+     *
+     * The ambient (room) temperature in degree Celsius.
+     *
+     * Both wake-up and non wake-up versions are useful.
+     */
+    SENSOR_TYPE_AMBIENT_TEMPERATURE             = 13,
+
+    /*
+     * SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED
+     * reporting-mode: continuous
+     *
+     * Similar to SENSOR_TYPE_MAGNETIC_FIELD, but the hard iron calibration is
+     * reported separately instead of being included in the measurement.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED     = 14,
+
+    /*
+     * SENSOR_TYPE_GAME_ROTATION_VECTOR
+     * reporting-mode: continuous
+     *
+     * Similar to SENSOR_TYPE_ROTATION_VECTOR, but not using the geomagnetic
+     * field.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_GAME_ROTATION_VECTOR            = 15,
+
+    /*
+     * SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
+     * reporting-mode: continuous
+     *
+     * All values are in radians/second and measure the rate of rotation
+     * around the X, Y and Z axis.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_GYROSCOPE_UNCALIBRATED          = 16,
+
+    /*
+     * SENSOR_TYPE_SIGNIFICANT_MOTION
+     * reporting-mode: one-shot
+     *
+     * A sensor of this type triggers an event each time significant motion
+     * is detected and automatically disables itself.
+     * For Significant Motion sensor to be useful, it must be defined as a
+     * wake-up sensor. (set SENSOR_FLAG_WAKE_UP). Implement the wake-up
+     * significant motion sensor. A non wake-up version is not useful.
+     * The only allowed value to return is 1.0.
+     */
+    SENSOR_TYPE_SIGNIFICANT_MOTION              = 17,
+
+    /*
+     * SENSOR_TYPE_STEP_DETECTOR
+     * reporting-mode: special
+     *
+     * A sensor of this type triggers an event each time a step is taken
+     * by the user. The only allowed value to return is 1.0 and an event
+     * is generated for each step.
+     *
+     * Both wake-up and non wake-up versions are useful.
+     */
+    SENSOR_TYPE_STEP_DETECTOR                   = 18,
+
+    /*
+     * SENSOR_TYPE_STEP_COUNTER
+     * reporting-mode: on-change
+     *
+     * A sensor of this type returns the number of steps taken by the user since
+     * the last reboot while activated. The value is returned as a uint64_t and
+     * is reset to zero only on a system / android reboot.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_STEP_COUNTER                    = 19,
+
+    /*
+     * SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR
+     * reporting-mode: continuous
+     *
+     *  Similar to SENSOR_TYPE_ROTATION_VECTOR, but using a magnetometer instead
+     *  of using a gyroscope.
+     *
+     * Implement the non-wake-up version of this sensor and implement the
+     * wake-up version if the system possesses a wake up fifo.
+     */
+    SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR     = 20,
+
+    /*
+     * SENSOR_TYPE_HEART_RATE
+     * reporting-mode: on-change
+     *
+     *  A sensor of this type returns the current heart rate.
+     *  The events contain the current heart rate in beats per minute (BPM) and
+     *  the status of the sensor during the measurement. See "HeartRate" below
+     *  for more details.
+     *
+     *  Because this sensor is on-change, events must be generated when and only
+     *  when heart_rate.bpm or heart_rate.status have changed since the last
+     *  event. In particular, upon the first activation, unless the device is
+     *  known to not be on the body, the status field of the first event must be
+     *  set to SENSOR_STATUS_UNRELIABLE. The event should be generated no faster
+     *  than every period_ns passed to setDelay() or to batch().
+     *  See the definition of the on-change reporting mode for more information.
+     *
+     *  SensorInfo.requiredPermission must be set to
+     *  SENSOR_PERMISSION_BODY_SENSORS.
+     *
+     *  Both wake-up and non wake-up versions are useful.
+     */
+    SENSOR_TYPE_HEART_RATE                      = 21,
+
+    /*
+     * SENSOR_TYPE_WAKE_UP_TILT_DETECTOR
+     * reporting-mode: special (setDelay has no impact)
+     *
+     * A sensor of this type generates an event each time a tilt event is
+     * detected. A tilt event should be generated if the direction of the
+     * 2-seconds window average gravity changed by at least 35 degrees since the
+     * activation or the last trigger of the sensor.
+     *
+     *  reference_estimated_gravity = average of accelerometer measurements over
+     *  the first 1 second after activation or the estimated gravity at the last
+     *  trigger.
+     *
+     *  current_estimated_gravity = average of accelerometer measurements over
+     *  the last 2 seconds.
+     *
+     *  trigger when
+     *     angle(reference_estimated_gravity, current_estimated_gravity)
+     *       > 35 degrees
+     *
+     * Large accelerations without a change in phone orientation should not
+     * trigger a tilt event.
+     * For example, a sharp turn or strong acceleration while driving a car
+     * should not trigger a tilt event, even though the angle of the average
+     * acceleration might vary by more than 35 degrees.
+     *
+     * Typically, this sensor is implemented with the help of only an
+     * accelerometer. Other sensors can be used as well if they do not increase
+     * the power consumption significantly. This is a low power sensor that
+     * should allow the AP to go into suspend mode. Do not emulate this sensor
+     * in the HAL.
+     * Like other wake up sensors, the driver is expected to a hold a wake_lock
+     * with a timeout of 200 ms while reporting this event. The only allowed
+     * return value is 1.0.
+     *
+     * Implement only the wake-up version of this sensor.
+     */
+    SENSOR_TYPE_TILT_DETECTOR                   = 22,
+
+    /*
+     * SENSOR_TYPE_WAKE_GESTURE
+     * reporting-mode: one-shot
+     *
+     * A sensor enabling waking up the device based on a device specific motion.
+     *
+     * When this sensor triggers, the device behaves as if the power button was
+     * pressed, turning the screen on. This behavior (turning on the screen when
+     * this sensor triggers) might be deactivated by the user in the device
+     * settings. Changes in settings do not impact the behavior of the sensor:
+     * only whether the framework turns the screen on when it triggers.
+     *
+     * The actual gesture to be detected is not specified, and can be chosen by
+     * the manufacturer of the device.
+     * This sensor must be low power, as it is likely to be activated 24/7.
+     * The only allowed value to return is 1.0.
+     *
+     * Implement only the wake-up version of this sensor.
+     */
+    SENSOR_TYPE_WAKE_GESTURE                    = 23,
+
+    /*
+     * SENSOR_TYPE_GLANCE_GESTURE
+     * reporting-mode: one-shot
+     *
+     * A sensor enabling briefly turning the screen on to enable the user to
+     * glance content on screen based on a specific motion.  The device should
+     * turn the screen off after a few moments.
+     *
+     * When this sensor triggers, the device turns the screen on momentarily
+     * to allow the user to glance notifications or other content while the
+     * device remains locked in a non-interactive state (dozing). This behavior
+     * (briefly turning on the screen when this sensor triggers) might be
+     * deactivated by the user in the device settings.
+     * Changes in settings do not impact the behavior of the sensor: only
+     * whether the framework briefly turns the screen on when it triggers.
+     *
+     * The actual gesture to be detected is not specified, and can be chosen by
+     * the manufacturer of the device.
+     * This sensor must be low power, as it is likely to be activated 24/7.
+     * The only allowed value to return is 1.0.
+     *
+     * Implement only the wake-up version of this sensor.
+     */
+    SENSOR_TYPE_GLANCE_GESTURE                  = 24,
+
+    /**
+     * SENSOR_TYPE_PICK_UP_GESTURE
+     * reporting-mode: one-shot
+     *
+     * A sensor of this type triggers when the device is picked up regardless of
+     * wherever is was before (desk, pocket, bag). The only allowed return value
+     * is 1.0. This sensor de-activates itself immediately after it triggers.
+     *
+     * Implement only the wake-up version of this sensor.
+     */
+    SENSOR_TYPE_PICK_UP_GESTURE                 = 25,
+
+    /*
+     * SENSOR_TYPE_WRIST_TILT_GESTURE
+     * trigger-mode: special
+     * wake-up sensor: yes
+     *
+     * A sensor of this type triggers an event each time a tilt of the
+     * wrist-worn device is detected.
+     *
+     * This sensor must be low power, as it is likely to be activated 24/7.
+     * The only allowed value to return is 1.0.
+     *
+     * Implement only the wake-up version of this sensor.
+     */
+    SENSOR_TYPE_WRIST_TILT_GESTURE              = 26,
+
+    /*
+     * SENSOR_TYPE_DEVICE_ORIENTATION
+     * reporting-mode: on-change
+     *
+     * The current orientation of the device. The value should be reported in
+     * the "scalar" element of the EventPayload in Event. The
+     * only values that can be reported are (please refer to Android Sensor
+     * Coordinate System to understand the X and Y axis direction with respect
+     * to default orientation):
+     *  - 0: device is in default orientation (Y axis is vertical and points up)
+     *  - 1: device is rotated 90 degrees counter-clockwise from default
+     *       orientation (X axis is vertical and points up)
+     *  - 2: device is rotated 180 degrees from default orientation (Y axis is
+     *       vertical and points down)
+     *  - 3: device is rotated 90 degrees clockwise from default orientation
+     *       (X axis is vertical and points down)
+     *
+     * Moving the device to an orientation where the Z axis is vertical (either
+     * up or down) should not cause a new event to be reported.
+     *
+     * To improve the user experience of this sensor, it is recommended to
+     * implement some physical (i.e., rotation angle) and temporal (i.e., delay)
+     * hysteresis.
+     * In other words, minor or transient rotations should not cause a new event
+     * to be reported.
+     *
+     * This sensor should only be implemented with the help of an accelerometer.
+     * This is a low power sensor that should reduce the number of interrupts of
+     * the AP. Do not emulate this sensor in the HAL.
+     *
+     * Both wake-up and non wake-up versions are useful.
+     */
+    SENSOR_TYPE_DEVICE_ORIENTATION              = 27,
+
+    /*
+     * SENSOR_TYPE_POSE_6DOF
+     * trigger-mode: continuous
+     *
+     * A sensor of this type returns the pose of the device.
+     * Pose of the device is defined as the orientation of the device from a
+     * Earth Centered Earth Fixed frame and the translation from an arbitrary
+     * point at subscription.
+     *
+     * This sensor can be high power. It can use any and all of the following
+     *           . Accelerometer
+     *           . Gyroscope
+     *           . Camera
+     *           . Depth Camera
+     *
+     */
+    SENSOR_TYPE_POSE_6DOF                       = 28,
+
+    /*
+     * SENSOR_TYPE_STATIONARY_DETECT
+     * trigger mode: one shot
+     *
+     * A sensor of this type returns an event if the device is still/stationary
+     * for a while. The period of time to monitor for statinarity should be
+     * greater than 5 seconds, and less than 10 seconds.
+     *
+     * Stationarity here refers to absolute stationarity. eg: device on desk.
+     *
+     * The only allowed value to return is 1.0.
+     */
+    SENSOR_TYPE_STATIONARY_DETECT               = 29,
+
+    /*
+     * SENSOR_TYPE_MOTION_DETECT
+     * trigger mode: one shot
+     *
+     * A sensor of this type returns an event if the device is not still for
+     * a while. The period of time to monitor for statinarity should be greater
+     * than 5 seconds, and less than 10 seconds.
+     *
+     * Motion here refers to any mechanism in which the device is causes to be
+     * moved in its inertial frame. eg: Pickin up the device and walking with it
+     * to a nearby room may trigger motion wherewas keeping the device on a
+     * table on a smooth train moving at constant velocity may not trigger
+     * motion.
+     *
+     * The only allowed value to return is 1.0.
+     */
+    SENSOR_TYPE_MOTION_DETECT                   = 30,
+
+    /*
+     * SENSOR_TYPE_HEART_BEAT
+     * trigger mode: continuous
+     *
+     * A sensor of this type returns an event everytime a hear beat peak is
+     * detected.
+     *
+     * Peak here ideally corresponds to the positive peak in the QRS complex of
+     * and ECG signal.
+     *
+     * The sensor is not expected to be optimized for latency. As a guide, a
+     * latency of up to 10 seconds is acceptable. However the timestamp attached
+     * to the event should be accurate and should correspond to the time the
+     * peak occured.
+     *
+     * The sensor event contains a parameter for the confidence in the detection
+     * of the peak where 0.0 represent no information at all, and 1.0 represents
+     * certainty.
+     */
+    SENSOR_TYPE_HEART_BEAT                      = 31,
+
+    /**
+     * SENSOR_TYPE_DYNAMIC_SENSOR_META
+     * trigger-mode: special
+     *
+     * A sensor event of this type is received when a dynamic sensor is added to
+     * or removed from the system. At most one sensor of this type can be
+     * present in one sensor HAL implementation and presence of a sensor of this
+     * type in sensor HAL implementation indicates that this sensor HAL supports
+     * dynamic sensor feature. Operations, such as batch, activate and setDelay,
+     * to this special purpose sensor should be treated as no-op and return
+     * successful; flush() also has to generate flush complete event as if this
+     * is a sensor that does not support batching.
+     *
+     * A dynamic sensor connection indicates connection of a physical device or
+     * instantiation of a virtual sensor backed by algorithm; and a dynamic
+     * sensor disconnection indicates the the opposite. A sensor event of
+     * SENSOR_TYPE_DYNAMIC_SENSOR_META type should be delivered regardless of
+     * the activation status of the sensor in the event of dynamic sensor
+     * connection and disconnection. In the sensor event, besides the common
+     * data entries, "dynamic_sensor_meta", which includes fields for connection
+     * status, handle of the sensor involved, pointer to sensor_t structure and
+     * a uuid field, should be populated.
+     *
+     * At a dynamic sensor connection event, fields of sensor_t structure
+     * referenced by a pointer in dynamic_sensor_meta should be filled as if it
+     * was regular sensors. Sensor HAL is responsible for recovery of memory if
+     * the corresponding data is dynamicially allocated. However, the the
+     * pointer must be valid until the first activate call to the sensor
+     * reported in this connection event. At a dynamic sensor disconnection,
+     * the sensor_t pointer should be NULL.
+     *
+     * The sensor handle assigned to dynamic sensors should never be the same as
+     * that of any regular static sensors, and should be unique until next boot.
+     * In another word, if a handle h is used for a dynamic sensor A, that same
+     * number cannot be used for the same dynamic sensor A or another dynamic
+     * sensor B even after disconnection of A until reboot.
+     *
+     * The UUID field will be used for identifying the sensor in addition to
+     * name, vendor and version and type. For physical sensors of the same
+     * model, all sensors will have the same values in sensor_t, but the UUID
+     * should be unique and persistent for each individual unit. An all zero
+     * UUID indicates it is not possible to differentiate individual sensor
+     * unit.
+     *
+     */
+    SENSOR_TYPE_DYNAMIC_SENSOR_META             = 32,
+
+    /**
+     * SENSOR_TYPE_ADDITIONAL_INFO
+     * reporting-mode: N/A
+     *
+     * This sensor type is for delivering additional sensor information aside
+     * from sensor event data.
+     * Additional information may include sensor front-end group delay, internal
+     * calibration parameters, noise level metrics, device internal temperature,
+     * etc.
+     *
+     * This type will never bind to a sensor. In other words, no sensor in the
+     * sensor list should be of the type SENSOR_TYPE_ADDITIONAL_INFO. If a
+     * sensor HAL supports sensor additional information feature, it reports
+     * sensor_event_t with "sensor" field set to handle of the reporting sensor
+     * and "type" field set to SENSOR_TYPE_ADDITIONAL_INFO. Delivery of
+     * additional information events is triggered under two conditions: an
+     * enable activate() call or a flush() call to the corresponding sensor.
+     *
+     * A single additional information report consists of multiple frames.
+     * Sequences of these frames are ordered using timestamps, which means the
+     * timestamps of sequential frames have to be at least 1 nanosecond apart
+     * from each other. Each frame is a sensor_event_t delivered through the HAL
+     * interface, with related data stored in the "additional_info" field, which
+     * is of type additional_info_event_t.
+     * The "type" field of additional_info_event_t denotes the nature of the
+     * payload data (see additional_info_type_t).
+     * The "serial" field is used to keep the sequence of payload data that
+     * spans multiple frames. The first frame of the entire report is always of
+     * type AINFO_BEGIN, and the last frame is always AINFO_END.
+     *
+     * All additional information frames have to be delivered after flush
+     * complete event if flush() was triggering the report.
+     */
+    SENSOR_TYPE_ADDITIONAL_INFO                 = 33,
+
+    /*
+     * SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT
+     * trigger-mode: on-change
+     * wake-up sensor: yes
+     *
+     * A sensor of this type is defined for devices that are supposed to be worn
+     * by the user in the normal use case (such as a watch, wristband, etc) and
+     * is not yet defined for other device.
+     *
+     * A sensor of this type triggers an event each time the wearable device
+     * is removed from the body and each time it's put back onto the body.
+     * It must be low-latency and be able to detect the on-body to off-body
+     * transition within one second (event delivery time included),
+     * and 3-second latency to determine the off-body to on-body transition
+     * (event delivery time included).
+     *
+     * There are only two valid event values for the sensor to return :
+     *    0.0 for off-body
+     *    1.0 for on-body
+     *
+     */
+    SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT      = 34,
+
+    /*
+     * Base for device manufacturers private sensor types.
+     * These sensor types can't be exposed in the SDK.
+     */
+    SENSOR_TYPE_DEVICE_PRIVATE_BASE             = 0x10000
+};
+
+@export(name="")
+enum SensorFlagBits : uint64_t {
+    /*
+     * Whether this sensor wakes up the AP from suspend mode when data is
+     * available.  Whenever sensor events are delivered from a wake_up sensor,
+     * the driver needs to hold a wake_lock till the events are read by the
+     * SensorService i.e till ISensors::poll() is called the next time.
+     * Once poll is called again it means events have been read by the
+     * SensorService, the driver can safely release the wake_lock. SensorService
+     * will continue to hold a wake_lock till the app actually reads the events.
+     */
+    SENSOR_FLAG_WAKE_UP                     = 1,
+
+    /*
+     * Reporting modes for various sensors. Each sensor will have exactly one of
+     * these modes set.
+     * The least significant 2nd, 3rd and 4th bits are used to represent four
+     * possible reporting modes.
+     */
+    SENSOR_FLAG_CONTINUOUS_MODE             = 0,
+    SENSOR_FLAG_ON_CHANGE_MODE              = 2,
+    SENSOR_FLAG_ONE_SHOT_MODE               = 4,
+    SENSOR_FLAG_SPECIAL_REPORTING_MODE      = 6,
+
+    /*
+     * Set this flag if the sensor supports data_injection mode and allows data
+     * to be injected from the SensorService. When in data_injection ONLY
+     * sensors with this flag set are injected sensor data and only sensors with
+     * this flag set are activated. Eg: Accelerometer and Step Counter sensors
+     * can be set with this flag and SensorService will inject accelerometer
+     * data and read the corresponding step counts.
+     */
+    SENSOR_FLAG_SUPPORTS_DATA_INJECTION     = 0x10,
+
+    /*
+     * Set this flag if the sensor is a dynamically connected sensor. See
+     * DynamicSensorInfo and DYNAMIC_SENSOR_META for details.
+     */
+    SENSOR_FLAG_DYNAMIC_SENSOR              = 0x20,
+
+    /*
+     * Set this flag if sensor additional information is supported.
+     * See ADDITIONAL_INFO and AdditionalInfo for details.
+     */
+    SENSOR_FLAG_ADDITIONAL_INFO             = 0x40,
+};
+
+struct SensorInfo {
+    /* handle that identifies this sensors. This handle is used to reference
+     * this sensor throughout the HAL API.
+     */
+    int32_t sensorHandle;
+
+    /* Name of this sensor.
+     * All sensors of the same "type" must have a different "name".
+     */
+    string name;
+
+    /* vendor of the hardware part */
+    string vendor;
+
+    /* version of the hardware part + driver. The value of this field
+     * must increase when the driver is updated in a way that changes the
+     * output of this sensor. This is important for fused sensors when the
+     * fusion algorithm is updated.
+     */
+    int32_t version;
+
+    /* this sensor's type. */
+    SensorType type;
+
+    /* type of this sensor as a string. Set to corresponding
+     * SENSOR_STRING_TYPE_*.
+     * When defining an OEM specific sensor or sensor manufacturer specific
+     * sensor, use your reserve domain name as a prefix.
+     * ex: com.google.glass.onheaddetector
+     * For sensors of known type, the android framework might overwrite this
+     * string automatically.
+     */
+    string typeAsString;
+
+    /* maximum range of this sensor's value in SI units */
+    float maxRange;
+
+    /* smallest difference between two values reported by this sensor */
+    float resolution;
+
+    /* rough estimate of this sensor's power consumption in mA */
+    float power;
+
+    /* this value depends on the reporting mode:
+     *
+     *   continuous: minimum sample period allowed in microseconds
+     *   on-change : 0
+     *   one-shot  :-1
+     *   special   : 0, unless otherwise noted
+     */
+    int32_t minDelay;
+
+    /* number of events reserved for this sensor in the batch mode FIFO.
+     * If there is a dedicated FIFO for this sensor, then this is the
+     * size of this FIFO. If the FIFO is shared with other sensors,
+     * this is the size reserved for that sensor and it can be zero.
+     */
+    uint32_t fifoReservedEventCount;
+
+    /* maximum number of events of this sensor that could be batched.
+     * This is especially relevant when the FIFO is shared between
+     * several sensors; this value is then set to the size of that FIFO.
+     */
+    uint32_t fifoMaxEventCount;
+
+    /* permission required to see this sensor, register to it and receive data.
+     * Set to "" if no permission is required. Some sensor types like the
+     * heart rate monitor have a mandatory require_permission.
+     * For sensors that always require a specific permission, like the heart
+     * rate monitor, the android framework might overwrite this string
+     * automatically.
+     */
+    string requiredPermission;
+
+    /* This value is defined only for continuous mode and on-change sensors.
+     * It is the delay between two sensor events corresponding to the lowest
+     * frequency that this sensor supports. When lower frequencies are requested
+     * through batch()/setDelay() the events will be generated at this frequency
+     * instead.
+     * It can be used by the framework or applications to estimate when the
+     * batch FIFO may be full.
+     *
+     * NOTE: periodNs is in nanoseconds where as maxDelay/minDelay are in
+     *       microseconds.
+     *
+     *       continuous, on-change: maximum sampling period allowed in
+     *                              microseconds.
+     *
+     *          one-shot, special : 0
+     */
+    int32_t maxDelay;
+
+    /* Bitmask of SensorFlagBits */
+    uint64_t flags;
+};
+
+@export(name="")
+enum SensorStatus : int8_t {
+    SENSOR_STATUS_NO_CONTACT      = -1,
+    SENSOR_STATUS_UNRELIABLE      = 0,
+    SENSOR_STATUS_ACCURACY_LOW    = 1,
+    SENSOR_STATUS_ACCURACY_MEDIUM = 2,
+    SENSOR_STATUS_ACCURACY_HIGH   = 3,
+};
+
+struct Vec3 {
+    float x;
+    float y;
+    float z;
+    SensorStatus status;
+};
+
+struct Vec4 {
+    float x;
+    float y;
+    float z;
+    float w;
+};
+
+struct Uncal {
+    float x;
+    float y;
+    float z;
+    float x_bias;
+    float y_bias;
+    float z_bias;
+};
+
+struct HeartRate {
+    /* Heart rate in beats per minute.
+     * Set to 0 when status is SENSOR_STATUS_UNRELIABLE or ..._NO_CONTACT
+     */
+    float bpm;
+
+    /* Status of the sensor for this reading. Set to one SENSOR_STATUS_...
+     * Note that this value should only be set for sensors that explicitly
+     * define the meaning of this field. This field is not piped through the
+     * framework for other sensors.
+     */
+    SensorStatus status;
+};
+
+@export(name="")
+enum MetaDataEventType : uint32_t {
+    META_DATA_FLUSH_COMPLETE = 1,
+};
+
+struct MetaData {
+    MetaDataEventType what;
+};
+
+struct DynamicSensorInfo {
+    bool connected;
+    int32_t sensorHandle;
+
+    /* UUID of a dynamic sensor (using RFC 4122 byte order)
+     * For UUID 12345678-90AB-CDEF-1122-334455667788 the uuid field should be
+     * initialized as:
+     *   {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x11, ...}
+     */
+    uint8_t[16] uuid;
+};
+
+@export(name="additional_info_type_t")
+enum AdditionalInfoType : uint32_t {
+    /* Marks the beginning of additional information frames */
+    AINFO_BEGIN                       = 0,
+
+    /* Marks the end of additional information frames */
+    AINFO_END                         = 1,
+
+    /* Estimation of the delay that is not tracked by sensor timestamps. This
+     * includes delay introduced by sensor front-end filtering, data transport,
+     * etc.
+     * float[2]: delay in seconds, standard deviation of estimated value
+     */
+    AINFO_UNTRACKED_DELAY             = 0x10000,
+
+    /* float: Celsius temperature */
+    AINFO_INTERNAL_TEMPERATURE,
+
+    /* First three rows of a homogeneous matrix, which represents calibration to
+     * a three-element vector raw sensor reading.
+     * float[12]: 3x4 matrix in row major order
+     */
+    AINFO_VEC3_CALIBRATION,
+
+    /* Location and orientation of sensor element in the device frame: origin is
+     * the geometric center of the mobile device screen surface; the axis
+     * definition corresponds to Android sensor definitions.
+     * float[12]: 3x4 matrix in row major order
+     */
+    AINFO_SENSOR_PLACEMENT,
+
+    /* float[2]: raw sample period in seconds,
+     *           standard deviation of sampling period
+     */
+    AINFO_SAMPLING,
+
+    /* Sampling channel modeling information
+     * int32_t: noise type
+     * float[n]: parameters
+     */
+    AINFO_CHANNEL_NOISE               = 0x20000,
+
+    /* float[3]: sample period, standard deviation of sample period,
+     * quantization unit
+     */
+    AINFO_CHANNEL_SAMPLER,
+
+    /* Represents a filter:
+     *   \sum_j a_j y[n-j] == \sum_i b_i x[n-i]
+     *
+     * int32_t[3]: number of feedforward coeffients M,
+     *             number of feedback coefficients N (for FIR filter, N = 1).
+     *             bit mask that represents which element the filter is applied
+     *             to. (bit 0==1 means this filter applies to vector element 0).
+     * float[M+N]: filter coefficients (b0, b1, ..., b_{M-1}), then
+     *             (a0, a1, ..., a_{N-1}), a0 is always 1.
+     *
+     * Multiple frames may be needed for higher number of taps.
+     */
+    AINFO_CHANNEL_FILTER,
+
+    /* int32_t[2]: size in (row, column) ... 1st frame
+     * float[n]: matrix element values in row major order.
+     */
+    AINFO_CHANNEL_LINEAR_TRANSFORM,
+
+    /* int32_t[2]: extrapolate method, interpolate method
+     * float[n]: mapping key points in paris, (in, out)...
+     *           (may be used to model saturation).
+     */
+    AINFO_CHANNEL_NONLINEAR_MAP,
+
+    /* int32_t: resample method (0-th order, 1st order...)
+     * float[1]: resample ratio (upsampling if < 1.0, downsampling if > 1.0).
+     */
+    AINFO_CHANNEL_RESAMPLER,
+
+    /* Custom information */
+    AINFO_CUSTOM_START                = 0x10000000,
+
+    /* Debugging */
+    AINFO_DEBUGGING_START             = 0x40000000,
+};
+
+struct AdditionalInfo {
+    /* type of payload data, see AdditionalInfoType */
+    AdditionalInfoType type;
+
+    /* sequence number of this frame for this type */
+    int32_t serial;
+
+    union Payload {
+        /* for each frame, a single data type, either int32_t or float,
+         * should be used.
+         */
+        int32_t[14] data_int32;
+        float[14] data_float;
+    } u;
+};
+
+/* acceleration values are in meter per second per second (m/s^2)
+ * magnetic vector values are in micro-Tesla (uT)
+ * orientation values are in degrees
+ * gyroscope values are in rad/s
+ * temperature is in degrees centigrade (Celsius)
+ * distance in centimeters
+ * light in SI lux units
+ * pressure in hectopascal (hPa)
+ * relative humidity in percent
+ */
+union EventPayload {
+    /* SENSOR_TYPE_ACCELEROMETER, SENSOR_TYPE_GEOMAGNETIC_FIELD,
+     * SENSOR_TYPE_ORIENTATION, SENSOR_TYPE_GYROSCOPE, SENSOR_TYPE_GRAVITY,
+     * SENSOR_TYPE_LINEAR_ACCELERATION
+     */
+    Vec3 vec3;
+
+    /* SENSOR_TYPE_ROTATION_VECTOR, SENSOR_TYPE_GAME_ROTATION_VECTOR,
+     * SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR
+     */
+    Vec4 vec4;
+
+    /* SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED,
+     * SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
+     */
+    Uncal uncal;
+
+    /* SENSOR_TYPE_META_DATA */
+    MetaData meta;
+
+    /* SENSOR_TYPE_DEVICE_ORIENTATION, SENSOR_TYPE_LIGHT, SENSOR_TYPE_PRESSURE,
+     * SENSOR_TYPE_TEMPERATURE, SENSOR_TYPE_PROXIMITY,
+     * SENSOR_TYPE_RELATIVE_HUMIDITY, SENSOR_TYPE_AMBIENT_TEMPERATURE,
+     * SENSOR_TYPE_SIGNIFICANT_MOTION, SENSOR_TYPE_STEP_DETECTOR,
+     * SENSOR_TYPE_TILT_DETECTOR, SENSOR_TYPE_WAKE_GESTURE,
+     * SENSOR_TYPE_GLANCE_GESTURE, SENSOR_TYPE_PICK_UP_GESTURE,
+     * SENSOR_TYPE_WRIST_TILT_GESTURE, SENSOR_TYPE_STATIONARY_DETECT,
+     * SENSOR_TYPE_MOTION_DETECT, SENSOR_TYPE_HEART_BEAT
+     */
+    float scalar;
+
+    /* SENSOR_TYPE_STEP_COUNTER */
+    uint64_t stepCount;
+
+    /* SENSOR_TYPE_HEART_RATE */
+    HeartRate heartRate;
+
+    /* SENSOR_TYPE_POSE_6DOF */
+    float[15] pose6DOF;
+
+    /* SENSOR_TYPE_DYNAMIC_SENSOR_META */
+    DynamicSensorInfo dynamic;
+
+    /* SENSOR_TYPE_ADDITIONAL_INFO */
+    AdditionalInfo additional;
+
+    /* undefined/custom sensor type, >= SENSOR_TYPE_DEVICE_PRIVATE_BASE */
+    float[16] data;
+};
+
+struct Event {
+    /* Time measured in nanoseconds, in "elapsedRealtimeNano()'s" timebase. */
+    int64_t timestamp;
+
+    /* sensor identifier */
+    int32_t sensorHandle;
+
+    SensorType sensorType;
+
+    /* Union discriminated on sensorType */
+    EventPayload u;
+};
diff --git a/sensors/Android.bp b/sensors/Android.bp
new file mode 100644 (file)
index 0000000..ba90f2c
--- /dev/null
@@ -0,0 +1,5 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+    "1.0/default",
+]
diff --git a/soundtrigger/2.0/Android.bp b/soundtrigger/2.0/Android.bp
new file mode 100644 (file)
index 0000000..79ae797
--- /dev/null
@@ -0,0 +1,61 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.soundtrigger@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.soundtrigger@2.0",
+    srcs: [
+        "types.hal",
+        "ISoundTriggerHw.hal",
+        "ISoundTriggerHwCallback.hal",
+    ],
+    out: [
+        "android/hardware/soundtrigger/2.0/types.cpp",
+        "android/hardware/soundtrigger/2.0/SoundTriggerHwAll.cpp",
+        "android/hardware/soundtrigger/2.0/SoundTriggerHwCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.soundtrigger@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.soundtrigger@2.0",
+    srcs: [
+        "types.hal",
+        "ISoundTriggerHw.hal",
+        "ISoundTriggerHwCallback.hal",
+    ],
+    out: [
+        "android/hardware/soundtrigger/2.0/types.h",
+        "android/hardware/soundtrigger/2.0/ISoundTriggerHw.h",
+        "android/hardware/soundtrigger/2.0/IHwSoundTriggerHw.h",
+        "android/hardware/soundtrigger/2.0/BnSoundTriggerHw.h",
+        "android/hardware/soundtrigger/2.0/BpSoundTriggerHw.h",
+        "android/hardware/soundtrigger/2.0/BsSoundTriggerHw.h",
+        "android/hardware/soundtrigger/2.0/ISoundTriggerHwCallback.h",
+        "android/hardware/soundtrigger/2.0/IHwSoundTriggerHwCallback.h",
+        "android/hardware/soundtrigger/2.0/BnSoundTriggerHwCallback.h",
+        "android/hardware/soundtrigger/2.0/BpSoundTriggerHwCallback.h",
+        "android/hardware/soundtrigger/2.0/BsSoundTriggerHwCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.soundtrigger@2.0",
+    generated_sources: ["android.hardware.soundtrigger@2.0_genc++"],
+    generated_headers: ["android.hardware.soundtrigger@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.soundtrigger@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.audio.common@2.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.audio.common@2.0",
+    ],
+}
diff --git a/soundtrigger/2.0/ISoundTriggerHw.hal b/soundtrigger/2.0/ISoundTriggerHw.hal
new file mode 100644 (file)
index 0000000..cf35ef1
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+ * Copyright 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 android.hardware.soundtrigger@2.0;
+
+import android.hardware.audio.common@2.0;
+
+import ISoundTriggerHwCallback;
+
+interface ISoundTriggerHw {
+
+    /*
+     * Sound trigger implementation descriptor read by the framework via
+     * getProperties(). Used by SoundTrigger service to report to applications
+     * and manage concurrency and policy.
+     */
+    struct Properties {
+        /* Implementor name */
+        string   implementor;
+        /* Implementation description */
+        string   description;
+        /* Implementation version */
+        uint32_t version;
+        /* Unique implementation ID. The UUID must change with each version of
+           the engine implementation */
+        Uuid     uuid;
+        /* Maximum number of concurrent sound models loaded */
+        uint32_t maxSoundModels;
+        /* Maximum number of key phrases */
+        uint32_t maxKeyPhrases;
+        /* Maximum number of concurrent users detected */
+        uint32_t maxUsers;
+        /* All supported modes. e.g RecognitionMode.VOICE_TRIGGER */
+        uint32_t recognitionModes;
+        /* Supports seamless transition from detection to capture */
+        bool     captureTransition;
+        /* Maximum buffering capacity in ms if captureTransition is true */
+        uint32_t maxBufferMs;
+        /* Supports capture by other use cases while detection is active */
+        bool     concurrentCapture;
+        /* Returns the trigger capture in event */
+        bool     triggerInEvent;
+        /* Rated power consumption when detection is active with TDB
+         * silence/sound/speech ratio */
+        uint32_t powerConsumptionMw;
+    };
+
+
+    /*
+     * Base sound model descriptor. This struct is the header of a larger block
+     * passed to loadSoundModel() and contains the binary data of the
+     * sound model.
+     */
+    struct SoundModel {
+        /* Model type. e.g. SoundModelType.KEYPHRASE */
+        SoundModelType type;
+        /* Unique sound model ID. */
+        Uuid           uuid;
+        /* Unique vendor ID. Identifies the engine the sound model
+         * was build for */
+        Uuid           vendorUuid;
+        /* Opaque data transparent to Android framework */
+        vec<uint8_t>   data;
+    };
+
+    /* Key phrase descriptor */
+    struct Phrase {
+        /* Unique keyphrase ID assigned at enrollment time */
+        uint32_t      id;
+        /* Recognition modes supported by this key phrase */
+        uint32_t      recognitionModes;
+        /* List of users IDs associated with this key phrase */
+        vec<uint32_t> users;
+        /* Locale - Java Locale style (e.g. en_US) */
+        string        locale;
+        /* Phrase text in UTF-8 format. */
+        string        text;
+    };
+
+    /*
+     * Specialized sound model for key phrase detection.
+     * Proprietary representation of key phrases in binary data must match
+     * information indicated by phrases field
+     */
+    struct PhraseSoundModel {
+        /* Common part of sound model descriptor */
+        SoundModel  common;
+        /* List of descriptors for key phrases supported by this sound model */
+        vec<Phrase> phrases;
+    };
+
+    /*
+     * Configuration for sound trigger capture session passed to
+     * startRecognition() method
+     */
+    struct RecognitionConfig {
+        /* IO handle that will be used for capture. N/A if captureRequested
+         * is false */
+        AudioIoHandle   captureHandle;
+        /* Input device requested for detection capture */
+        AudioDevice     captureDevice;
+        /* Capture and buffer audio for this recognition instance */
+        bool            captureRequested;
+        /* Configuration for each key phrase */
+        vec<PhraseRecognitionExtra> phrases;
+        /* Opaque capture configuration data transparent to the framework */
+        vec<uint8_t>    data;
+    };
+
+
+    /*
+     * Retrieve implementation properties.
+     * @return retval Operation completion status: 0 in case of success,
+     *                -ENODEV in case of initialization error.
+     * @return properties A Properties structure containing implementation
+     *                    description and capabilities.
+     */
+    getProperties() generates (int32_t retval, Properties properties);
+
+    /*
+     * Load a sound model. Once loaded, recognition of this model can be
+     * started and stopped. Only one active recognition per model at a time.
+     * The SoundTrigger service must handle concurrent recognition requests by
+     * different users/applications on the same model.
+     * The implementation returns a unique handle used by other functions
+     * (unloadSoundModel(), startRecognition(), etc...
+     * @param soundModel A SoundModel structure describing the sound model to
+     *                   load.
+     * @param callback The callback interface on which the soundmodelCallback()
+     *                 method will be called upon completion.
+     * @param cookie The value of the cookie argument passed to the completion
+     *               callback. This unique context information is assigned and
+     *               used only by the framework.
+     * @return retval Operation completion status: 0 in case of success,
+     *                -EINVAL in case of invalid sound model (e.g 0 data size),
+     *                -ENOSYS in case of invalid operation (e.g max number of
+     *                models exceeded),
+     *                -ENOMEM in case of memory allocation failure,
+     *                -ENODEV in case of initialization error.
+     * @return modelHandle A unique handle assigned by the HAL for use by the
+     *                framework when controlling activity for this sound model.
+     */
+    loadSoundModel(SoundModel soundModel,
+                   ISoundTriggerHwCallback callback,
+                   CallbackCookie cookie)
+            generates (int32_t retval, SoundModelHandle modelHandle);
+
+    /*
+     * Load a key phrase sound model. Once loaded, recognition of this model can
+     * be started and stopped. Only one active recognition per model at a time.
+     * The SoundTrigger service must handle concurrent recognition requests by
+     * different users/applications on the same model.
+     * The implementation returns a unique handle used by other functions
+     * (unloadSoundModel(), startRecognition(), etc...
+     * @param soundModel A PhraseSoundModel structure describing the sound model
+     *                   to load.
+     * @param callback The callback interface on which the soundmodelCallback()
+     *                 method will be called upon completion.
+     * @param cookie The value of the cookie argument passed to the completion
+     *               callback. This unique context information is assigned and
+     *               used only by the framework.
+     * @return retval Operation completion status: 0 in case of success,
+     *                -EINVAL in case of invalid sound model (e.g 0 data size),
+     *                -ENOSYS in case of invalid operation (e.g max number of
+     *                models exceeded),
+     *                -ENOMEM in case of memory allocation failure,
+     *                -ENODEV in case of initialization error.
+     * @return modelHandle A unique handle assigned by the HAL for use by the
+     *                framework when controlling activity for this sound model.
+     */
+    loadPhraseSoundModel(PhraseSoundModel soundModel,
+                   ISoundTriggerHwCallback callback,
+                   CallbackCookie cookie)
+            generates (int32_t retval, SoundModelHandle modelHandle);
+
+    /*
+     * Unload a sound model. A sound model may be unloaded to make room for a
+     * new one to overcome implementation limitations.
+     * @param modelHandle the handle of the sound model to unload
+     * @return retval Operation completion status: 0 in case of success,
+     *                -ENOSYS if the model is not loaded,
+     *                -ENODEV in case of initialization error.
+     */
+    unloadSoundModel(SoundModelHandle modelHandle)
+            generates (int32_t retval);
+
+    /*
+     * Start recognition on a given model. Only one recognition active
+     * at a time per model. Once recognition succeeds of fails, the callback
+     * is called.
+     * @param modelHandle the handle of the sound model to use for recognition
+     * @param config A RecognitionConfig structure containing attributes of the
+     *               recognition to perform
+     * @param callback The callback interface on which the recognitionCallback()
+     *                 method must be called upon recognition.
+     * @param cookie The value of the cookie argument passed to the recognition
+     *               callback. This unique context information is assigned and
+     *               used only by the framework.
+     * @return retval Operation completion status: 0 in case of success,
+     *                -EINVAL in case of invalid recognition attributes,
+     *                -ENOSYS in case of invalid model handle,
+     *                -ENOMEM in case of memory allocation failure,
+     *                -ENODEV in case of initialization error.
+     */
+    startRecognition(SoundModelHandle modelHandle,
+                     RecognitionConfig config,
+                     ISoundTriggerHwCallback callback,
+                     CallbackCookie cookie)
+            generates (int32_t retval);
+
+    /*
+     * Stop recognition on a given model.
+     * The implementation must not call the recognition callback when stopped
+     * via this method.
+     * @param modelHandle The handle of the sound model to use for recognition
+     * @return retval Operation completion status: 0 in case of success,
+     *                -ENOSYS in case of invalid model handle,
+     *                -ENODEV in case of initialization error.
+     */
+    stopRecognition(SoundModelHandle modelHandle)
+            generates (int32_t retval);
+
+    /*
+     * Stop recognition on all models.
+     * @return retval Operation completion status: 0 in case of success,
+     *                -ENODEV in case of initialization error.
+     */
+    stopAllRecognitions()
+            generates (int32_t retval);
+};
diff --git a/soundtrigger/2.0/ISoundTriggerHwCallback.hal b/soundtrigger/2.0/ISoundTriggerHwCallback.hal
new file mode 100644 (file)
index 0000000..c6555f6
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright 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 android.hardware.soundtrigger@2.0;
+
+import android.hardware.audio.common@2.0;
+
+interface ISoundTriggerHwCallback {
+    enum RecognitionStatus : uint32_t {
+        SUCCESS  = 0,
+        ABORT    = 1,
+        FAILURE  = 2,
+    };
+
+    enum SoundModelStatus : uint32_t {
+        UPDATED  = 0,
+    };
+
+    /*
+     * Generic recognition event sent via recognition callback
+     */
+    struct RecognitionEvent {
+        /* Recognition status e.g. SUCCESS */
+        RecognitionStatus status;
+        /* Sound model type for this event. e.g SoundModelType.TYPE_KEYPHRASE */
+        SoundModelType    type;
+        /* Handle of loaded sound model which triggered the event */
+        SoundModelHandle  model;
+        /* It is possible to capture audio from this */
+        /* utterance buffered by the implementation */
+        bool              captureAvailable;
+        /* Audio session ID. framework use */
+        int32_t           captureSession;
+        /* Delay in ms between end of model detection and start of audio
+        /* available for capture. A negative value is possible
+         * (e.g. if key phrase is also available for capture */
+        int32_t           captureDelayMs;
+        /* Duration in ms of audio captured before the start of the trigger.
+         * 0 if none. */
+        int32_t           capturePreambleMs;
+        /* The opaque data is the capture of the trigger sound */
+        bool              triggerInData;
+        /* Audio format of either the trigger in event data or to use for
+         * capture of the rest of the utterance */
+        AudioConfig       audioConfig;
+        /* Opaque event data */
+        vec<uint8_t>      data;
+    };
+
+    /*
+     * Specialized recognition event for key phrase recognitions
+     */
+    struct PhraseRecognitionEvent {
+        /* Common part of the recognition event */
+        RecognitionEvent common;
+        /* List of descriptors for each recognized key phrase */
+        vec<PhraseRecognitionExtra> phraseExtras;
+    };
+
+    /*
+     * Event sent via load sound model callback
+     */
+    struct ModelEvent {
+         /* Sound model status e.g. SoundModelStatus.UPDATED */
+        SoundModelStatus status;
+        /* Loaded sound model that triggered the event */
+        SoundModelHandle model;
+        /* Opaque event data, passed transparently by the framework */
+        vec<uint8_t>     data;
+    };
+
+    typedef int32_t CallbackCookie;
+
+    /*
+     * Callback method called by the HAL when the sound recognition triggers
+     * @param event A RecognitionEvent structure containing detailed results
+     *              of the recognition triggered
+     * @param cookie The cookie passed by the framework when recognition was
+     *               started (see ISoundtriggerHw.startRecognition()
+     */
+    recognitionCallback(RecognitionEvent event, CallbackCookie cookie);
+
+    /*
+     * Callback method called by the HAL when the sound recognition triggers
+     * for a key phrase sound model.
+     * @param event A RecognitionEvent structure containing detailed results
+     *              of the recognition triggered
+     * @param cookie The cookie passed by the framework when recognition was
+     *               started (see ISoundtriggerHw.startRecognition()
+     */
+    phraseRecognitionCallback(PhraseRecognitionEvent event,
+                              CallbackCookie cookie);
+    /*
+     * Callback method called by the HAL when the sound model loading completes
+     * @param event A ModelEvent structure containing detailed results of the
+     *              model loading operation
+     * @param cookie The cookie passed by the framework when loading was
+     *               initiated (see ISoundtriggerHw.loadSoundModel()
+     */
+    soundModelCallback(ModelEvent event, CallbackCookie cookie);
+};
diff --git a/soundtrigger/2.0/default/Android.mk b/soundtrigger/2.0/default/Android.mk
new file mode 100644 (file)
index 0000000..4ec64de
--- /dev/null
@@ -0,0 +1,42 @@
+#
+# 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.
+
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.soundtrigger@2.0-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    SoundTriggerHalImpl.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+        libhidl \
+        liblog \
+        libhwbinder \
+        libutils \
+        libhardware \
+        android.hardware.soundtrigger@2.0 \
+        android.hardware.audio.common@2.0
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
+
+ifeq ($(strip $(AUDIOSERVER_MULTILIB)),)
+LOCAL_MULTILIB := 32
+else
+LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
+endif
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/soundtrigger/2.0/default/SoundTriggerHalImpl.cpp b/soundtrigger/2.0/default/SoundTriggerHalImpl.cpp
new file mode 100644 (file)
index 0000000..1ae996a
--- /dev/null
@@ -0,0 +1,595 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "SoundTriggerHalImpl"
+//#define LOG_NDEBUG 0
+
+#include <utils/Log.h>
+#include "SoundTriggerHalImpl.h"
+
+
+namespace android {
+namespace hardware {
+namespace soundtrigger {
+namespace V2_0 {
+namespace implementation {
+
+// static
+void SoundTriggerHalImpl::soundModelCallback(struct sound_trigger_model_event *halEvent,
+                                               void *cookie)
+{
+    if (halEvent == NULL) {
+        ALOGW("soundModelCallback called with NULL event");
+        return;
+    }
+    sp<SoundModelClient> client =
+            wp<SoundModelClient>(static_cast<SoundModelClient *>(cookie)).promote();
+    if (client == 0) {
+        ALOGW("soundModelCallback called on stale client");
+        return;
+    }
+    if (halEvent->model != client->mHalHandle) {
+        ALOGW("soundModelCallback call with wrong handle %d on client with handle %d",
+              (int)halEvent->model, (int)client->mHalHandle);
+        return;
+    }
+
+    ISoundTriggerHwCallback::ModelEvent event;
+    convertSoundModelEventFromHal(&event, halEvent);
+    event.model = client->mId;
+
+    client->mCallback->soundModelCallback(event, client->mCookie);
+}
+
+// static
+void SoundTriggerHalImpl::recognitionCallback(struct sound_trigger_recognition_event *halEvent,
+                                               void *cookie)
+{
+    if (halEvent == NULL) {
+        ALOGW("recognitionCallback call NULL event");
+        return;
+    }
+    sp<SoundModelClient> client =
+            wp<SoundModelClient>(static_cast<SoundModelClient *>(cookie)).promote();
+    if (client == 0) {
+        ALOGW("soundModelCallback called on stale client");
+        return;
+    }
+
+    ISoundTriggerHwCallback::RecognitionEvent *event = convertRecognitionEventFromHal(halEvent);
+    event->model = client->mId;
+    if (halEvent->type == SOUND_MODEL_TYPE_KEYPHRASE) {
+        client->mCallback->phraseRecognitionCallback(
+                *(reinterpret_cast<ISoundTriggerHwCallback::PhraseRecognitionEvent *>(event)),
+                client->mCookie);
+    } else {
+        client->mCallback->recognitionCallback(*event, client->mCookie);
+    }
+    delete event;
+}
+
+
+
+// Methods from ::android::hardware::soundtrigger::V2_0::ISoundTriggerHw follow.
+Return<void> SoundTriggerHalImpl::getProperties(getProperties_cb _hidl_cb)
+{
+    ALOGV("getProperties() mHwDevice %p", mHwDevice);
+    int ret;
+    struct sound_trigger_properties halProperties;
+    ISoundTriggerHw::Properties properties;
+
+    if (mHwDevice == NULL) {
+        ret = -ENODEV;
+        goto exit;
+    }
+
+    ret = mHwDevice->get_properties(mHwDevice, &halProperties);
+
+    convertPropertiesFromHal(&properties, &halProperties);
+
+    ALOGV("getProperties implementor %s recognitionModes %08x",
+          properties.implementor.c_str(), properties.recognitionModes);
+
+exit:
+    _hidl_cb(ret, properties);
+    return Void();
+}
+
+int SoundTriggerHalImpl::doLoadSoundModel(const ISoundTriggerHw::SoundModel& soundModel,
+                                                 const sp<ISoundTriggerHwCallback>& callback,
+                                                 ISoundTriggerHwCallback::CallbackCookie cookie,
+                                                 uint32_t *modelId)
+{
+    int32_t ret = 0;
+    struct sound_trigger_sound_model *halSoundModel;
+    *modelId = 0;
+    sp<SoundModelClient> client;
+
+    ALOGV("doLoadSoundModel() data size %zu", soundModel.data.size());
+
+    if (mHwDevice == NULL) {
+        ret = -ENODEV;
+        goto exit;
+    }
+
+    halSoundModel = convertSoundModelToHal(&soundModel);
+    if (halSoundModel == NULL) {
+        ret = -EINVAL;
+        goto exit;
+    }
+
+    {
+        AutoMutex lock(mLock);
+        do {
+            *modelId = nextUniqueId();
+        } while (mClients.valueFor(*modelId) != 0 && *modelId != 0);
+    }
+    LOG_ALWAYS_FATAL_IF(*modelId == 0,
+                        "wrap around in sound model IDs, num loaded models %d", mClients.size());
+
+    client = new SoundModelClient(*modelId, callback, cookie);
+
+    ret = mHwDevice->load_sound_model(mHwDevice, halSoundModel, soundModelCallback,
+                                          client.get(), &client->mHalHandle);
+
+    free(halSoundModel);
+
+    if (ret != 0) {
+        goto exit;
+    }
+
+    {
+        AutoMutex lock(mLock);
+        mClients.add(*modelId, client);
+    }
+
+exit:
+    return ret;
+}
+
+Return<void> SoundTriggerHalImpl::loadSoundModel(const ISoundTriggerHw::SoundModel& soundModel,
+                                                 const sp<ISoundTriggerHwCallback>& callback,
+                                                 ISoundTriggerHwCallback::CallbackCookie cookie,
+                                                 loadSoundModel_cb _hidl_cb)
+{
+    uint32_t modelId = 0;
+    int32_t ret = doLoadSoundModel(soundModel, callback, cookie, &modelId);
+
+    _hidl_cb(ret, modelId);
+    return Void();
+}
+
+Return<void> SoundTriggerHalImpl::loadPhraseSoundModel(
+                                            const ISoundTriggerHw::PhraseSoundModel& soundModel,
+                                            const sp<ISoundTriggerHwCallback>& callback,
+                                            ISoundTriggerHwCallback::CallbackCookie cookie,
+                                            ISoundTriggerHw::loadPhraseSoundModel_cb _hidl_cb)
+{
+    uint32_t modelId = 0;
+    int32_t ret = doLoadSoundModel((const ISoundTriggerHw::SoundModel&)soundModel,
+                                   callback, cookie, &modelId);
+
+    _hidl_cb(ret, modelId);
+    return Void();
+}
+
+Return<int32_t> SoundTriggerHalImpl::unloadSoundModel(SoundModelHandle modelHandle)
+{
+    int32_t ret;
+    sp<SoundModelClient> client;
+
+    if (mHwDevice == NULL) {
+        ret = -ENODEV;
+        goto exit;
+    }
+
+    {
+        AutoMutex lock(mLock);
+        client = mClients.valueFor(modelHandle);
+        if (client == 0) {
+            ret = -ENOSYS;
+            goto exit;
+        }
+    }
+
+    ret = mHwDevice->unload_sound_model(mHwDevice, client->mHalHandle);
+
+    mClients.removeItem(modelHandle);
+
+exit:
+    return ret;
+}
+
+Return<int32_t> SoundTriggerHalImpl::startRecognition(SoundModelHandle modelHandle,
+                                           const ISoundTriggerHw::RecognitionConfig& config,
+                                           const sp<ISoundTriggerHwCallback>& callback __unused,
+                                           ISoundTriggerHwCallback::CallbackCookie cookie __unused)
+{
+    int32_t ret;
+    sp<SoundModelClient> client;
+    struct sound_trigger_recognition_config *halConfig;
+
+    if (mHwDevice == NULL) {
+        ret = -ENODEV;
+        goto exit;
+    }
+
+    {
+        AutoMutex lock(mLock);
+        client = mClients.valueFor(modelHandle);
+        if (client == 0) {
+            ret = -ENOSYS;
+            goto exit;
+        }
+    }
+
+
+    halConfig = convertRecognitionConfigToHal(&config);
+
+    if (halConfig == NULL) {
+        ret = -EINVAL;
+        goto exit;
+    }
+    ret = mHwDevice->start_recognition(mHwDevice, client->mHalHandle, halConfig,
+                                 recognitionCallback, client.get());
+
+    free(halConfig);
+
+exit:
+    return ret;
+}
+
+Return<int32_t> SoundTriggerHalImpl::stopRecognition(SoundModelHandle modelHandle)
+{
+    int32_t ret;
+    sp<SoundModelClient> client;
+    if (mHwDevice == NULL) {
+        ret = -ENODEV;
+        goto exit;
+    }
+
+    {
+        AutoMutex lock(mLock);
+        client = mClients.valueFor(modelHandle);
+        if (client == 0) {
+            ret = -ENOSYS;
+            goto exit;
+        }
+    }
+
+    ret = mHwDevice->stop_recognition(mHwDevice, client->mHalHandle);
+
+exit:
+    return ret;
+}
+
+Return<int32_t> SoundTriggerHalImpl::stopAllRecognitions()
+{
+    int32_t ret;
+    if (mHwDevice == NULL) {
+        ret = -ENODEV;
+        goto exit;
+    }
+
+    if (mHwDevice->common.version >= SOUND_TRIGGER_DEVICE_API_VERSION_1_1 &&
+            mHwDevice->stop_all_recognitions) {
+        ret = mHwDevice->stop_all_recognitions(mHwDevice);
+    } else {
+        ret = -ENOSYS;
+    }
+exit:
+    return ret;
+}
+
+SoundTriggerHalImpl::SoundTriggerHalImpl(const char *moduleName)
+    : mModuleName(moduleName), mNextModelId(1)
+{
+}
+
+void SoundTriggerHalImpl::onFirstRef()
+{
+    const hw_module_t *mod;
+    int rc;
+
+    if (mModuleName == NULL || strlen(mModuleName) == 0) {
+        mModuleName = "primary";
+    }
+    rc = hw_get_module_by_class(SOUND_TRIGGER_HARDWARE_MODULE_ID, mModuleName, &mod);
+    if (rc != 0) {
+        ALOGE("couldn't load sound trigger module %s.%s (%s)",
+              SOUND_TRIGGER_HARDWARE_MODULE_ID, mModuleName, strerror(-rc));
+        return;
+    }
+    rc = sound_trigger_hw_device_open(mod, &mHwDevice);
+    if (rc != 0) {
+        ALOGE("couldn't open sound trigger hw device in %s.%s (%s)",
+              SOUND_TRIGGER_HARDWARE_MODULE_ID, mModuleName, strerror(-rc));
+        mHwDevice = NULL;
+        return;
+    }
+    if (mHwDevice->common.version < SOUND_TRIGGER_DEVICE_API_VERSION_1_0 ||
+            mHwDevice->common.version > SOUND_TRIGGER_DEVICE_API_VERSION_CURRENT) {
+        ALOGE("wrong sound trigger hw device version %04x", mHwDevice->common.version);
+        sound_trigger_hw_device_close(mHwDevice);
+        mHwDevice = NULL;
+        return;
+    }
+
+    ALOGI("onFirstRef() mModuleName %s mHwDevice %p", mModuleName, mHwDevice);
+}
+
+SoundTriggerHalImpl::~SoundTriggerHalImpl()
+{
+    if (mHwDevice != NULL) {
+        sound_trigger_hw_device_close(mHwDevice);
+    }
+}
+
+uint32_t SoundTriggerHalImpl::nextUniqueId()
+{
+    return (uint32_t) atomic_fetch_add_explicit(&mNextModelId,
+                (uint_fast32_t) 1, memory_order_acq_rel);
+}
+
+void SoundTriggerHalImpl::convertUuidFromHal(Uuid *uuid,
+                                             const sound_trigger_uuid_t *halUuid)
+{
+    uuid->timeLow = halUuid->timeLow;
+    uuid->timeMid = halUuid->timeMid;
+    uuid->versionAndTimeHigh = halUuid->timeHiAndVersion;
+    uuid->variantAndClockSeqHigh = halUuid->clockSeq;
+    memcpy(&uuid->node[0], &halUuid->node[0], 6);
+}
+
+void SoundTriggerHalImpl::convertUuidToHal(sound_trigger_uuid_t *halUuid,
+                                           const Uuid *uuid)
+{
+    halUuid->timeLow = uuid->timeLow;
+    halUuid->timeMid = uuid->timeMid;
+    halUuid->timeHiAndVersion = uuid->versionAndTimeHigh;
+    halUuid->clockSeq = uuid->variantAndClockSeqHigh;
+    memcpy(&halUuid->node[0], &uuid->node[0], 6);
+}
+
+void SoundTriggerHalImpl::convertPropertiesFromHal(
+        ISoundTriggerHw::Properties *properties,
+        const struct sound_trigger_properties *halProperties)
+{
+    properties->implementor = halProperties->implementor;
+    properties->description = halProperties->description;
+    properties->version = halProperties->version;
+    convertUuidFromHal(&properties->uuid, &halProperties->uuid);
+    properties->maxSoundModels = halProperties->max_sound_models;
+    properties->maxKeyPhrases = halProperties->max_key_phrases;
+    properties->maxUsers = halProperties->max_users;
+    properties->recognitionModes = halProperties->recognition_modes;
+    properties->captureTransition = halProperties->capture_transition;
+    properties->maxBufferMs = halProperties->max_buffer_ms;
+    properties->concurrentCapture = halProperties->concurrent_capture;
+    properties->triggerInEvent = halProperties->trigger_in_event;
+    properties->powerConsumptionMw = halProperties->power_consumption_mw;
+
+}
+
+void SoundTriggerHalImpl::convertTriggerPhraseToHal(
+        struct sound_trigger_phrase *halTriggerPhrase,
+        const ISoundTriggerHw::Phrase *triggerPhrase)
+{
+    halTriggerPhrase->id = triggerPhrase->id;
+    halTriggerPhrase->recognition_mode = triggerPhrase->recognitionModes;
+    unsigned int i;
+    for (i = 0; i < triggerPhrase->users.size(); i++) {
+        halTriggerPhrase->users[i] = triggerPhrase->users[i];
+    }
+    halTriggerPhrase->num_users = i;
+
+    strlcpy(halTriggerPhrase->locale,
+            triggerPhrase->locale.c_str(), SOUND_TRIGGER_MAX_LOCALE_LEN);
+    strlcpy(halTriggerPhrase->text,
+            triggerPhrase->text.c_str(), SOUND_TRIGGER_MAX_STRING_LEN);
+}
+
+struct sound_trigger_sound_model *SoundTriggerHalImpl::convertSoundModelToHal(
+        const ISoundTriggerHw::SoundModel *soundModel)
+{
+    struct sound_trigger_sound_model *halModel = NULL;
+    if (soundModel->type == SoundModelType::KEYPHRASE) {
+        size_t allocSize =
+                sizeof(struct sound_trigger_phrase_sound_model) + soundModel->data.size();
+        struct sound_trigger_phrase_sound_model *halKeyPhraseModel =
+                static_cast<struct sound_trigger_phrase_sound_model *>(malloc(allocSize));
+        LOG_ALWAYS_FATAL_IF(halKeyPhraseModel == NULL,
+                        "malloc failed for size %zu in convertSoundModelToHal PHRASE", allocSize);
+
+        const ISoundTriggerHw::PhraseSoundModel *keyPhraseModel =
+                reinterpret_cast<const ISoundTriggerHw::PhraseSoundModel *>(soundModel);
+
+        size_t i;
+        for (i = 0; i < keyPhraseModel->phrases.size() && i < SOUND_TRIGGER_MAX_PHRASES; i++) {
+            convertTriggerPhraseToHal(&halKeyPhraseModel->phrases[i],
+                                      &keyPhraseModel->phrases[i]);
+        }
+        halKeyPhraseModel->num_phrases = (unsigned int)i;
+        halModel = reinterpret_cast<struct sound_trigger_sound_model *>(halKeyPhraseModel);
+        halModel->data_offset = sizeof(struct sound_trigger_phrase_sound_model);
+    } else {
+        size_t allocSize =
+                sizeof(struct sound_trigger_sound_model) + soundModel->data.size();
+        halModel = static_cast<struct sound_trigger_sound_model *>(malloc(allocSize));
+        LOG_ALWAYS_FATAL_IF(halModel == NULL,
+                            "malloc failed for size %zu in convertSoundModelToHal GENERIC",
+                            allocSize);
+
+        halModel->data_offset = sizeof(struct sound_trigger_sound_model);
+    }
+    halModel->type = (sound_trigger_sound_model_type_t)soundModel->type;
+    convertUuidToHal(&halModel->uuid, &soundModel->uuid);
+    convertUuidToHal(&halModel->vendor_uuid, &soundModel->vendorUuid);
+    halModel->data_size = soundModel->data.size();
+    uint8_t *dst = reinterpret_cast<uint8_t *>(halModel) + halModel->data_offset;
+    const uint8_t *src = reinterpret_cast<const uint8_t *>(&soundModel->data[0]);
+    memcpy(dst, src, soundModel->data.size());
+
+    return halModel;
+}
+
+void SoundTriggerHalImpl::convertPhraseRecognitionExtraToHal(
+        struct sound_trigger_phrase_recognition_extra *halExtra,
+        const PhraseRecognitionExtra *extra)
+{
+    halExtra->id = extra->id;
+    halExtra->recognition_modes = extra->recognitionModes;
+    halExtra->confidence_level = extra->confidenceLevel;
+
+    unsigned int i;
+    for (i = 0; i < extra->levels.size() && i < SOUND_TRIGGER_MAX_USERS; i++) {
+        halExtra->levels[i].user_id = extra->levels[i].userId;
+        halExtra->levels[i].level = extra->levels[i].levelPercent;
+    }
+    halExtra->num_levels = i;
+}
+
+struct sound_trigger_recognition_config *SoundTriggerHalImpl::convertRecognitionConfigToHal(
+        const ISoundTriggerHw::RecognitionConfig *config)
+{
+    size_t allocSize = sizeof(struct sound_trigger_recognition_config) + config->data.size();
+    struct sound_trigger_recognition_config *halConfig =
+            static_cast<struct sound_trigger_recognition_config *>(malloc(allocSize));
+
+    LOG_ALWAYS_FATAL_IF(halConfig == NULL,
+                        "malloc failed for size %zu in convertRecognitionConfigToHal",
+                        allocSize);
+
+    halConfig->capture_handle = (audio_io_handle_t)config->captureHandle;
+    halConfig->capture_device = (audio_devices_t)config->captureDevice;
+    halConfig->capture_requested = config->captureRequested;
+
+    unsigned int i;
+    for (i = 0; i < config->phrases.size() && i < SOUND_TRIGGER_MAX_PHRASES; i++) {
+        convertPhraseRecognitionExtraToHal(&halConfig->phrases[i],
+                                  &config->phrases[i]);
+    }
+    halConfig->num_phrases = i;
+
+    halConfig->data_offset = sizeof(struct sound_trigger_recognition_config);
+    halConfig->data_size = config->data.size();
+    uint8_t *dst = reinterpret_cast<uint8_t *>(halConfig) + halConfig->data_offset;
+    const uint8_t *src = reinterpret_cast<const uint8_t *>(&config->data[0]);
+    memcpy(dst, src, config->data.size());
+    return halConfig;
+}
+
+// static
+void SoundTriggerHalImpl::convertSoundModelEventFromHal(ISoundTriggerHwCallback::ModelEvent *event,
+                                                const struct sound_trigger_model_event *halEvent)
+{
+    event->status = (ISoundTriggerHwCallback::SoundModelStatus)halEvent->status;
+    // event->model to be remapped by called
+    event->data.setToExternal(
+            const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(halEvent)) + halEvent->data_offset,
+            halEvent->data_size);
+}
+
+// static
+ISoundTriggerHwCallback::RecognitionEvent *SoundTriggerHalImpl::convertRecognitionEventFromHal(
+                                            const struct sound_trigger_recognition_event *halEvent)
+{
+    ISoundTriggerHwCallback::RecognitionEvent * event;
+
+    if (halEvent->type == SOUND_MODEL_TYPE_KEYPHRASE) {
+        const struct sound_trigger_phrase_recognition_event *halPhraseEvent =
+                reinterpret_cast<const struct sound_trigger_phrase_recognition_event *>(halEvent);
+        ISoundTriggerHwCallback::PhraseRecognitionEvent *phraseEvent =
+                new ISoundTriggerHwCallback::PhraseRecognitionEvent();
+
+        PhraseRecognitionExtra *phraseExtras =
+                new PhraseRecognitionExtra[halPhraseEvent->num_phrases];
+        for (unsigned int i = 0; i < halPhraseEvent->num_phrases; i++) {
+            convertPhraseRecognitionExtraFromHal(&phraseExtras[i],
+                                                 &halPhraseEvent->phrase_extras[i]);
+        }
+        phraseEvent->phraseExtras.setToExternal(phraseExtras, halPhraseEvent->num_phrases);
+        // FIXME: transfer buffer ownership. should have a method for that in hidl_vec
+        phraseEvent->phraseExtras.resize(halPhraseEvent->num_phrases);
+        delete[] phraseExtras;
+        event = reinterpret_cast<ISoundTriggerHwCallback::RecognitionEvent *>(phraseEvent);
+    } else {
+        event = new ISoundTriggerHwCallback::RecognitionEvent();
+    }
+
+    event->status = static_cast<ISoundTriggerHwCallback::RecognitionStatus>(halEvent->status);
+    event->type = static_cast<SoundModelType>(halEvent->type);
+    // event->model to be remapped by called
+    event->captureAvailable = halEvent->capture_available;
+    event->captureSession = halEvent->capture_session;
+    event->captureDelayMs = halEvent->capture_delay_ms;
+    event->capturePreambleMs = halEvent->capture_preamble_ms;
+    event->triggerInData = halEvent->trigger_in_data;
+    event->audioConfig.sampleRateHz = halEvent->audio_config.sample_rate;
+    event->audioConfig.channelMask =
+            (audio::common::V2_0::AudioChannelMask)halEvent->audio_config.channel_mask;
+    event->audioConfig.format = (audio::common::V2_0::AudioFormat)halEvent->audio_config.format;
+    event->data.setToExternal(
+            const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(halEvent)) + halEvent->data_offset,
+            halEvent->data_size);
+
+    return event;
+}
+
+// static
+void SoundTriggerHalImpl::convertPhraseRecognitionExtraFromHal(
+        PhraseRecognitionExtra *extra,
+        const struct sound_trigger_phrase_recognition_extra *halExtra)
+{
+    extra->id = halExtra->id;
+    extra->recognitionModes = halExtra->recognition_modes;
+    extra->confidenceLevel = halExtra->confidence_level;
+
+    ConfidenceLevel *levels =
+            new ConfidenceLevel[halExtra->num_levels];
+    for (unsigned int i = 0; i < halExtra->num_levels; i++) {
+        levels[i].userId = halExtra->levels[i].user_id;
+        levels[i].levelPercent = halExtra->levels[i].level;
+    }
+    extra->levels.setToExternal(levels, halExtra->num_levels);
+    // FIXME: transfer buffer ownership. should have a method for that in hidl_vec
+    extra->levels.resize(halExtra->num_levels);
+    delete[] levels;
+}
+
+ISoundTriggerHw *HIDL_FETCH_ISoundTriggerHw(const char *name)
+{
+    if (name != NULL) {
+        if (strncmp(SOUND_TRIGGER_HARDWARE_MODULE_ID, name,
+                strlen(SOUND_TRIGGER_HARDWARE_MODULE_ID)) != 0) {
+            return NULL;
+        }
+        name = strchr(name, '.');
+        if (name == NULL) {
+            return NULL;
+        }
+        name++;
+    }
+    return new SoundTriggerHalImpl(name);
+}
+} // namespace implementation
+}  // namespace V2_0
+}  // namespace soundtrigger
+}  // namespace hardware
+}  // namespace android
+
+
+
diff --git a/soundtrigger/2.0/default/SoundTriggerHalImpl.h b/soundtrigger/2.0/default/SoundTriggerHalImpl.h
new file mode 100644 (file)
index 0000000..4e0d01d
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_HARDWARE_SOUNDTRIGGER_V2_0_IMPLEMENTATION_H
+#define ANDROID_HARDWARE_SOUNDTRIGGER_V2_0_IMPLEMENTATION_H
+
+#include <android/hardware/soundtrigger/2.0/ISoundTriggerHw.h>
+#include <android/hardware/soundtrigger/2.0/ISoundTriggerHwCallback.h>
+#include <hidl/Status.h>
+#include <utils/threads.h>
+#include <utils/KeyedVector.h>
+#include <system/sound_trigger.h>
+#include <hardware/sound_trigger.h>
+
+namespace android {
+namespace hardware {
+namespace soundtrigger {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::Uuid;
+using ::android::hardware::soundtrigger::V2_0::ISoundTriggerHwCallback;
+
+
+class SoundTriggerHalImpl : public ISoundTriggerHw {
+public:
+        explicit SoundTriggerHalImpl(const char *moduleName = NULL);
+
+        // Methods from ::android::hardware::soundtrigger::V2_0::ISoundTriggerHw follow.
+        Return<void> getProperties(getProperties_cb _hidl_cb)  override;
+        Return<void> loadSoundModel(const ISoundTriggerHw::SoundModel& soundModel,
+                                    const sp<ISoundTriggerHwCallback>& callback,
+                                    ISoundTriggerHwCallback::CallbackCookie cookie,
+                                    loadSoundModel_cb _hidl_cb)  override;
+        Return<void> loadPhraseSoundModel(const ISoundTriggerHw::PhraseSoundModel& soundModel,
+                                    const sp<ISoundTriggerHwCallback>& callback,
+                                    ISoundTriggerHwCallback::CallbackCookie cookie,
+                                    loadPhraseSoundModel_cb _hidl_cb)  override;
+
+        Return<int32_t> unloadSoundModel(SoundModelHandle modelHandle)  override;
+        Return<int32_t> startRecognition(SoundModelHandle modelHandle,
+                                      const ISoundTriggerHw::RecognitionConfig& config,
+                                      const sp<ISoundTriggerHwCallback>& callback,
+                                      ISoundTriggerHwCallback::CallbackCookie cookie)  override;
+        Return<int32_t> stopRecognition(SoundModelHandle modelHandle)  override;
+        Return<int32_t> stopAllRecognitions()  override;
+
+        // RefBase
+        virtual     void        onFirstRef();
+
+        static void soundModelCallback(struct sound_trigger_model_event *halEvent,
+                                       void *cookie);
+        static void recognitionCallback(struct sound_trigger_recognition_event *halEvent,
+                                        void *cookie);
+
+private:
+
+        class SoundModelClient : public RefBase {
+        public:
+            SoundModelClient(uint32_t id, sp<ISoundTriggerHwCallback> callback,
+                             ISoundTriggerHwCallback::CallbackCookie cookie)
+                : mId(id), mCallback(callback), mCookie(cookie) {}
+            virtual ~SoundModelClient() {}
+
+            uint32_t mId;
+            sound_model_handle_t mHalHandle;
+            sp<ISoundTriggerHwCallback> mCallback;
+            ISoundTriggerHwCallback::CallbackCookie mCookie;
+        };
+
+        uint32_t nextUniqueId();
+        void convertUuidFromHal(Uuid *uuid,
+                                const sound_trigger_uuid_t *halUuid);
+        void convertUuidToHal(sound_trigger_uuid_t *halUuid,
+                              const Uuid *uuid);
+        void convertPropertiesFromHal(ISoundTriggerHw::Properties *properties,
+                                      const struct sound_trigger_properties *halProperties);
+        void convertTriggerPhraseToHal(struct sound_trigger_phrase *halTriggerPhrase,
+                                       const ISoundTriggerHw::Phrase *triggerPhrase);
+        // returned HAL sound model must be freed by caller
+        struct sound_trigger_sound_model *convertSoundModelToHal(
+                    const ISoundTriggerHw::SoundModel *soundModel);
+        void convertPhraseRecognitionExtraToHal(
+                struct sound_trigger_phrase_recognition_extra *halExtra,
+                const PhraseRecognitionExtra *extra);
+        // returned recognition config must be freed by caller
+        struct sound_trigger_recognition_config *convertRecognitionConfigToHal(
+                const ISoundTriggerHw::RecognitionConfig *config);
+
+
+        static void convertSoundModelEventFromHal(ISoundTriggerHwCallback::ModelEvent *event,
+                                            const struct sound_trigger_model_event *halEvent);
+        static ISoundTriggerHwCallback::RecognitionEvent *convertRecognitionEventFromHal(
+                                            const struct sound_trigger_recognition_event *halEvent);
+        static void convertPhraseRecognitionExtraFromHal(PhraseRecognitionExtra *extra,
+                                    const struct sound_trigger_phrase_recognition_extra *halExtra);
+
+        int doLoadSoundModel(const ISoundTriggerHw::SoundModel& soundModel,
+                             const sp<ISoundTriggerHwCallback>& callback,
+                             ISoundTriggerHwCallback::CallbackCookie cookie,
+                             uint32_t *modelId);
+
+        virtual             ~SoundTriggerHalImpl();
+
+        const char *                                        mModuleName;
+        struct sound_trigger_hw_device*                     mHwDevice;
+        volatile atomic_uint_fast32_t                       mNextModelId;
+        DefaultKeyedVector<int32_t, sp<SoundModelClient> >  mClients;
+        Mutex                                               mLock;
+};
+
+extern "C" ISoundTriggerHw *HIDL_FETCH_ISoundTriggerHw(const char *name);
+
+}  // namespace implementation
+}  // namespace V2_0
+}  // namespace soundtrigger
+}  // namespace hardware
+}  // namespace android
+
+#endif  // ANDROID_HARDWARE_SOUNDTRIGGER_V2_0_IMPLEMENTATION_H
+
diff --git a/soundtrigger/2.0/types.hal b/soundtrigger/2.0/types.hal
new file mode 100644 (file)
index 0000000..26928ba
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright 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 android.hardware.soundtrigger@2.0;
+
+/*
+ * Sound model types modes used in ISoundTriggerHw.SoundModel
+ */
+enum SoundModelType : int32_t {
+    /* use for unspecified sound model type */
+    UNKNOWN   = -1,
+    /* use for key phrase sound models */
+    KEYPHRASE = 0,
+    /* use for all models other than keyphrase */
+    GENERIC   = 1,
+};
+
+typedef int32_t SoundModelHandle;
+
+
+/*
+ * Recognition modes used in ISoundTriggerHw.RecognitionConfig,
+ * ISoundTriggerHw.Properties or PhraseRecognitionExtra
+ */
+enum RecognitionMode : uint32_t {
+    /* simple voice trigger */
+    VOICE_TRIGGER       = (1 << 0),
+    /* trigger only if one user in model identified */
+    USER_IDENTIFICATION = (1 << 1),
+    /* trigger only if one user in mode authenticated */
+    USER_AUTHENTICATION = (1 << 2),
+    /* generic sound trigger */
+    GENERIC_TRIGGER     = (1 << 3),
+};
+
+/*
+ * Confidence level for each user in structure PhraseRecognitionExtra
+ */
+struct ConfidenceLevel {
+    /* user ID */
+    uint32_t userId;
+    /* confidence level in percent (0 - 100): */
+    /* - min level for recognition configuration */
+    /* - detected level for recognition event */
+    uint32_t levelPercent;
+};
+
+/*
+ * Specialized recognition event for key phrase detection
+ */
+struct PhraseRecognitionExtra {
+    /* keyphrase ID */
+    uint32_t id;
+    /* recognition modes used for this keyphrase */
+    uint32_t recognitionModes;
+    /* confidence level for mode RecognitionMode.VOICE_TRIGGER */
+    uint32_t confidenceLevel;
+    /* list of confidence levels per user for
+     * RecognitionMode.USER_IDENTIFICATION and
+     * RecognitionMode.USER_AUTHENTICATION */
+    vec<ConfidenceLevel> levels;
+};
+
+/* TODO(elaurent) remove when Java build problem is fixed */
+union Dummy {
+  uint32_t dummy1;
+  int32_t dummy2;
+};
\ No newline at end of file
diff --git a/soundtrigger/Android.bp b/soundtrigger/Android.bp
new file mode 100644 (file)
index 0000000..c12cd4f
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "2.0",
+]
diff --git a/thermal/1.0/Android.bp b/thermal/1.0/Android.bp
new file mode 100644 (file)
index 0000000..60f2626
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.thermal@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.thermal@1.0",
+    srcs: [
+        "types.hal",
+        "IThermal.hal",
+    ],
+    out: [
+        "android/hardware/thermal/1.0/types.cpp",
+        "android/hardware/thermal/1.0/ThermalAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.thermal@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.thermal@1.0",
+    srcs: [
+        "types.hal",
+        "IThermal.hal",
+    ],
+    out: [
+        "android/hardware/thermal/1.0/types.h",
+        "android/hardware/thermal/1.0/IThermal.h",
+        "android/hardware/thermal/1.0/IHwThermal.h",
+        "android/hardware/thermal/1.0/BnThermal.h",
+        "android/hardware/thermal/1.0/BpThermal.h",
+        "android/hardware/thermal/1.0/BsThermal.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.thermal@1.0",
+    generated_sources: ["android.hardware.thermal@1.0_genc++"],
+    generated_headers: ["android.hardware.thermal@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.thermal@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/thermal/1.0/Android.mk b/thermal/1.0/Android.mk
new file mode 100644 (file)
index 0000000..87879ff
--- /dev/null
@@ -0,0 +1,338 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.thermal@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (CoolingDevice)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/CoolingDevice.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.CoolingDevice
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CoolingType)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/CoolingType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.CoolingType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CpuUsage)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/CpuUsage.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.CpuUsage
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Temperature)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/Temperature.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.Temperature
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (TemperatureType)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/TemperatureType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.TemperatureType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ThermalStatus)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/ThermalStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.ThermalStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ThermalStatusCode)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/ThermalStatusCode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.ThermalStatusCode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IThermal.hal
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/IThermal.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IThermal.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::IThermal
+
+$(GEN): $(LOCAL_PATH)/IThermal.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.thermal@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (CoolingDevice)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/CoolingDevice.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.CoolingDevice
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CoolingType)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/CoolingType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.CoolingType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CpuUsage)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/CpuUsage.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.CpuUsage
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Temperature)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/Temperature.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.Temperature
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (TemperatureType)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/TemperatureType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.TemperatureType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ThermalStatus)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/ThermalStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.ThermalStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (ThermalStatusCode)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/ThermalStatusCode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::types.ThermalStatusCode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IThermal.hal
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/IThermal.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IThermal.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0::IThermal
+
+$(GEN): $(LOCAL_PATH)/IThermal.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.thermal@1.0-java-constants
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+#
+GEN := $(intermediates)/android/hardware/thermal/1.0/Constants.java
+$(GEN): $(HIDL)
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/IThermal.hal
+
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava-constants -randroid.hardware:hardware/interfaces \
+        android.hardware.thermal@1.0
+
+$(GEN):
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+# Avoid dependency cycle of framework.jar -> this-library -> framework.jar
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core-oj
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/thermal/1.0/IThermal.hal b/thermal/1.0/IThermal.hal
new file mode 100644 (file)
index 0000000..e5f70cb
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * 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 android.hardware.thermal@1.0;
+
+interface IThermal {
+
+    /*
+     * Retrieves temperatures in Celsius.
+     *
+     * @return status Status of the operation. If status code is FAILURE,
+     *         the status.debugMessage must be populated with the human-readable
+     *         error message.
+     * @return temperatures If status code is SUCCESS, it's filled with the
+     *         current temperatures. The order of temperatures of built-in
+     *         devices (such as CPUs, GPUs and etc.) in the list must be kept
+     *         the same regardless the number of calls to this method even if
+     *         they go offline, if these devices exist on boot. The method
+     *         always returns and never removes such temperatures.
+     *
+     */
+    @callflow(next={"*"})
+    @entry
+    @exit
+    getTemperatures()
+        generates (ThermalStatus status, vec<Temperature> temperatures);
+
+    /*
+     * Retrieves CPU usage information of each core: active and total times
+     * in ms since first boot.
+     *
+     * @return status Status of the operation. If status code is FAILURE,
+     *         the status.debugMessage must be populated with the human-readable
+     *         error message.
+     * @return cpuUsages If status code is SUCCESS, it's filled with the current
+     *         CPU usages. The order and number of CPUs in the list must be kept
+     *         the same regardless the number of calls to this method.
+     *
+     */
+    @callflow(next={"*"})
+    @entry
+    @exit
+    getCpuUsages() generates (ThermalStatus status, vec<CpuUsage> cpuUsages);
+
+    /*
+     * Retrieves the cooling devices information.
+     *
+     * @return status Status of the operation. If status code is FAILURE,
+     *         the status.debugMessage must be populated with the human-readable
+     *         error message.
+     * @return devices If status code is SUCCESS, it's filled with the current
+     *         cooling device information. The order of built-in cooling
+     *         devices in the list must be kept the same regardless the number
+     *         of calls to this method even if they go offline, if these devices
+     *         exist on boot. The method always returns and never removes from
+     *         the list such cooling devices.
+     *
+     */
+    @callflow(next={"*"})
+    @entry
+    @exit
+    getCoolingDevices()
+        generates (ThermalStatus status, vec<CoolingDevice> devices);
+
+};
diff --git a/thermal/1.0/default/Android.bp b/thermal/1.0/default/Android.bp
new file mode 100644 (file)
index 0000000..626dcaf
--- /dev/null
@@ -0,0 +1,16 @@
+cc_library_shared {
+    name: "android.hardware.thermal@1.0-impl",
+    relative_install_path: "hw",
+    srcs: ["Thermal.cpp"],
+    shared_libs: [
+        "liblog",
+        "libcutils",
+        "libhardware",
+        "libhwbinder",
+        "libbase",
+        "libcutils",
+        "libutils",
+        "libhidl",
+        "android.hardware.thermal@1.0",
+    ],
+}
diff --git a/thermal/1.0/default/Android.mk b/thermal/1.0/default/Android.mk
new file mode 100644 (file)
index 0000000..fa7414e
--- /dev/null
@@ -0,0 +1,39 @@
+#
+# 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_MODULE := android.hardware.thermal@1.0-service
+LOCAL_INIT_RC := android.hardware.thermal@1.0-service.rc
+LOCAL_SRC_FILES := \
+        service.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+        liblog \
+        libcutils \
+        libdl \
+        libbase \
+        libutils \
+        libhardware_legacy \
+        libhardware \
+
+LOCAL_SHARED_LIBRARIES += \
+        libhwbinder \
+        libhidl \
+        android.hardware.thermal@1.0 \
+
+include $(BUILD_EXECUTABLE)
diff --git a/thermal/1.0/default/Thermal.cpp b/thermal/1.0/default/Thermal.cpp
new file mode 100644 (file)
index 0000000..6c2111f
--- /dev/null
@@ -0,0 +1,197 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.thermal@1.0-impl"
+#include <utils/Log.h>
+
+#include <errno.h>
+#include <hardware/hardware.h>
+#include <hardware/thermal.h>
+#include <vector>
+
+#include "Thermal.h"
+
+namespace android {
+namespace hardware {
+namespace thermal {
+namespace V1_0 {
+namespace implementation {
+
+Thermal::Thermal(thermal_module_t* module) : mModule(module) {}
+
+// Methods from ::android::hardware::thermal::V1_0::IThermal follow.
+Return<void> Thermal::getTemperatures(getTemperatures_cb _hidl_cb) {
+  ThermalStatus status;
+  status.code = ThermalStatusCode::SUCCESS;
+  hidl_vec<Temperature> temperatures;
+
+  if (!mModule || !mModule->getTemperatures) {
+    ALOGI("getTemperatures is not implemented in Thermal HAL.");
+    _hidl_cb(status, temperatures);
+    return Void();
+  }
+
+  ssize_t size = mModule->getTemperatures(mModule, nullptr, 0);
+  if (size >= 0) {
+    std::vector<temperature_t> list;
+    list.resize(size);
+    size = mModule->getTemperatures(mModule, list.data(), list.size());
+    if (size >= 0) {
+      temperatures.resize(list.size());
+      for (size_t i = 0; i < list.size(); ++i) {
+        switch (list[i].type) {
+          case DEVICE_TEMPERATURE_UNKNOWN:
+            temperatures[i].type = TemperatureType::UNKNOWN;
+            break;
+          case DEVICE_TEMPERATURE_CPU:
+            temperatures[i].type = TemperatureType::CPU;
+            break;
+          case DEVICE_TEMPERATURE_GPU:
+            temperatures[i].type = TemperatureType::GPU;
+            break;
+          case DEVICE_TEMPERATURE_BATTERY:
+            temperatures[i].type = TemperatureType::BATTERY;
+            break;
+          case DEVICE_TEMPERATURE_SKIN:
+            temperatures[i].type = TemperatureType::SKIN;
+            break;
+          default:
+            ALOGE("Unknown temperature %s type", list[i].name);
+            ;
+        }
+        temperatures[i].name = list[i].name;
+        temperatures[i].currentValue = list[i].current_value;
+        temperatures[i].throttlingThreshold = list[i].throttling_threshold;
+        temperatures[i].shutdownThreshold = list[i].shutdown_threshold;
+        temperatures[i].vrThrottlingThreshold = list[i].vr_throttling_threshold;
+      }
+    }
+  }
+  if (size < 0) {
+    status.code = ThermalStatusCode::FAILURE;
+    status.debugMessage = strerror(-size);
+  }
+  _hidl_cb(status, temperatures);
+  return Void();
+}
+
+Return<void> Thermal::getCpuUsages(getCpuUsages_cb _hidl_cb) {
+  ThermalStatus status;
+  hidl_vec<CpuUsage> cpuUsages;
+  status.code = ThermalStatusCode::SUCCESS;
+
+  if (!mModule || !mModule->getCpuUsages) {
+    ALOGI("getCpuUsages is not implemented in Thermal HAL");
+    _hidl_cb(status, cpuUsages);
+    return Void();
+  }
+
+  ssize_t size = mModule->getCpuUsages(mModule, nullptr);
+  if (size >= 0) {
+    std::vector<cpu_usage_t> list;
+    list.resize(size);
+    size = mModule->getCpuUsages(mModule, list.data());
+    if (size >= 0) {
+      list.resize(size);
+      cpuUsages.resize(size);
+      for (size_t i = 0; i < list.size(); ++i) {
+        cpuUsages[i].name = list[i].name;
+        cpuUsages[i].active = list[i].active;
+        cpuUsages[i].total = list[i].total;
+        cpuUsages[i].isOnline = list[i].is_online;
+      }
+    } else {
+      status.code = ThermalStatusCode::FAILURE;
+      status.debugMessage = strerror(-size);
+    }
+  }
+  if (size < 0) {
+    status.code = ThermalStatusCode::FAILURE;
+    status.debugMessage = strerror(-size);
+  }
+  _hidl_cb(status, cpuUsages);
+  return Void();
+}
+
+Return<void> Thermal::getCoolingDevices(getCoolingDevices_cb _hidl_cb) {
+  ThermalStatus status;
+  status.code = ThermalStatusCode::SUCCESS;
+  hidl_vec<CoolingDevice> coolingDevices;
+
+  if (!mModule || !mModule->getCoolingDevices) {
+    ALOGI("getCoolingDevices is not implemented in Thermal HAL.");
+    _hidl_cb(status, coolingDevices);
+    return Void();
+  }
+
+  ssize_t size = mModule->getCoolingDevices(mModule, nullptr, 0);
+  if (size >= 0) {
+    std::vector<cooling_device_t> list;
+    list.resize(size);
+    size = mModule->getCoolingDevices(mModule, list.data(), list.size());
+    if (size >= 0) {
+      list.resize(size);
+      coolingDevices.resize(list.size());
+      for (size_t i = 0; i < list.size(); ++i) {
+        switch (list[i].type) {
+          case FAN_RPM:
+            coolingDevices[i].type = CoolingType::FAN_RPM;
+            break;
+          default:
+            ALOGE("Unknown cooling device %s type", list[i].name);
+        }
+        coolingDevices[i].name = list[i].name;
+        coolingDevices[i].currentValue = list[i].current_value;
+      }
+    }
+  }
+  if (size < 0) {
+    status.code = ThermalStatusCode::FAILURE;
+    status.debugMessage = strerror(-size);
+  }
+  _hidl_cb(status, coolingDevices);
+  return Void();
+}
+
+IThermal* HIDL_FETCH_IThermal(const char* /* name */) {
+  thermal_module_t* module;
+  status_t err = hw_get_module(THERMAL_HARDWARE_MODULE_ID,
+                               const_cast<hw_module_t const**>(
+                                   reinterpret_cast<hw_module_t**>(&module)));
+  if (err || !module) {
+    ALOGE("Couldn't load %s module (%s)", THERMAL_HARDWARE_MODULE_ID,
+          strerror(-err));
+  }
+
+  if (err == 0 && module->common.methods->open) {
+    struct hw_device_t* device;
+    err = module->common.methods->open(&module->common,
+                                       THERMAL_HARDWARE_MODULE_ID, &device);
+    if (err) {
+      ALOGE("Couldn't open %s module (%s)", THERMAL_HARDWARE_MODULE_ID,
+            strerror(-err));
+    } else {
+      return new Thermal(reinterpret_cast<thermal_module_t*>(device));
+    }
+  }
+  return new Thermal(module);
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace thermal
+}  // namespace hardware
+}  // namespace android
diff --git a/thermal/1.0/default/Thermal.h b/thermal/1.0/default/Thermal.h
new file mode 100644 (file)
index 0000000..8212ab9
--- /dev/null
@@ -0,0 +1,45 @@
+#ifndef HIDL_GENERATED_android_hardware_thermal_V1_0_Thermal_H_
+#define HIDL_GENERATED_android_hardware_thermal_V1_0_Thermal_H_
+
+#include <android/hardware/thermal/1.0/IThermal.h>
+#include <hidl/Status.h>
+#include <hardware/thermal.h>
+
+#include <hidl/MQDescriptor.h>
+
+namespace android {
+namespace hardware {
+namespace thermal {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::thermal::V1_0::CoolingDevice;
+using ::android::hardware::thermal::V1_0::CpuUsage;
+using ::android::hardware::thermal::V1_0::IThermal;
+using ::android::hardware::thermal::V1_0::Temperature;
+using ::android::hardware::thermal::V1_0::ThermalStatus;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Thermal : public IThermal {
+    Thermal(thermal_module_t* module);
+    // Methods from ::android::hardware::thermal::V1_0::IThermal follow.
+    Return<void> getTemperatures(getTemperatures_cb _hidl_cb)  override;
+    Return<void> getCpuUsages(getCpuUsages_cb _hidl_cb)  override;
+    Return<void> getCoolingDevices(getCoolingDevices_cb _hidl_cb)  override;
+    private:
+        thermal_module_t* mModule;
+};
+
+extern "C" IThermal* HIDL_FETCH_IThermal(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace thermal
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_thermal_V1_0_Thermal_H_
diff --git a/thermal/1.0/default/android.hardware.thermal@1.0-service.rc b/thermal/1.0/default/android.hardware.thermal@1.0-service.rc
new file mode 100644 (file)
index 0000000..cc7ba6a
--- /dev/null
@@ -0,0 +1,4 @@
+service thermal-hal-1-0 /system/bin/hw/android.hardware.thermal@1.0-service
+    class hal
+    user system
+    group system readproc
diff --git a/thermal/1.0/default/service.cpp b/thermal/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..ea86de4
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.thermal@1.0-service"
+
+#include <android/hardware/thermal/1.0/IThermal.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::thermal::V1_0::IThermal;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IThermal>("thermal");
+}
diff --git a/thermal/1.0/types.hal b/thermal/1.0/types.hal
new file mode 100644 (file)
index 0000000..8864f43
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * 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 android.hardware.thermal@1.0;
+
+/** Device temperature types */
+@export
+enum TemperatureType : int32_t {
+    UNKNOWN = -1,
+    CPU = 0,
+    GPU = 1,
+    BATTERY = 2,
+    SKIN = 3,
+};
+
+enum CoolingType : uint32_t {
+    /** Fan cooling device speed in RPM. */
+    FAN_RPM = 0,
+};
+
+struct Temperature {
+    /**
+     * This temperature's type.
+     */
+    TemperatureType type;
+
+    /**
+     * Name of this temperature.
+     * All temperatures of the same "type" must have a different "name",
+     * e.g., cpu0, battery.
+     */
+    string name;
+
+    /**
+     * Current temperature in Celsius. If not available set by HAL to
+     * UNKNOWN_TEMPERATURE.
+     * Current temperature can be in any units if type=UNKNOWN.
+     */
+    float currentValue;
+
+    /**
+     * Throttling temperature constant for this temperature.
+     * If not available, set by HAL to UNKNOWN_TEMPERATURE.
+     */
+    float throttlingThreshold;
+
+    /**
+     * Shutdown temperature constant for this temperature.
+     * If not available, set by HAL to UNKNOWN_TEMPERATURE.
+     */
+    float shutdownThreshold;
+
+    /**
+     * Threshold temperature above which the VR mode clockrate minimums cannot
+     * be maintained for this device.
+     * If not available, set by HAL to UNKNOWN_TEMPERATURE.
+     */
+    float vrThrottlingThreshold;
+
+};
+
+struct CoolingDevice {
+    /**
+     * This cooling device type.
+     */
+    CoolingType type;
+
+    /**
+     * Name of this cooling device.
+     * All cooling devices of the same "type" must have a different "name".
+     */
+    string name;
+
+    /**
+     * Current cooling device value. Units depend on cooling device "type".
+     */
+    float currentValue;
+
+};
+
+struct CpuUsage {
+    /**
+     * Name of this CPU.
+     * All CPUs must have a different "name".
+     */
+    string name;
+
+    /**
+     * Active time since the last boot in ms.
+     */
+    uint64_t active;
+
+    /**
+     * Total time since the last boot in ms.
+     */
+    uint64_t total;
+
+    /**
+     * Is set to true when a core is online.
+     * If the core is offline, all other members except |name| should be ignored.
+     */
+    bool isOnline;
+
+};
+
+enum ThermalStatusCode : uint32_t {
+    /** No errors. */
+    SUCCESS = 0,
+    /** Unknown failure occured. */
+    FAILURE = 1
+};
+
+/**
+ * Generic structure to return the status of any thermal operation.
+ */
+struct ThermalStatus {
+    ThermalStatusCode code;
+
+    /**
+     * A specific error message to provide more information.
+     * This can be used for debugging purposes only.
+     */
+    string debugMessage;
+};
+
+/**
+ * TODO(pbond): add float constant UNDEFINED_TEMPERATURE.
+ */
diff --git a/thermal/1.0/vts/Android.mk b/thermal/1.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..f1ac716
--- /dev/null
@@ -0,0 +1,84 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for Thermal v1.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_thermal@1.0
+
+LOCAL_SRC_FILES := \
+  Thermal.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES := \
+  android.hardware.thermal@1.0 \
+  system/core/base/include \
+  system/core/include \
+
+LOCAL_SHARED_LIBRARIES += \
+  android.hardware.thermal@1.0 \
+  libbase \
+  libutils \
+  libcutils \
+  liblog \
+  libhidl \
+  libhwbinder \
+  libprotobuf-cpp-full \
+  libvts_common \
+  libvts_datatype \
+  libvts_measurement \
+  libvts_multidevice_proto \
+
+LOCAL_STATIC_LIBRARIES := \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for thermal.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_thermal@1.0
+
+LOCAL_SRC_FILES := \
+   Thermal.vts \
+   types.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.thermal@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/thermal/1.0/vts/Thermal.vts b/thermal/1.0/vts/Thermal.vts
new file mode 100644 (file)
index 0000000..e76d943
--- /dev/null
@@ -0,0 +1,82 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "IThermal"
+
+package: "android.hardware.thermal"
+
+import: "android.hardware.thermal@1.0::types"
+
+interface: {
+    api: {
+        name: "getTemperatures"
+        return_type_hidl: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::thermal::V1_0::ThermalStatus"
+        }
+        return_type_hidl: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_STRUCT
+                predefined_type: "::android::hardware::thermal::V1_0::Temperature"
+            }
+        }
+        callflow: {
+            next: "*"
+        }
+        callflow: {
+            entry: true
+        }
+        callflow: {
+            exit: true
+        }
+    }
+
+    api: {
+        name: "getCpuUsages"
+        return_type_hidl: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::thermal::V1_0::ThermalStatus"
+        }
+        return_type_hidl: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_STRUCT
+                predefined_type: "::android::hardware::thermal::V1_0::CpuUsage"
+            }
+        }
+        callflow: {
+            next: "*"
+        }
+        callflow: {
+            entry: true
+        }
+        callflow: {
+            exit: true
+        }
+    }
+
+    api: {
+        name: "getCoolingDevices"
+        return_type_hidl: {
+            type: TYPE_STRUCT
+            predefined_type: "::android::hardware::thermal::V1_0::ThermalStatus"
+        }
+        return_type_hidl: {
+            type: TYPE_VECTOR
+            vector_value: {
+                type: TYPE_STRUCT
+                predefined_type: "::android::hardware::thermal::V1_0::CoolingDevice"
+            }
+        }
+        callflow: {
+            next: "*"
+        }
+        callflow: {
+            entry: true
+        }
+        callflow: {
+            exit: true
+        }
+    }
+
+}
diff --git a/thermal/1.0/vts/functional/Android.bp b/thermal/1.0/vts/functional/Android.bp
new file mode 100644 (file)
index 0000000..7e0d1d0
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// 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.
+//
+
+cc_test {
+    name: "thermal_hidl_hal_test",
+    gtest: true,
+    srcs: ["thermal_hidl_hal_test.cpp"],
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libcutils",
+        "libhidl",
+        "libhwbinder",
+        "libnativehelper",
+        "libutils",
+        "android.hardware.thermal@1.0",
+    ],
+    static_libs: ["libgtest"],
+    cflags: [
+        "-O0",
+        "-g",
+    ],
+}
+
diff --git a/thermal/1.0/vts/functional/thermal_hidl_hal_test.cpp b/thermal/1.0/vts/functional/thermal_hidl_hal_test.cpp
new file mode 100644 (file)
index 0000000..e3b00ab
--- /dev/null
@@ -0,0 +1,219 @@
+/*
+ * 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.
+ */
+
+#include <algorithm>
+#include <cmath>
+#include <string>
+#include <vector>
+
+#define LOG_TAG "thermal_hidl_hal_test"
+
+#include <android-base/logging.h>
+#include <android/hardware/thermal/1.0/IThermal.h>
+#include <android/hardware/thermal/1.0/types.h>
+#include <gtest/gtest.h>
+#include <unistd.h>
+
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::thermal::V1_0::CoolingDevice;
+using ::android::hardware::thermal::V1_0::CpuUsage;
+using ::android::hardware::thermal::V1_0::IThermal;
+using ::android::hardware::thermal::V1_0::Temperature;
+using ::android::hardware::thermal::V1_0::TemperatureType;
+using ::android::hardware::thermal::V1_0::ThermalStatus;
+using ::android::hardware::thermal::V1_0::ThermalStatusCode;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::sp;
+
+#define THERMAL_SERVICE_NAME "thermal"
+#define MONITORING_OPERATION_NUMBER 10
+
+#define UNDEFINED_TEMPERATURE (-FLT_MAX)
+
+#define MAX_DEVICE_TEMPERATURE 200
+#define MAX_FAN_SPEED 20000
+
+// The main test class for THERMAL HIDL HAL.
+class ThermalHidlTest : public ::testing::Test {
+ public:
+  virtual void SetUp() override {
+    thermal_ = IThermal::getService(THERMAL_SERVICE_NAME, false);
+    ASSERT_NE(thermal_, nullptr);
+    baseSize_ = 0;
+    names_.clear();
+  }
+
+  virtual void TearDown() override {}
+
+ protected:
+  // Check validity of temperatures returned by Thremal HAL.
+  void checkTemperatures(const hidl_vec<Temperature> temperatures) {
+    size_t size = temperatures.size();
+    EXPECT_LE(baseSize_, size);
+
+    for (size_t i = 0; i < size; ++i) {
+      checkDeviceTemperature(temperatures[i]);
+      if (i < baseSize_) {
+        EXPECT_EQ(names_[i], temperatures[i].name.c_str());
+      } else {
+        // Names must be unique.
+        EXPECT_EQ(names_.end(), std::find(names_.begin(), names_.end(),
+                                          temperatures[i].name.c_str()));
+        names_.push_back(temperatures[i].name);
+      }
+    }
+    baseSize_ = size;
+  }
+
+  // Check validity of CPU usages returned by Thermal HAL.
+  void checkCpuUsages(const hidl_vec<CpuUsage>& cpuUsages) {
+    size_t size = cpuUsages.size();
+    // A number of CPU's does not change.
+    if (baseSize_ != 0) EXPECT_EQ(baseSize_, size);
+
+    for (size_t i = 0; i < size; ++i) {
+      checkCpuUsage(cpuUsages[i]);
+      if (i < baseSize_) {
+        EXPECT_EQ(names_[i], cpuUsages[i].name.c_str());
+      } else {
+        // Names must be unique.
+        EXPECT_EQ(names_.end(), std::find(names_.begin(), names_.end(),
+                                          cpuUsages[i].name.c_str()));
+        names_.push_back(cpuUsages[i].name);
+      }
+    }
+    baseSize_ = size;
+  }
+
+  // Check validity of cooling devices information returned by Thermal HAL.
+  void checkCoolingDevices(const hidl_vec<CoolingDevice> coolingDevices) {
+    size_t size = coolingDevices.size();
+    EXPECT_LE(baseSize_, size);
+
+    for (size_t i = 0; i < size; ++i) {
+      checkCoolingDevice(coolingDevices[i]);
+      if (i < baseSize_) {
+        EXPECT_EQ(names_[i], coolingDevices[i].name.c_str());
+      } else {
+        // Names must be unique.
+        EXPECT_EQ(names_.end(), std::find(names_.begin(), names_.end(),
+                                          coolingDevices[i].name.c_str()));
+        names_.push_back(coolingDevices[i].name);
+      }
+    }
+    baseSize_ = size;
+  }
+
+  sp<IThermal> thermal_;
+
+ private:
+  // Check validity of temperature returned by Thermal HAL.
+  void checkDeviceTemperature(const Temperature& temperature) {
+    // .currentValue of known type is in Celsius and must be reasonable.
+    EXPECT_TRUE(temperature.type == TemperatureType::UNKNOWN ||
+                std::abs(temperature.currentValue) < MAX_DEVICE_TEMPERATURE ||
+                temperature.currentValue == UNDEFINED_TEMPERATURE);
+
+    // .name must not be empty.
+    EXPECT_LT(0u, temperature.name.size());
+
+    // .currentValue must not exceed .shutdwonThreshold if defined.
+    EXPECT_TRUE(temperature.currentValue < temperature.shutdownThreshold ||
+                temperature.currentValue == UNDEFINED_TEMPERATURE ||
+                temperature.shutdownThreshold == UNDEFINED_TEMPERATURE);
+
+    // .throttlingThreshold must not exceed .shutdownThreshold if defined.
+    EXPECT_TRUE(temperature.throttlingThreshold <
+                    temperature.shutdownThreshold ||
+                temperature.throttlingThreshold == UNDEFINED_TEMPERATURE ||
+                temperature.shutdownThreshold == UNDEFINED_TEMPERATURE);
+  }
+
+  // Check validity of CPU usage returned by Thermal HAL.
+  void checkCpuUsage(const CpuUsage& cpuUsage) {
+    // .active must be less than .total if CPU is online.
+    EXPECT_TRUE(!cpuUsage.isOnline ||
+                (cpuUsage.active >= 0 && cpuUsage.total >= 0 &&
+                 cpuUsage.total >= cpuUsage.active));
+
+    // .name must be not empty.
+    EXPECT_LT(0u, cpuUsage.name.size());
+  }
+
+  // Check validity of a cooling device information returned by Thermal HAL.
+  void checkCoolingDevice(const CoolingDevice& coolingDevice) {
+    EXPECT_LE(0, coolingDevice.currentValue);
+    EXPECT_GT(MAX_FAN_SPEED, coolingDevice.currentValue);
+    EXPECT_LT(0u, coolingDevice.name.size());
+  }
+
+  size_t baseSize_;
+  std::vector<hidl_string> names_;
+};
+
+// Sanity test for Thermal::getTemperatures().
+TEST_F(ThermalHidlTest, TemperatureTest) {
+  hidl_vec<Temperature> passed;
+  for (size_t i = 0; i < MONITORING_OPERATION_NUMBER; ++i) {
+    thermal_->getTemperatures(
+        [&passed](ThermalStatus status, hidl_vec<Temperature> temperatures) {
+          EXPECT_EQ(ThermalStatusCode::SUCCESS, status.code);
+          passed = temperatures;
+        });
+
+    checkTemperatures(passed);
+    sleep(1);
+  }
+}
+
+// Sanity test for Thermal::getCpuUsages().
+TEST_F(ThermalHidlTest, CpuUsageTest) {
+  hidl_vec<CpuUsage> passed;
+  for (size_t i = 0; i < MONITORING_OPERATION_NUMBER; ++i) {
+    thermal_->getCpuUsages(
+        [&passed](ThermalStatus status, hidl_vec<CpuUsage> cpuUsages) {
+          EXPECT_EQ(ThermalStatusCode::SUCCESS, status.code);
+          passed = cpuUsages;
+        });
+
+    checkCpuUsages(passed);
+    sleep(1);
+  }
+}
+
+// Sanity test for Thermal::getCoolingDevices().
+TEST_F(ThermalHidlTest, CoolingDeviceTest) {
+  hidl_vec<CoolingDevice> passed;
+  for (size_t i = 0; i < MONITORING_OPERATION_NUMBER; ++i) {
+    thermal_->getCoolingDevices([&passed](
+        ThermalStatus status, hidl_vec<CoolingDevice> coolingDevices) {
+      EXPECT_EQ(ThermalStatusCode::SUCCESS, status.code);
+      passed = coolingDevices;
+    });
+
+    checkCoolingDevices(passed);
+    sleep(1);
+  }
+}
+
+int main(int argc, char** argv) {
+  ::testing::InitGoogleTest(&argc, argv);
+  int status = RUN_ALL_TESTS();
+  ALOGI("Test result = %d", status);
+  return status;
+}
diff --git a/thermal/1.0/vts/types.vts b/thermal/1.0/vts/types.vts
new file mode 100644 (file)
index 0000000..1e60f48
--- /dev/null
@@ -0,0 +1,157 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "types"
+
+package: "android.hardware.thermal"
+
+
+attribute: {
+    name: "::android::hardware::thermal::V1_0::TemperatureType"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "UNKNOWN"
+        scalar_value: {
+            uint32_t: 1000
+        }
+        enumerator: "CPU"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "GPU"
+        scalar_value: {
+            uint32_t: 1
+        }
+        enumerator: "BATTERY"
+        scalar_value: {
+            uint32_t: 2
+        }
+        enumerator: "SKIN"
+        scalar_value: {
+            uint32_t: 3
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::thermal::V1_0::CoolingType"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "FAN_RPM"
+        scalar_value: {
+            uint32_t: 0
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::thermal::V1_0::Temperature"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "type"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::thermal::V1_0::TemperatureType"
+    }
+    struct_value: {
+        name: "name"
+        type: TYPE_STRING
+    }
+    struct_value: {
+        name: "currentValue"
+        type: TYPE_SCALAR
+        scalar_type: "float_t"
+    }
+    struct_value: {
+        name: "throttlingThreshold"
+        type: TYPE_SCALAR
+        scalar_type: "float_t"
+    }
+    struct_value: {
+        name: "shutdownThreshold"
+        type: TYPE_SCALAR
+        scalar_type: "float_t"
+    }
+    struct_value: {
+        name: "vrThrottlingThreshold"
+        type: TYPE_SCALAR
+        scalar_type: "float_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::thermal::V1_0::CoolingDevice"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "type"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::thermal::V1_0::CoolingType"
+    }
+    struct_value: {
+        name: "name"
+        type: TYPE_STRING
+    }
+    struct_value: {
+        name: "currentValue"
+        type: TYPE_SCALAR
+        scalar_type: "float_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::thermal::V1_0::CpuUsage"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "name"
+        type: TYPE_STRING
+    }
+    struct_value: {
+        name: "active"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+    struct_value: {
+        name: "total"
+        type: TYPE_SCALAR
+        scalar_type: "uint64_t"
+    }
+    struct_value: {
+        name: "isOnline"
+        type: TYPE_SCALAR
+        scalar_type: "bool_t"
+    }
+}
+
+attribute: {
+    name: "::android::hardware::thermal::V1_0::ThermalStatusCode"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "SUCCESS"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "FAILURE"
+        scalar_value: {
+            uint32_t: 1
+        }
+    }
+}
+
+attribute: {
+    name: "::android::hardware::thermal::V1_0::ThermalStatus"
+    type: TYPE_STRUCT
+    struct_value: {
+        name: "code"
+        type: TYPE_ENUM
+        predefined_type: "::android::hardware::thermal::V1_0::ThermalStatusCode"
+    }
+    struct_value: {
+        name: "debugMessage"
+        type: TYPE_STRING
+    }
+}
+
diff --git a/thermal/Android.bp b/thermal/Android.bp
new file mode 100644 (file)
index 0000000..ed19a37
--- /dev/null
@@ -0,0 +1,6 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+    "1.0/default",
+    "1.0/vts/functional",
+]
diff --git a/tv/Android.bp b/tv/Android.bp
new file mode 100644 (file)
index 0000000..5ad82f4
--- /dev/null
@@ -0,0 +1,5 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "cec/1.0",
+    "input/1.0",
+]
diff --git a/tv/cec/1.0/Android.bp b/tv/cec/1.0/Android.bp
new file mode 100644 (file)
index 0000000..bb1ae82
--- /dev/null
@@ -0,0 +1,59 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.tv.cec@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.tv.cec@1.0",
+    srcs: [
+        "types.hal",
+        "IHdmiCec.hal",
+        "IHdmiCecCallback.hal",
+    ],
+    out: [
+        "android/hardware/tv/cec/1.0/types.cpp",
+        "android/hardware/tv/cec/1.0/HdmiCecAll.cpp",
+        "android/hardware/tv/cec/1.0/HdmiCecCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.tv.cec@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.tv.cec@1.0",
+    srcs: [
+        "types.hal",
+        "IHdmiCec.hal",
+        "IHdmiCecCallback.hal",
+    ],
+    out: [
+        "android/hardware/tv/cec/1.0/types.h",
+        "android/hardware/tv/cec/1.0/IHdmiCec.h",
+        "android/hardware/tv/cec/1.0/IHwHdmiCec.h",
+        "android/hardware/tv/cec/1.0/BnHdmiCec.h",
+        "android/hardware/tv/cec/1.0/BpHdmiCec.h",
+        "android/hardware/tv/cec/1.0/BsHdmiCec.h",
+        "android/hardware/tv/cec/1.0/IHdmiCecCallback.h",
+        "android/hardware/tv/cec/1.0/IHwHdmiCecCallback.h",
+        "android/hardware/tv/cec/1.0/BnHdmiCecCallback.h",
+        "android/hardware/tv/cec/1.0/BpHdmiCecCallback.h",
+        "android/hardware/tv/cec/1.0/BsHdmiCecCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.tv.cec@1.0",
+    generated_sources: ["android.hardware.tv.cec@1.0_genc++"],
+    generated_headers: ["android.hardware.tv.cec@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.tv.cec@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/tv/cec/1.0/Android.mk b/tv/cec/1.0/Android.mk
new file mode 100644 (file)
index 0000000..5d6f03f
--- /dev/null
@@ -0,0 +1,518 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.tv.cec@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (AbortReason)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/AbortReason.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.AbortReason
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecDeviceType)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecDeviceType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecDeviceType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecLogicalAddress)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecLogicalAddress.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecLogicalAddress
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecMessage)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecMessage.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecMessage
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecMessageType)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecMessageType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecMessageType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HdmiPortInfo)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/HdmiPortInfo.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.HdmiPortInfo
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HdmiPortType)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/HdmiPortType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.HdmiPortType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HotplugEvent)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/HotplugEvent.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.HotplugEvent
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MaxLength)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/MaxLength.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.MaxLength
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (OptionKey)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/OptionKey.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.OptionKey
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Result)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/Result.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.Result
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SendMessageResult)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/SendMessageResult.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.SendMessageResult
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IHdmiCec.hal
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/IHdmiCec.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IHdmiCec.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/IHdmiCecCallback.hal
+$(GEN): $(LOCAL_PATH)/IHdmiCecCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::IHdmiCec
+
+$(GEN): $(LOCAL_PATH)/IHdmiCec.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IHdmiCecCallback.hal
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/IHdmiCecCallback.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IHdmiCecCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::IHdmiCecCallback
+
+$(GEN): $(LOCAL_PATH)/IHdmiCecCallback.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.tv.cec@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (AbortReason)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/AbortReason.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.AbortReason
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecDeviceType)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecDeviceType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecDeviceType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecLogicalAddress)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecLogicalAddress.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecLogicalAddress
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecMessage)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecMessage.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecMessage
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (CecMessageType)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/CecMessageType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.CecMessageType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HdmiPortInfo)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/HdmiPortInfo.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.HdmiPortInfo
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HdmiPortType)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/HdmiPortType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.HdmiPortType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (HotplugEvent)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/HotplugEvent.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.HotplugEvent
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (MaxLength)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/MaxLength.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.MaxLength
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (OptionKey)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/OptionKey.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.OptionKey
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (Result)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/Result.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.Result
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SendMessageResult)
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/SendMessageResult.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::types.SendMessageResult
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IHdmiCec.hal
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/IHdmiCec.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IHdmiCec.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/IHdmiCecCallback.hal
+$(GEN): $(LOCAL_PATH)/IHdmiCecCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::IHdmiCec
+
+$(GEN): $(LOCAL_PATH)/IHdmiCec.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IHdmiCecCallback.hal
+#
+GEN := $(intermediates)/android/hardware/tv/cec/1.0/IHdmiCecCallback.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IHdmiCecCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.tv.cec@1.0::IHdmiCecCallback
+
+$(GEN): $(LOCAL_PATH)/IHdmiCecCallback.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tv/cec/1.0/IHdmiCec.hal b/tv/cec/1.0/IHdmiCec.hal
new file mode 100644 (file)
index 0000000..e8db265
--- /dev/null
@@ -0,0 +1,166 @@
+/*
+ * 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 android.hardware.tv.cec@1.0;
+
+import IHdmiCecCallback;
+
+/*
+ * HDMI-CEC HAL interface definition.
+ */
+interface IHdmiCec {
+    /*
+     * Passes the logical address that must be used in this system.
+     *
+     * HAL must use it to configure the hardware so that the CEC commands
+     * addressed the given logical address can be filtered in. This method must
+     * be able to be called as many times as necessary in order to support
+     * multiple logical devices.
+     *
+     * @param addr Logical address that must be used in this system. It must be
+     *        in the range of valid logical addresses for the call to succeed.
+     * @return result Result status of the operation. SUCCESS if successful,
+     *         FAILURE_INVALID_ARGS if the given logical address is invalid,
+     *         FAILURE_BUSY if device or resource is busy
+     */
+    @callflow(next={"*"})
+    addLogicalAddress(CecLogicalAddress addr) generates (Result result);
+
+    /*
+     * Clears all the logical addresses.
+     *
+     * It is used when the system doesn't need to process CEC command any more,
+     * hence to tell HAL to stop receiving commands from the CEC bus, and change
+     * the state back to the beginning.
+     */
+    @callflow(next="addLogicalAddress")
+    @exit
+    clearLogicalAddress();
+
+    /*
+     * Gets the CEC physical address.
+     *
+     * The physical address depends on the topology of the network formed by
+     * connected HDMI devices. It is therefore likely to change if the cable is
+     * plugged off and on again. It is advised to call getPhysicalAddress to get
+     * the updated address when hot plug event takes place.
+     *
+     * @return result Result status of the operation. SUCCESS if successful,
+     *         FAILURE_INVALID_STATE if HAL cannot retrieve the physical
+     *         address.
+     * @return addr Physical address of this device.
+     */
+    @callflow(next="*")
+    getPhysicalAddress() generates (Result result, uint16_t addr);
+
+    /*
+     * Transmits HDMI-CEC message to other HDMI device.
+     *
+     * The method must be designed to return in a certain amount of time and not
+     * hanging forever which may happen if CEC signal line is pulled low for
+     * some reason.
+     *
+     * It must try retransmission at least once as specified in the section '7.1
+     * Frame Re-transmissions' of the CEC Spec 1.4b.
+     *
+     * @param message CEC message to be sent to other HDMI device.
+     * @return result Result status of the operation. SUCCESS if successful,
+     *         NACK if the sent message is not acknowledged,
+     *         BUSY if the CEC bus is busy.
+     */
+    @callflow(next="*")
+    sendMessage(CecMessage message) generates (SendMessageResult result);
+
+    /*
+     * Sets a callback that HDMI-CEC HAL must later use for incoming CEC
+     * messages or internal HDMI events.
+     *
+     * @param callback Callback object to pass hdmi events to the system. The
+     *        previously registered callback must be replaced with this one.
+     */
+    @callflow(next={"addLogicalAddress"})
+    @entry
+    setCallback(IHdmiCecCallback callback);
+
+    /*
+     * Returns the CEC version supported by underlying hardware.
+     *
+     * @return version the CEC version supported by underlying hardware.
+     */
+    @callflow(next={"*"})
+    getCecVersion() generates (int32_t version);
+
+    /*
+     * Gets the identifier of the vendor.
+     *
+     * @return vendorId Identifier of the vendor that is the 24-bit unique
+     *         company ID obtained from the IEEE Registration Authority
+     *         Committee (RAC). The upper 8 bits must be 0.
+     */
+    @callflow(next={"*"})
+    getVendorId() generates (uint32_t vendorId);
+
+    /*
+     * Gets the hdmi port information of underlying hardware.
+     *
+     * @return infos The list of HDMI port information
+     */
+    @callflow(next={"*"})
+    getPortInfo() generates (vec<HdmiPortInfo> infos);
+
+    /*
+     * Sets flags controlling the way HDMI-CEC service works down to HAL
+     * implementation. Those flags must be used in case the feature needs update
+     * in HAL itself, firmware or microcontroller.
+     *
+     * @param key The key of the option to be updated with a new value.
+     * @param value Value to be set.
+     */
+    @callflow(next="*")
+    setOption(OptionKey key, bool value);
+
+    /*
+     * Passes the updated language information of Android system. Contains
+     * three-letter code as defined in ISO/FDIS 639-2. Must be used for HAL to
+     * respond to <Get Menu Language> while in standby mode.
+     *
+     * @param language Three-letter code defined in ISO/FDIS 639-2. Must be
+     *        lowercase letters. (e.g., eng for English)
+     */
+    @callflow(next="*")
+    setLanguage(string language);
+
+    /*
+     * Configures ARC circuit in the hardware logic to start or stop the
+     * feature.
+     *
+     * @param portId Port id to be configured.
+     * @param enable Flag must be either true to start the feature or false to
+     *        stop it.
+     */
+    @callflow(next="*")
+    enableAudioReturnChannel(int32_t portId, bool enable);
+
+    /*
+     * Gets the connection status of the specified port.
+     *
+     * @param portId Port id to be inspected for the connection status.
+     * @return status True if a device is connected, otherwise false. The HAL
+     *         must watch for +5V power signal to determine the status.
+     */
+    @callflow(next="*")
+    isConnected(int32_t portId) generates (bool status);
+};
diff --git a/tv/cec/1.0/IHdmiCecCallback.hal b/tv/cec/1.0/IHdmiCecCallback.hal
new file mode 100644 (file)
index 0000000..4a9d28f
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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 android.hardware.tv.cec@1.0;
+
+interface IHdmiCecCallback {
+    /*
+     * The callback function that must be called by HAL implementation to notify
+     * the system of new CEC message arrival.
+     */
+    oneway onCecMessage(CecMessage message);
+
+    /*
+     * The callback function that must be called by HAL implementation to notify
+     * the system of new hotplug event.
+     */
+    oneway onHotplugEvent(HotplugEvent event);
+};
diff --git a/tv/cec/1.0/default/Android.mk b/tv/cec/1.0/default/Android.mk
new file mode 100644 (file)
index 0000000..3971f6c
--- /dev/null
@@ -0,0 +1,42 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.tv.cec@1.0-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    HdmiCec.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+    libhidl \
+    libhwbinder \
+    liblog \
+    libbase \
+    libutils \
+    libhardware \
+    android.hardware.tv.cec@1.0 \
+
+include $(BUILD_SHARED_LIBRARY)
+
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_MODULE := android.hardware.tv.cec@1.0-service
+LOCAL_INIT_RC := android.hardware.tv.cec@1.0-service.rc
+LOCAL_SRC_FILES := \
+    service.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libcutils \
+    libdl \
+    libbase \
+    libutils \
+    libhardware_legacy \
+    libhardware \
+
+LOCAL_SHARED_LIBRARIES += \
+    libhwbinder \
+    libhidl \
+    android.hardware.tv.cec@1.0 \
+
+include $(BUILD_EXECUTABLE)
diff --git a/tv/cec/1.0/default/HdmiCec.cpp b/tv/cec/1.0/default/HdmiCec.cpp
new file mode 100644 (file)
index 0000000..ebe2681
--- /dev/null
@@ -0,0 +1,415 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.tv.cec@1.0-impl"
+#include <android-base/logging.h>
+
+#include <hardware/hardware.h>
+#include <hardware/hdmi_cec.h>
+#include "HdmiCec.h"
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace cec {
+namespace V1_0 {
+namespace implementation {
+
+static_assert(CEC_DEVICE_INACTIVE == static_cast<int>(CecDeviceType::INACTIVE),
+        "CecDeviceType::INACTIVE must match legacy value.");
+static_assert(CEC_DEVICE_TV == static_cast<int>(CecDeviceType::TV),
+        "CecDeviceType::TV must match legacy value.");
+static_assert(CEC_DEVICE_RECORDER == static_cast<int>(CecDeviceType::RECORDER),
+        "CecDeviceType::RECORDER must match legacy value.");
+static_assert(CEC_DEVICE_TUNER == static_cast<int>(CecDeviceType::TUNER),
+        "CecDeviceType::TUNER must match legacy value.");
+static_assert(CEC_DEVICE_PLAYBACK == static_cast<int>(CecDeviceType::PLAYBACK),
+        "CecDeviceType::PLAYBACK must match legacy value.");
+static_assert(CEC_DEVICE_AUDIO_SYSTEM == static_cast<int>(CecDeviceType::AUDIO_SYSTEM),
+        "CecDeviceType::AUDIO_SYSTEM must match legacy value.");
+static_assert(CEC_DEVICE_MAX == static_cast<int>(CecDeviceType::MAX),
+        "CecDeviceType::MAX must match legacy value.");
+
+static_assert(CEC_ADDR_TV == static_cast<int>(CecLogicalAddress::TV),
+        "CecLogicalAddress::TV must match legacy value.");
+static_assert(CEC_ADDR_RECORDER_1 == static_cast<int>(CecLogicalAddress::RECORDER_1),
+        "CecLogicalAddress::RECORDER_1 must match legacy value.");
+static_assert(CEC_ADDR_RECORDER_2 == static_cast<int>(CecLogicalAddress::RECORDER_2),
+        "CecLogicalAddress::RECORDER_2 must match legacy value.");
+static_assert(CEC_ADDR_TUNER_1 == static_cast<int>(CecLogicalAddress::TUNER_1),
+        "CecLogicalAddress::TUNER_1 must match legacy value.");
+static_assert(CEC_ADDR_PLAYBACK_1 == static_cast<int>(CecLogicalAddress::PLAYBACK_1),
+        "CecLogicalAddress::PLAYBACK_1 must match legacy value.");
+static_assert(CEC_ADDR_AUDIO_SYSTEM == static_cast<int>(CecLogicalAddress::AUDIO_SYSTEM),
+        "CecLogicalAddress::AUDIO_SYSTEM must match legacy value.");
+static_assert(CEC_ADDR_TUNER_2 == static_cast<int>(CecLogicalAddress::TUNER_2),
+        "CecLogicalAddress::TUNER_2 must match legacy value.");
+static_assert(CEC_ADDR_TUNER_3 == static_cast<int>(CecLogicalAddress::TUNER_3),
+        "CecLogicalAddress::TUNER_3 must match legacy value.");
+static_assert(CEC_ADDR_PLAYBACK_2 == static_cast<int>(CecLogicalAddress::PLAYBACK_2),
+        "CecLogicalAddress::PLAYBACK_2 must match legacy value.");
+static_assert(CEC_ADDR_RECORDER_3 == static_cast<int>(CecLogicalAddress::RECORDER_3),
+        "CecLogicalAddress::RECORDER_3 must match legacy value.");
+static_assert(CEC_ADDR_TUNER_4 == static_cast<int>(CecLogicalAddress::TUNER_4),
+        "CecLogicalAddress::TUNER_4 must match legacy value.");
+static_assert(CEC_ADDR_PLAYBACK_3 == static_cast<int>(CecLogicalAddress::PLAYBACK_3),
+        "CecLogicalAddress::PLAYBACK_3 must match legacy value.");
+static_assert(CEC_ADDR_FREE_USE == static_cast<int>(CecLogicalAddress::FREE_USE),
+        "CecLogicalAddress::FREE_USE must match legacy value.");
+static_assert(CEC_ADDR_UNREGISTERED == static_cast<int>(CecLogicalAddress::UNREGISTERED),
+        "CecLogicalAddress::UNREGISTERED must match legacy value.");
+static_assert(CEC_ADDR_BROADCAST == static_cast<int>(CecLogicalAddress::BROADCAST),
+        "CecLogicalAddress::BROADCAST must match legacy value.");
+
+static_assert(CEC_MESSAGE_FEATURE_ABORT == static_cast<int>(CecMessageType::FEATURE_ABORT),
+        "CecMessageType::FEATURE_ABORT must match legacy value.");
+static_assert(CEC_MESSAGE_IMAGE_VIEW_ON == static_cast<int>(CecMessageType::IMAGE_VIEW_ON),
+        "CecMessageType::IMAGE_VIEW_ON must match legacy value.");
+static_assert(CEC_MESSAGE_TUNER_STEP_INCREMENT == static_cast<int>(
+        CecMessageType::TUNER_STEP_INCREMENT),
+        "CecMessageType::TUNER_STEP_INCREMENT must match legacy value.");
+static_assert(CEC_MESSAGE_TUNER_STEP_DECREMENT == static_cast<int>(
+        CecMessageType::TUNER_STEP_DECREMENT),
+        "CecMessageType::TUNER_STEP_DECREMENT must match legacy value.");
+static_assert(CEC_MESSAGE_TUNER_DEVICE_STATUS == static_cast<int>(
+        CecMessageType::TUNER_DEVICE_STATUS),
+        "CecMessageType::TUNER_DEVICE_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_TUNER_DEVICE_STATUS == static_cast<int>(
+        CecMessageType::GIVE_TUNER_DEVICE_STATUS),
+        "CecMessageType::GIVE_TUNER_DEVICE_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_RECORD_ON == static_cast<int>(CecMessageType::RECORD_ON),
+        "CecMessageType::RECORD_ON must match legacy value.");
+static_assert(CEC_MESSAGE_RECORD_STATUS == static_cast<int>(CecMessageType::RECORD_STATUS),
+        "CecMessageType::RECORD_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_RECORD_OFF == static_cast<int>(CecMessageType::RECORD_OFF),
+        "CecMessageType::RECORD_OFF must match legacy value.");
+static_assert(CEC_MESSAGE_TEXT_VIEW_ON == static_cast<int>(CecMessageType::TEXT_VIEW_ON),
+        "CecMessageType::TEXT_VIEW_ON must match legacy value.");
+static_assert(CEC_MESSAGE_RECORD_TV_SCREEN == static_cast<int>(CecMessageType::RECORD_TV_SCREEN),
+        "CecMessageType::RECORD_TV_SCREEN must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_DECK_STATUS == static_cast<int>(CecMessageType::GIVE_DECK_STATUS),
+        "CecMessageType::GIVE_DECK_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_STANDBY == static_cast<int>(CecMessageType::STANDBY),
+        "CecMessageType::STANDBY must match legacy value.");
+static_assert(CEC_MESSAGE_PLAY == static_cast<int>(CecMessageType::PLAY),
+        "CecMessageType::PLAY must match legacy value.");
+static_assert(CEC_MESSAGE_DECK_CONTROL == static_cast<int>(CecMessageType::DECK_CONTROL),
+        "CecMessageType::DECK_CONTROL must match legacy value.");
+static_assert(CEC_MESSAGE_TIMER_CLEARED_STATUS == static_cast<int>(
+        CecMessageType::TIMER_CLEARED_STATUS),
+        "CecMessageType::TIMER_CLEARED_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_USER_CONTROL_PRESSED == static_cast<int>(
+        CecMessageType::USER_CONTROL_PRESSED),
+        "CecMessageType::USER_CONTROL_PRESSED must match legacy value.");
+static_assert(CEC_MESSAGE_USER_CONTROL_RELEASED == static_cast<int>(
+        CecMessageType::USER_CONTROL_RELEASED),
+        "CecMessageType::USER_CONTROL_RELEASED must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_OSD_NAME == static_cast<int>(CecMessageType::GIVE_OSD_NAME),
+        "CecMessageType::GIVE_OSD_NAME must match legacy value.");
+static_assert(CEC_MESSAGE_SET_OSD_NAME == static_cast<int>(CecMessageType::SET_OSD_NAME),
+        "CecMessageType::SET_OSD_NAME must match legacy value.");
+static_assert(CEC_MESSAGE_SYSTEM_AUDIO_MODE_REQUEST == static_cast<int>(
+        CecMessageType::SYSTEM_AUDIO_MODE_REQUEST),
+        "CecMessageType::SYSTEM_AUDIO_MODE_REQUEST must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_AUDIO_STATUS == static_cast<int>(CecMessageType::GIVE_AUDIO_STATUS),
+        "CecMessageType::GIVE_AUDIO_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_SET_SYSTEM_AUDIO_MODE == static_cast<int>(
+        CecMessageType::SET_SYSTEM_AUDIO_MODE),
+        "CecMessageType::SET_SYSTEM_AUDIO_MODE must match legacy value.");
+static_assert(CEC_MESSAGE_REPORT_AUDIO_STATUS == static_cast<int>(
+        CecMessageType::REPORT_AUDIO_STATUS),
+        "CecMessageType::REPORT_AUDIO_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_SYSTEM_AUDIO_MODE_STATUS == static_cast<int>(
+        CecMessageType::GIVE_SYSTEM_AUDIO_MODE_STATUS),
+        "CecMessageType::GIVE_SYSTEM_AUDIO_MODE_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_SYSTEM_AUDIO_MODE_STATUS == static_cast<int>(
+        CecMessageType::SYSTEM_AUDIO_MODE_STATUS),
+        "CecMessageType::SYSTEM_AUDIO_MODE_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_ROUTING_CHANGE == static_cast<int>(CecMessageType::ROUTING_CHANGE),
+        "CecMessageType::ROUTING_CHANGE must match legacy value.");
+static_assert(CEC_MESSAGE_ROUTING_INFORMATION == static_cast<int>(
+        CecMessageType::ROUTING_INFORMATION),
+        "CecMessageType::ROUTING_INFORMATION must match legacy value.");
+static_assert(CEC_MESSAGE_ACTIVE_SOURCE == static_cast<int>(CecMessageType::ACTIVE_SOURCE),
+        "CecMessageType::ACTIVE_SOURCE must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_PHYSICAL_ADDRESS == static_cast<int>(
+        CecMessageType::GIVE_PHYSICAL_ADDRESS),
+        "CecMessageType::GIVE_PHYSICAL_ADDRESS must match legacy value.");
+static_assert(CEC_MESSAGE_REPORT_PHYSICAL_ADDRESS == static_cast<int>(
+        CecMessageType::REPORT_PHYSICAL_ADDRESS),
+        "CecMessageType::REPORT_PHYSICAL_ADDRESS must match legacy value.");
+static_assert(CEC_MESSAGE_REQUEST_ACTIVE_SOURCE == static_cast<int>(
+        CecMessageType::REQUEST_ACTIVE_SOURCE),
+        "CecMessageType::REQUEST_ACTIVE_SOURCE must match legacy value.");
+static_assert(CEC_MESSAGE_SET_STREAM_PATH == static_cast<int>(CecMessageType::SET_STREAM_PATH),
+        "CecMessageType::SET_STREAM_PATH must match legacy value.");
+static_assert(CEC_MESSAGE_DEVICE_VENDOR_ID == static_cast<int>(CecMessageType::DEVICE_VENDOR_ID),
+        "CecMessageType::DEVICE_VENDOR_ID must match legacy value.");
+static_assert(CEC_MESSAGE_VENDOR_COMMAND == static_cast<int>(CecMessageType::VENDOR_COMMAND),
+        "CecMessageType::VENDOR_COMMAND must match legacy value.");
+static_assert(CEC_MESSAGE_VENDOR_REMOTE_BUTTON_DOWN == static_cast<int>(
+        CecMessageType::VENDOR_REMOTE_BUTTON_DOWN),
+        "CecMessageType::VENDOR_REMOTE_BUTTON_DOWN must match legacy value.");
+static_assert(CEC_MESSAGE_VENDOR_REMOTE_BUTTON_UP == static_cast<int>(
+        CecMessageType::VENDOR_REMOTE_BUTTON_UP),
+        "CecMessageType::VENDOR_REMOTE_BUTTON_UP must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_DEVICE_VENDOR_ID == static_cast<int>(
+        CecMessageType::GIVE_DEVICE_VENDOR_ID),
+        "CecMessageType::GIVE_DEVICE_VENDOR_ID must match legacy value.");
+static_assert(CEC_MESSAGE_MENU_REQUEST == static_cast<int>(CecMessageType::MENU_REQUEST),
+        "CecMessageType::MENU_REQUEST must match legacy value.");
+static_assert(CEC_MESSAGE_MENU_STATUS == static_cast<int>(CecMessageType::MENU_STATUS),
+        "CecMessageType::MENU_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_GIVE_DEVICE_POWER_STATUS == static_cast<int>(
+        CecMessageType::GIVE_DEVICE_POWER_STATUS),
+        "CecMessageType::GIVE_DEVICE_POWER_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_REPORT_POWER_STATUS == static_cast<int>(
+        CecMessageType::REPORT_POWER_STATUS),
+        "CecMessageType::REPORT_POWER_STATUS must match legacy value.");
+static_assert(CEC_MESSAGE_GET_MENU_LANGUAGE == static_cast<int>(CecMessageType::GET_MENU_LANGUAGE),
+        "CecMessageType::GET_MENU_LANGUAGE must match legacy value.");
+static_assert(CEC_MESSAGE_SELECT_ANALOG_SERVICE == static_cast<int>(
+        CecMessageType::SELECT_ANALOG_SERVICE),
+        "CecMessageType::SELECT_ANALOG_SERVICE must match legacy value.");
+static_assert(CEC_MESSAGE_SELECT_DIGITAL_SERVICE == static_cast<int>(
+        CecMessageType::SELECT_DIGITAL_SERVICE),
+        "CecMessageType::SELECT_DIGITAL_SERVICE must match legacy value.");
+static_assert(CEC_MESSAGE_SET_DIGITAL_TIMER == static_cast<int>(CecMessageType::SET_DIGITAL_TIMER),
+        "CecMessageType::SET_DIGITAL_TIMER must match legacy value.");
+static_assert(CEC_MESSAGE_CLEAR_DIGITAL_TIMER == static_cast<int>(
+        CecMessageType::CLEAR_DIGITAL_TIMER),
+        "CecMessageType::CLEAR_DIGITAL_TIMER must match legacy value.");
+static_assert(CEC_MESSAGE_SET_AUDIO_RATE == static_cast<int>(CecMessageType::SET_AUDIO_RATE),
+        "CecMessageType::SET_AUDIO_RATE must match legacy value.");
+static_assert(CEC_MESSAGE_INACTIVE_SOURCE == static_cast<int>(CecMessageType::INACTIVE_SOURCE),
+        "CecMessageType::INACTIVE_SOURCE must match legacy value.");
+static_assert(CEC_MESSAGE_CEC_VERSION == static_cast<int>(CecMessageType::CEC_VERSION),
+        "CecMessageType::CEC_VERSION must match legacy value.");
+static_assert(CEC_MESSAGE_GET_CEC_VERSION == static_cast<int>(CecMessageType::GET_CEC_VERSION),
+        "CecMessageType::GET_CEC_VERSION must match legacy value.");
+static_assert(CEC_MESSAGE_VENDOR_COMMAND_WITH_ID == static_cast<int>(
+        CecMessageType::VENDOR_COMMAND_WITH_ID),
+        "CecMessageType::VENDOR_COMMAND_WITH_ID must match legacy value.");
+static_assert(CEC_MESSAGE_CLEAR_EXTERNAL_TIMER == static_cast<int>(
+        CecMessageType::CLEAR_EXTERNAL_TIMER),
+        "CecMessageType::CLEAR_EXTERNAL_TIMER must match legacy value.");
+static_assert(CEC_MESSAGE_SET_EXTERNAL_TIMER == static_cast<int>(
+        CecMessageType::SET_EXTERNAL_TIMER),
+        "CecMessageType::SET_EXTERNAL_TIMER must match legacy value.");
+static_assert(CEC_MESSAGE_INITIATE_ARC == static_cast<int>(CecMessageType::INITIATE_ARC),
+        "CecMessageType::INITIATE_ARC must match legacy value.");
+static_assert(CEC_MESSAGE_REPORT_ARC_INITIATED == static_cast<int>(
+        CecMessageType::REPORT_ARC_INITIATED),
+        "CecMessageType::REPORT_ARC_INITIATED must match legacy value.");
+static_assert(CEC_MESSAGE_REPORT_ARC_TERMINATED == static_cast<int>(
+        CecMessageType::REPORT_ARC_TERMINATED),
+        "CecMessageType::REPORT_ARC_TERMINATED must match legacy value.");
+static_assert(CEC_MESSAGE_REQUEST_ARC_INITIATION == static_cast<int>(
+        CecMessageType::REQUEST_ARC_INITIATION),
+        "CecMessageType::REQUEST_ARC_INITIATION must match legacy value.");
+static_assert(CEC_MESSAGE_REQUEST_ARC_TERMINATION == static_cast<int>(
+        CecMessageType::REQUEST_ARC_TERMINATION),
+        "CecMessageType::REQUEST_ARC_TERMINATION must match legacy value.");
+static_assert(CEC_MESSAGE_TERMINATE_ARC == static_cast<int>(CecMessageType::TERMINATE_ARC),
+        "CecMessageType::TERMINATE_ARC must match legacy value.");
+static_assert(CEC_MESSAGE_ABORT == static_cast<int>(CecMessageType::ABORT),
+        "CecMessageType::ABORT must match legacy value.");
+
+static_assert(ABORT_UNRECOGNIZED_MODE == static_cast<int>(AbortReason::UNRECOGNIZED_MODE),
+        "AbortReason::UNRECOGNIZED_MODE must match legacy value.");
+static_assert(ABORT_NOT_IN_CORRECT_MODE == static_cast<int>(AbortReason::NOT_IN_CORRECT_MODE),
+        "AbortReason::NOT_IN_CORRECT_MODE must match legacy value.");
+static_assert(ABORT_CANNOT_PROVIDE_SOURCE == static_cast<int>(AbortReason::CANNOT_PROVIDE_SOURCE),
+        "AbortReason::CANNOT_PROVIDE_SOURCE must match legacy value.");
+static_assert(ABORT_INVALID_OPERAND == static_cast<int>(AbortReason::INVALID_OPERAND),
+        "AbortReason::INVALID_OPERAND must match legacy value.");
+static_assert(ABORT_REFUSED == static_cast<int>(AbortReason::REFUSED),
+        "AbortReason::REFUSED must match legacy value.");
+static_assert(ABORT_UNABLE_TO_DETERMINE == static_cast<int>(AbortReason::UNABLE_TO_DETERMINE),
+        "AbortReason::UNABLE_TO_DETERMINE must match legacy value.");
+
+static_assert(HDMI_RESULT_SUCCESS == static_cast<int>(SendMessageResult::SUCCESS),
+        "SendMessageResult::SUCCESS must match legacy value.");
+static_assert(HDMI_RESULT_NACK == static_cast<int>(SendMessageResult::NACK),
+        "SendMessageResult::NACK must match legacy value.");
+static_assert(HDMI_RESULT_BUSY == static_cast<int>(SendMessageResult::BUSY),
+        "SendMessageResult::BUSY must match legacy value.");
+static_assert(HDMI_RESULT_FAIL == static_cast<int>(SendMessageResult::FAIL),
+        "SendMessageResult::FAIL must match legacy value.");
+
+static_assert(HDMI_INPUT == static_cast<int>(HdmiPortType::INPUT),
+        "HdmiPortType::INPUT must match legacy value.");
+static_assert(HDMI_OUTPUT == static_cast<int>(HdmiPortType::OUTPUT),
+        "HdmiPortType::OUTPUT must match legacy value.");
+
+static_assert(HDMI_OPTION_WAKEUP == static_cast<int>(OptionKey::WAKEUP),
+        "OptionKey::WAKEUP must match legacy value.");
+static_assert(HDMI_OPTION_ENABLE_CEC == static_cast<int>(OptionKey::ENABLE_CEC),
+        "OptionKey::ENABLE_CEC must match legacy value.");
+static_assert(HDMI_OPTION_SYSTEM_CEC_CONTROL == static_cast<int>(OptionKey::SYSTEM_CEC_CONTROL),
+        "OptionKey::SYSTEM_CEC_CONTROL must match legacy value.");
+
+sp<IHdmiCecCallback> HdmiCec::mCallback = nullptr;
+
+HdmiCec::HdmiCec(hdmi_cec_device_t* device) : mDevice(device) {
+}
+
+// Methods from ::android::hardware::tv::cec::V1_0::IHdmiCec follow.
+Return<Result> HdmiCec::addLogicalAddress(CecLogicalAddress addr) {
+    int ret = mDevice->add_logical_address(mDevice, static_cast<cec_logical_address_t>(addr));
+    switch (ret) {
+        case 0:
+            return Result::SUCCESS;
+        case -EINVAL:
+            return Result::FAILURE_INVALID_ARGS;
+        case -ENOTSUP:
+            return Result::FAILURE_NOT_SUPPORTED;
+        case -EBUSY:
+            return Result::FAILURE_BUSY;
+        default:
+            return Result::FAILURE_UNKNOWN;
+    }
+}
+
+Return<void> HdmiCec::clearLogicalAddress() {
+    mDevice->clear_logical_address(mDevice);
+    return Void();
+}
+
+Return<void> HdmiCec::getPhysicalAddress(getPhysicalAddress_cb _hidl_cb) {
+    uint16_t addr;
+    int ret = mDevice->get_physical_address(mDevice, &addr);
+    switch (ret) {
+        case 0:
+            _hidl_cb(Result::SUCCESS, addr);
+            break;
+        case -EBADF:
+            _hidl_cb(Result::FAILURE_INVALID_STATE, addr);
+            break;
+        default:
+            _hidl_cb(Result::FAILURE_UNKNOWN, addr);
+            break;
+    }
+    return Void();
+}
+
+Return<SendMessageResult> HdmiCec::sendMessage(const CecMessage& message) {
+    cec_message_t legacyMessage {
+        .initiator = static_cast<cec_logical_address_t>(message.initiator),
+        .destination = static_cast<cec_logical_address_t>(message.destination),
+        .length = message.body.size(),
+    };
+    for (size_t i = 0; i < message.body.size(); ++i) {
+        legacyMessage.body[i] = static_cast<unsigned char>(message.body[i]);
+    }
+    return static_cast<SendMessageResult>(mDevice->send_message(mDevice, &legacyMessage));
+}
+
+Return<void> HdmiCec::setCallback(const sp<IHdmiCecCallback>& callback) {
+    mCallback = callback;
+    mDevice->register_event_callback(mDevice, eventCallback, nullptr);
+    return Void();
+}
+
+Return<int32_t> HdmiCec::getCecVersion() {
+    int version;
+    mDevice->get_version(mDevice, &version);
+    return static_cast<int32_t>(version);
+}
+
+Return<uint32_t> HdmiCec::getVendorId() {
+    uint32_t vendor_id;
+    mDevice->get_vendor_id(mDevice, &vendor_id);
+    return vendor_id;
+}
+
+Return<void> HdmiCec::getPortInfo(getPortInfo_cb _hidl_cb) {
+    struct hdmi_port_info* legacyPorts;
+    int numPorts;
+    hidl_vec<HdmiPortInfo> portInfos;
+    mDevice->get_port_info(mDevice, &legacyPorts, &numPorts);
+    portInfos.resize(numPorts);
+    for (int i = 0; i < numPorts; ++i) {
+        portInfos[i] = {
+            .type = static_cast<HdmiPortType>(legacyPorts[i].type),
+            .portId = static_cast<uint32_t>(legacyPorts[i].port_id),
+            .cecSupported = legacyPorts[i].cec_supported != 0,
+            .arcSupported = legacyPorts[i].arc_supported != 0,
+            .physicalAddress = legacyPorts[i].physical_address
+        };
+    }
+    _hidl_cb(portInfos);
+    return Void();
+}
+
+Return<void> HdmiCec::setOption(OptionKey key, bool value) {
+    mDevice->set_option(mDevice, static_cast<int>(key), value ? 1 : 0);
+    return Void();
+}
+
+Return<void> HdmiCec::setLanguage(const hidl_string& language) {
+    if (language.size() != 3) {
+        LOG(ERROR) << "Wrong language code: expected 3 letters, but it was " << language.size()
+                << ".";
+        return Void();
+    }
+    const char *languageStr = language.c_str();
+    int convertedLanguage = ((languageStr[0] & 0xFF) << 16)
+            | ((languageStr[1] & 0xFF) << 8)
+            | (languageStr[2] & 0xFF);
+    mDevice->set_option(mDevice, HDMI_OPTION_SET_LANG, convertedLanguage);
+    return Void();
+}
+
+Return<void> HdmiCec::enableAudioReturnChannel(int32_t portId, bool enable) {
+    mDevice->set_audio_return_channel(mDevice, portId, enable ? 1 : 0);
+    return Void();
+}
+
+Return<bool> HdmiCec::isConnected(int32_t portId) {
+    return mDevice->is_connected(mDevice, portId) > 0;
+}
+
+
+IHdmiCec* HIDL_FETCH_IHdmiCec(const char* hal) {
+    hdmi_cec_device_t* hdmi_cec_device;
+    int ret = 0;
+    const hw_module_t* hw_module = nullptr;
+
+    ret = hw_get_module (HDMI_CEC_HARDWARE_MODULE_ID, &hw_module);
+    if (ret == 0) {
+        ret = hdmi_cec_open (hw_module, &hdmi_cec_device);
+        if (ret != 0) {
+            LOG(ERROR) << "hdmi_cec_open " << hal << " failed: " << ret;
+        }
+    } else {
+        LOG(ERROR) << "hw_get_module " << hal << " failed: " << ret;
+    }
+
+    if (ret == 0) {
+        return new HdmiCec(hdmi_cec_device);
+    } else {
+        LOG(ERROR) << "Passthrough failed to load legacy HAL.";
+        return nullptr;
+    }
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace cec
+}  // namespace tv
+}  // namespace hardware
+}  // namespace android
diff --git a/tv/cec/1.0/default/HdmiCec.h b/tv/cec/1.0/default/HdmiCec.h
new file mode 100644 (file)
index 0000000..a41a5f0
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+#ifndef HIDL_GENERATED_android_hardware_tv_cec_V1_0_HdmiCec_H_
+#define HIDL_GENERATED_android_hardware_tv_cec_V1_0_HdmiCec_H_
+
+#include <algorithm>
+
+#include <android/hardware/tv/cec/1.0/IHdmiCec.h>
+#include <hidl/Status.h>
+#include <hardware/hardware.h>
+#include <hardware/hdmi_cec.h>
+
+#include <hidl/MQDescriptor.h>
+namespace android {
+namespace hardware {
+namespace tv {
+namespace cec {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::tv::cec::V1_0::CecLogicalAddress;
+using ::android::hardware::tv::cec::V1_0::CecMessage;
+using ::android::hardware::tv::cec::V1_0::MaxLength;
+using ::android::hardware::tv::cec::V1_0::HdmiPortInfo;
+using ::android::hardware::tv::cec::V1_0::IHdmiCec;
+using ::android::hardware::tv::cec::V1_0::IHdmiCecCallback;
+using ::android::hardware::tv::cec::V1_0::OptionKey;
+using ::android::hardware::tv::cec::V1_0::Result;
+using ::android::hardware::tv::cec::V1_0::SendMessageResult;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct HdmiCec : public IHdmiCec {
+    HdmiCec(hdmi_cec_device_t* device);
+    // Methods from ::android::hardware::tv::cec::V1_0::IHdmiCec follow.
+    Return<Result> addLogicalAddress(CecLogicalAddress addr)  override;
+    Return<void> clearLogicalAddress()  override;
+    Return<void> getPhysicalAddress(getPhysicalAddress_cb _hidl_cb)  override;
+    Return<SendMessageResult> sendMessage(const CecMessage& message)  override;
+    Return<void> setCallback(const sp<IHdmiCecCallback>& callback)  override;
+    Return<int32_t> getCecVersion()  override;
+    Return<uint32_t> getVendorId()  override;
+    Return<void> getPortInfo(getPortInfo_cb _hidl_cb)  override;
+    Return<void> setOption(OptionKey key, bool value)  override;
+    Return<void> setLanguage(const hidl_string& language)  override;
+    Return<void> enableAudioReturnChannel(int32_t portId, bool enable)  override;
+    Return<bool> isConnected(int32_t portId)  override;
+
+    static void eventCallback(const hdmi_event_t* event, void* /* arg */) {
+        if (mCallback != nullptr && event != nullptr) {
+            if (event->type == HDMI_EVENT_CEC_MESSAGE) {
+                size_t length = std::min(event->cec.length,
+                        static_cast<size_t>(MaxLength::MESSAGE_BODY));
+                CecMessage cecMessage {
+                    .initiator = static_cast<CecLogicalAddress>(event->cec.initiator),
+                    .destination = static_cast<CecLogicalAddress>(event->cec.destination),
+                };
+                cecMessage.body.resize(length);
+                for (size_t i = 0; i < length; ++i) {
+                    cecMessage.body[i] = static_cast<uint8_t>(event->cec.body[i]);
+                }
+                mCallback->onCecMessage(cecMessage);
+            } else if (event->type == HDMI_EVENT_HOT_PLUG) {
+                HotplugEvent hotplugEvent {
+                    .connected = event->hotplug.connected > 0,
+                    .portId = static_cast<uint32_t>(event->hotplug.port_id)
+                };
+                mCallback->onHotplugEvent(hotplugEvent);
+            }
+        }
+    }
+
+private:
+    static sp<IHdmiCecCallback> mCallback;
+    const hdmi_cec_device_t* mDevice;
+};
+
+extern "C" IHdmiCec* HIDL_FETCH_IHdmiCec(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace cec
+}  // namespace tv
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_tv_cec_V1_0_HdmiCec_H_
diff --git a/tv/cec/1.0/default/android.hardware.tv.cec@1.0-service.rc b/tv/cec/1.0/default/android.hardware.tv.cec@1.0-service.rc
new file mode 100644 (file)
index 0000000..1af32cb
--- /dev/null
@@ -0,0 +1,4 @@
+service cec-hal-1-0 /system/bin/hw/android.hardware.tv.cec@1.0-service
+    class hal
+    user system
+    group system
diff --git a/tv/cec/1.0/default/service.cpp b/tv/cec/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..3c11e24
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.tv.cec@1.0-service"
+
+#include <android/hardware/tv/cec/1.0/IHdmiCec.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::tv::cec::V1_0::IHdmiCec;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IHdmiCec>("tv.cec");
+}
diff --git a/tv/cec/1.0/types.hal b/tv/cec/1.0/types.hal
new file mode 100644 (file)
index 0000000..ec2e373
--- /dev/null
@@ -0,0 +1,222 @@
+/*
+ * 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 android.hardware.tv.cec@1.0;
+
+enum MaxLength : int32_t {
+    MESSAGE_BODY = 15,
+};
+
+enum CecDeviceType : int32_t {
+    INACTIVE = -1,
+    TV = 0,
+    RECORDER = 1,
+    TUNER = 3,
+    PLAYBACK = 4,
+    AUDIO_SYSTEM = 5,
+    MAX = AUDIO_SYSTEM,
+};
+
+enum CecLogicalAddress : int32_t {
+    TV = 0,
+    RECORDER_1 = 1,
+    RECORDER_2 = 2,
+    TUNER_1 = 3,
+    PLAYBACK_1 = 4,
+    AUDIO_SYSTEM = 5,
+    TUNER_2 = 6,
+    TUNER_3 = 7,
+    PLAYBACK_2 = 8,
+    RECORDER_3 = 9,
+    TUNER_4 = 10,
+    PLAYBACK_3 = 11,
+    FREE_USE = 14,
+    UNREGISTERED = 15, // as Initiator address
+    BROADCAST = 15, // as Destination address
+};
+
+/*
+ * HDMI CEC message types. The assigned values represent opcode used in CEC
+ * frame as specified in CEC Table 8-26 of the CEC Spec 1.4b.
+ */
+enum CecMessageType : int32_t {
+    FEATURE_ABORT = 0x00,
+    IMAGE_VIEW_ON = 0x04,
+    TUNER_STEP_INCREMENT = 0x05,
+    TUNER_STEP_DECREMENT = 0x06,
+    TUNER_DEVICE_STATUS = 0x07,
+    GIVE_TUNER_DEVICE_STATUS = 0x08,
+    RECORD_ON = 0x09,
+    RECORD_STATUS = 0x0A,
+    RECORD_OFF = 0x0B,
+    TEXT_VIEW_ON = 0x0D,
+    RECORD_TV_SCREEN = 0x0F,
+    GIVE_DECK_STATUS = 0x1A,
+    DECK_STATUS = 0x1B,
+    SET_MENU_LANGUAGE = 0x32,
+    CLEAR_ANALOG_TIMER = 0x33,
+    SET_ANALOG_TIMER = 0x34,
+    TIMER_STATUS = 0x35,
+    STANDBY = 0x36,
+    PLAY = 0x41,
+    DECK_CONTROL = 0x42,
+    TIMER_CLEARED_STATUS = 0x43,
+    USER_CONTROL_PRESSED = 0x44,
+    USER_CONTROL_RELEASED = 0x45,
+    GIVE_OSD_NAME = 0x46,
+    SET_OSD_NAME = 0x47,
+    SET_OSD_STRING = 0x64,
+    SET_TIMER_PROGRAM_TITLE = 0x67,
+    SYSTEM_AUDIO_MODE_REQUEST = 0x70,
+    GIVE_AUDIO_STATUS = 0x71,
+    SET_SYSTEM_AUDIO_MODE = 0x72,
+    REPORT_AUDIO_STATUS = 0x7A,
+    GIVE_SYSTEM_AUDIO_MODE_STATUS = 0x7D,
+    SYSTEM_AUDIO_MODE_STATUS = 0x7E,
+    ROUTING_CHANGE = 0x80,
+    ROUTING_INFORMATION = 0x81,
+    ACTIVE_SOURCE = 0x82,
+    GIVE_PHYSICAL_ADDRESS = 0x83,
+    REPORT_PHYSICAL_ADDRESS = 0x84,
+    REQUEST_ACTIVE_SOURCE = 0x85,
+    SET_STREAM_PATH = 0x86,
+    DEVICE_VENDOR_ID = 0x87,
+    VENDOR_COMMAND = 0x89,
+    VENDOR_REMOTE_BUTTON_DOWN = 0x8A,
+    VENDOR_REMOTE_BUTTON_UP = 0x8B,
+    GIVE_DEVICE_VENDOR_ID = 0x8C,
+    MENU_REQUEST = 0x8D,
+    MENU_STATUS = 0x8E,
+    GIVE_DEVICE_POWER_STATUS = 0x8F,
+    REPORT_POWER_STATUS = 0x90,
+    GET_MENU_LANGUAGE = 0x91,
+    SELECT_ANALOG_SERVICE = 0x92,
+    SELECT_DIGITAL_SERVICE = 0x93,
+    SET_DIGITAL_TIMER = 0x97,
+    CLEAR_DIGITAL_TIMER = 0x99,
+    SET_AUDIO_RATE = 0x9A,
+    INACTIVE_SOURCE = 0x9D,
+    CEC_VERSION = 0x9E,
+    GET_CEC_VERSION = 0x9F,
+    VENDOR_COMMAND_WITH_ID = 0xA0,
+    CLEAR_EXTERNAL_TIMER = 0xA1,
+    SET_EXTERNAL_TIMER = 0xA2,
+    INITIATE_ARC = 0xC0,
+    REPORT_ARC_INITIATED = 0xC1,
+    REPORT_ARC_TERMINATED = 0xC2,
+    REQUEST_ARC_INITIATION = 0xC3,
+    REQUEST_ARC_TERMINATION = 0xC4,
+    TERMINATE_ARC = 0xC5,
+    ABORT = 0xFF,
+};
+
+/*
+ * Operand description [Abort Reason]
+ */
+enum AbortReason : int32_t {
+    UNRECOGNIZED_MODE = 0,
+    NOT_IN_CORRECT_MODE = 1,
+    CANNOT_PROVIDE_SOURCE = 2,
+    INVALID_OPERAND = 3,
+    REFUSED = 4,
+    UNABLE_TO_DETERMINE = 5,
+};
+
+enum Result : int32_t {
+    SUCCESS = 0,
+    FAILURE_UNKNOWN = 1,
+    FAILURE_INVALID_ARGS = 2,
+    FAILURE_INVALID_STATE = 3,
+    FAILURE_NOT_SUPPORTED = 4,
+    FAILURE_BUSY = 5,
+};
+
+/*
+ * error code used for send_message.
+ */
+enum SendMessageResult : int32_t {
+    SUCCESS = 0,
+    NACK = 1, // not acknowledged
+    BUSY = 2, // bus is busy
+    FAIL = 3,
+};
+
+/*
+ * HDMI port type.
+ */
+enum HdmiPortType : int32_t {
+    INPUT = 0,
+    OUTPUT = 1,
+};
+
+/*
+ * Options used for IHdmiCec.setOption()
+ */
+enum OptionKey : int32_t {
+    /* When set to false, HAL does not wake up the system upon receiving <Image
+     * View On> or <Text View On>. Used when user changes the TV settings to
+     * disable the auto TV on functionality.
+     * True by default.
+     */
+    WAKEUP = 1,
+
+    /* When set to false, all the CEC commands are discarded. Used when user
+     * changes the TV settings to disable CEC functionality.
+     * True by default.
+     */
+    ENABLE_CEC = 2,
+
+    /* Setting this flag to false means Android system must stop handling CEC
+     * service and yield the control over to the microprocessor that is powered
+     * on through the standby mode. When set to true, the system must gain the
+     * control over, hence telling the microprocessor to stop handling the CEC
+     * commands. For example, this may be called when system goes in and out of
+     * standby mode to notify the microprocessor that it should start/stop
+     * handling CEC commands on behalf of the system.
+     * False by default.
+     */
+    SYSTEM_CEC_CONTROL = 3,
+
+    /* Option 4 not used */
+};
+
+struct CecMessage {
+    /* logical address of sender */
+    CecLogicalAddress initiator;
+
+    /* logical address of receiver */
+    CecLogicalAddress destination;
+
+    /* The maximum size of body is 15 (MaxLength::MESSAGE_BODY) as specified in
+     * the section 6 of the CEC Spec 1.4b. Overflowed data must be ignored. */
+    vec<uint8_t> body;
+};
+
+struct HotplugEvent {
+    bool connected;
+    uint32_t portId;
+};
+
+/*
+ * HDMI port descriptor
+ */
+struct HdmiPortInfo {
+    HdmiPortType type;
+    uint32_t portId; // Should start from 1 which corresponds to HDMI "port 1".
+    bool cecSupported;
+    bool arcSupported;
+    uint16_t physicalAddress;
+};
diff --git a/tv/input/1.0/Android.bp b/tv/input/1.0/Android.bp
new file mode 100644 (file)
index 0000000..512634b
--- /dev/null
@@ -0,0 +1,61 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.tv.input@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.tv.input@1.0",
+    srcs: [
+        "types.hal",
+        "ITvInput.hal",
+        "ITvInputCallback.hal",
+    ],
+    out: [
+        "android/hardware/tv/input/1.0/types.cpp",
+        "android/hardware/tv/input/1.0/TvInputAll.cpp",
+        "android/hardware/tv/input/1.0/TvInputCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.tv.input@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.tv.input@1.0",
+    srcs: [
+        "types.hal",
+        "ITvInput.hal",
+        "ITvInputCallback.hal",
+    ],
+    out: [
+        "android/hardware/tv/input/1.0/types.h",
+        "android/hardware/tv/input/1.0/ITvInput.h",
+        "android/hardware/tv/input/1.0/IHwTvInput.h",
+        "android/hardware/tv/input/1.0/BnTvInput.h",
+        "android/hardware/tv/input/1.0/BpTvInput.h",
+        "android/hardware/tv/input/1.0/BsTvInput.h",
+        "android/hardware/tv/input/1.0/ITvInputCallback.h",
+        "android/hardware/tv/input/1.0/IHwTvInputCallback.h",
+        "android/hardware/tv/input/1.0/BnTvInputCallback.h",
+        "android/hardware/tv/input/1.0/BpTvInputCallback.h",
+        "android/hardware/tv/input/1.0/BsTvInputCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.tv.input@1.0",
+    generated_sources: ["android.hardware.tv.input@1.0_genc++"],
+    generated_headers: ["android.hardware.tv.input@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.tv.input@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.audio.common@2.0",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.audio.common@2.0",
+    ],
+}
diff --git a/tv/input/1.0/ITvInput.hal b/tv/input/1.0/ITvInput.hal
new file mode 100644 (file)
index 0000000..43de276
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * 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 android.hardware.tv.input@1.0;
+
+import ITvInputCallback;
+
+interface ITvInput {
+    /*
+     * Sets a callback for events.
+     *
+     * Note that initially no device is available in the client side, so the
+     * implementation must notify all the currently available devices including
+     * static devices via callback once callback is set.
+     *
+     * @param callback Callback object to pass events.
+     */
+    @entry
+    @exit
+    @callflow(next={"getStreamConfigurations"})
+    setCallback(ITvInputCallback callback);
+
+    /*
+     * Gets stream configurations for a specific device.
+     *
+     * The configs object is valid only until the next
+     * STREAM_CONFIGURATIONS_CHANGED event.
+     *
+     * @param deviceId Device ID for the configurations.
+     * @return result OK upon success. Otherwise,
+     *         INVALID_ARGUMENTS if the given device ID is not valid.
+     * @return configurations An array of available configurations.
+     */
+    @callflow(next={"openStream", "getStreamConfigurations", "closeStream"})
+    getStreamConfigurations(int32_t deviceId)
+            generates (Result result, vec<TvStreamConfig> configurations);
+
+    /*
+     * Opens a specific stream in a device.
+     *
+     * @param deviceId Device ID for the steam to open.
+     * @param streamId Steam ID for the steam to open. Must be one of the
+     *         stream IDs returned from getStreamConfigurations().
+     * @return result OK upon success. Otherwise,
+     *         INVALID_ARGUMENTS if any of given IDs are not valid;
+     *         INVALID_STATE if the stream with the given ID is already open;
+     *         NO_RESOURCE if the client must close other streams to open the
+     *                 stream.
+     * @return sidebandStream handle for sideband stream.
+     */
+    @callflow(next={"closeStream", "getStreamConfigurations", "openStream"})
+    openStream(int32_t deviceId, int32_t streamId)
+            generates (Result result, handle sidebandStream);
+
+    /*
+     * Closes a specific stream in a device.
+     *
+     * @param deviceId Device ID for the steam to open.
+     * @param streamId Steam ID for the steam to open.
+     * @return result OK upon success. Otherwise,
+     *         INVALID_ARGUMENTS if any of given IDs are not valid;
+     *         INVALID_STATE if the stream with the given ID is not open.
+     */
+    @callflow(next={"getStreamConfigurations", "openStream", "closeStream"})
+    closeStream(int32_t deviceId, int32_t streamId) generates (Result result);
+};
diff --git a/tv/input/1.0/ITvInputCallback.hal b/tv/input/1.0/ITvInputCallback.hal
new file mode 100644 (file)
index 0000000..f2f07a0
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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 android.hardware.tv.input@1.0;
+
+interface ITvInputCallback {
+    /*
+     * Notifies the client that an event has occured. For possible event types,
+     * check TvInputEventType.
+     *
+     * @param event Event passed to the client.
+     */
+    notify(TvInputEvent event);
+};
diff --git a/tv/input/1.0/default/Android.mk b/tv/input/1.0/default/Android.mk
new file mode 100644 (file)
index 0000000..520b0bf
--- /dev/null
@@ -0,0 +1,44 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.tv.input@1.0-impl
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+    TvInput.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    libbase \
+    liblog \
+    libhardware \
+    libhidl \
+    libhwbinder \
+    libutils \
+    android.hardware.audio.common@2.0 \
+    android.hardware.tv.input@1.0 \
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_MODULE := android.hardware.tv.input@1.0-service
+LOCAL_INIT_RC := android.hardware.tv.input@1.0-service.rc
+LOCAL_SRC_FILES := \
+    service.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libcutils \
+    libdl \
+    libbase \
+    libutils \
+    libhardware_legacy \
+    libhardware \
+
+LOCAL_SHARED_LIBRARIES += \
+    libhwbinder \
+    libhidl \
+    android.hardware.audio.common@2.0 \
+    android.hardware.tv.input@1.0 \
+
+include $(BUILD_EXECUTABLE)
+
diff --git a/tv/input/1.0/default/TvInput.cpp b/tv/input/1.0/default/TvInput.cpp
new file mode 100644 (file)
index 0000000..6181ffb
--- /dev/null
@@ -0,0 +1,226 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.tv.input@1.0-service"
+#include <android-base/logging.h>
+
+#include "TvInput.h"
+
+const native_handle_t kNullNativeHandle{sizeof(native_handle_t), 0, 0, {}};
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace input {
+namespace V1_0 {
+namespace implementation {
+
+static_assert(TV_INPUT_TYPE_OTHER_HARDWARE == static_cast<int>(TvInputType::OTHER),
+        "TvInputType::OTHER must match legacy value.");
+static_assert(TV_INPUT_TYPE_TUNER == static_cast<int>(TvInputType::TUNER),
+        "TvInputType::TUNER must match legacy value.");
+static_assert(TV_INPUT_TYPE_COMPOSITE == static_cast<int>(TvInputType::COMPOSITE),
+        "TvInputType::COMPOSITE must match legacy value.");
+static_assert(TV_INPUT_TYPE_SVIDEO == static_cast<int>(TvInputType::SVIDEO),
+        "TvInputType::SVIDEO must match legacy value.");
+static_assert(TV_INPUT_TYPE_SCART == static_cast<int>(TvInputType::SCART),
+        "TvInputType::SCART must match legacy value.");
+static_assert(TV_INPUT_TYPE_COMPONENT == static_cast<int>(TvInputType::COMPONENT),
+        "TvInputType::COMPONENT must match legacy value.");
+static_assert(TV_INPUT_TYPE_VGA == static_cast<int>(TvInputType::VGA),
+        "TvInputType::VGA must match legacy value.");
+static_assert(TV_INPUT_TYPE_DVI == static_cast<int>(TvInputType::DVI),
+        "TvInputType::DVI must match legacy value.");
+static_assert(TV_INPUT_TYPE_HDMI == static_cast<int>(TvInputType::HDMI),
+        "TvInputType::HDMI must match legacy value.");
+static_assert(TV_INPUT_TYPE_DISPLAY_PORT == static_cast<int>(TvInputType::DISPLAY_PORT),
+        "TvInputType::DISPLAY_PORT must match legacy value.");
+
+static_assert(TV_INPUT_EVENT_DEVICE_AVAILABLE == static_cast<int>(
+        TvInputEventType::DEVICE_AVAILABLE),
+        "TvInputEventType::DEVICE_AVAILABLE must match legacy value.");
+static_assert(TV_INPUT_EVENT_DEVICE_UNAVAILABLE == static_cast<int>(
+        TvInputEventType::DEVICE_UNAVAILABLE),
+        "TvInputEventType::DEVICE_UNAVAILABLE must match legacy value.");
+static_assert(TV_INPUT_EVENT_STREAM_CONFIGURATIONS_CHANGED == static_cast<int>(
+        TvInputEventType::STREAM_CONFIGURATIONS_CHANGED),
+        "TvInputEventType::STREAM_CONFIGURATIONS_CHANGED must match legacy value.");
+
+sp<ITvInputCallback> TvInput::mCallback = nullptr;
+
+TvInput::TvInput(tv_input_device_t* device) : mDevice(device) {
+    mCallbackOps.notify = &TvInput::notify;
+}
+
+TvInput::~TvInput() {
+    if (mDevice != nullptr) {
+        free(mDevice);
+    }
+}
+
+// Methods from ::android::hardware::tv_input::V1_0::ITvInput follow.
+Return<void> TvInput::setCallback(const sp<ITvInputCallback>& callback)  {
+    mCallback = callback;
+    if (mCallback != nullptr) {
+        mDevice->initialize(mDevice, &mCallbackOps, nullptr);
+    }
+    return Void();
+}
+
+Return<void> TvInput::getStreamConfigurations(int32_t deviceId, getStreamConfigurations_cb cb)  {
+    int32_t configCount = 0;
+    const tv_stream_config_t* configs = nullptr;
+    int ret = mDevice->get_stream_configurations(mDevice, deviceId, &configCount, &configs);
+    Result res = Result::UNKNOWN;
+    hidl_vec<TvStreamConfig> tvStreamConfigs;
+    if (ret == 0) {
+        res = Result::OK;
+        tvStreamConfigs.resize(getSupportedConfigCount(configCount, configs));
+        int32_t pos = 0;
+        for (int32_t i = 0; i < configCount; ++i) {
+            if (isSupportedStreamType(configs[i].type)) {
+                tvStreamConfigs[pos].streamId = configs[i].stream_id;
+                tvStreamConfigs[pos].maxVideoWidth = configs[i].max_video_width;
+                tvStreamConfigs[pos].maxVideoHeight = configs[i].max_video_height;
+                ++pos;
+            }
+        }
+    }
+    cb(res, tvStreamConfigs);
+    return Void();
+}
+
+Return<void> TvInput::openStream(int32_t deviceId, int32_t streamId, openStream_cb cb)  {
+    tv_stream_t stream;
+    stream.stream_id = streamId;
+    int ret = mDevice->open_stream(mDevice, deviceId, &stream);
+    Result res = Result::UNKNOWN;
+    native_handle_t* sidebandStream = nullptr;
+    if (ret == 0) {
+        if (isSupportedStreamType(stream.type)) {
+            res = Result::OK;
+            sidebandStream = stream.sideband_stream_source_handle;
+        }
+    } else {
+        // TODO(b/30814137)
+        sidebandStream = const_cast<native_handle_t*>(&kNullNativeHandle);
+        if (ret == -EBUSY) {
+            res = Result::NO_RESOURCE;
+        } else if (ret == -EEXIST) {
+            res = Result::INVALID_STATE;
+        } else if (ret == -EINVAL) {
+            res = Result::INVALID_ARGUMENTS;
+        }
+    }
+    cb(res, sidebandStream);
+    return Void();
+}
+
+Return<Result> TvInput::closeStream(int32_t deviceId, int32_t streamId)  {
+    int ret = mDevice->close_stream(mDevice, deviceId, streamId);
+    Result res = Result::UNKNOWN;
+    if (ret == 0) {
+        res = Result::OK;
+    } else if (ret == -ENOENT) {
+        res = Result::INVALID_STATE;
+    } else if (ret == -EINVAL) {
+        res = Result::INVALID_ARGUMENTS;
+    }
+    return res;
+}
+
+// static
+void TvInput::notify(struct tv_input_device* __unused, tv_input_event_t* event,
+        void* __unused) {
+    if (mCallback != nullptr && event != nullptr) {
+        // Capturing is no longer supported.
+        if (event->type >= TV_INPUT_EVENT_CAPTURE_SUCCEEDED) {
+            return;
+        }
+        TvInputEvent tvInputEvent;
+        tvInputEvent.type = static_cast<TvInputEventType>(event->type);
+        tvInputEvent.deviceInfo.deviceId = event->device_info.device_id;
+        tvInputEvent.deviceInfo.type = static_cast<TvInputType>(
+                event->device_info.type);
+        tvInputEvent.deviceInfo.portId = event->device_info.hdmi.port_id;
+        // TODO: Ensure the legacy audio type code is the same once audio HAL default
+        // implementation is ready.
+        tvInputEvent.deviceInfo.audioType = static_cast<AudioDevice>(
+                event->device_info.audio_type);
+        memset(tvInputEvent.deviceInfo.audioAddress.data(), 0,
+                tvInputEvent.deviceInfo.audioAddress.size());
+        const char* address = event->device_info.audio_address;
+        if (address != nullptr) {
+            size_t size = strlen(address);
+            if (size > tvInputEvent.deviceInfo.audioAddress.size()) {
+                LOG(ERROR) << "Audio address is too long. Address:" << address << "";
+                return;
+            }
+            for (size_t i = 0; i < size; ++i) {
+                tvInputEvent.deviceInfo.audioAddress[i] =
+                    static_cast<uint8_t>(event->device_info.audio_address[i]);
+            }
+        }
+        mCallback->notify(tvInputEvent);
+    }
+}
+
+// static
+uint32_t TvInput::getSupportedConfigCount(uint32_t configCount,
+        const tv_stream_config_t* configs) {
+    uint32_t supportedConfigCount = 0;
+    for (uint32_t i = 0; i < configCount; ++i) {
+        if (isSupportedStreamType(configs[i].type)) {
+            supportedConfigCount++;
+        }
+    }
+    return supportedConfigCount;
+}
+
+// static
+bool TvInput::isSupportedStreamType(int type) {
+    // Buffer producer type is no longer supported.
+    return type != TV_STREAM_TYPE_BUFFER_PRODUCER;
+}
+
+ITvInput* HIDL_FETCH_ITvInput(const char* name) {
+    int ret = 0;
+    const hw_module_t* hw_module = nullptr;
+    tv_input_device_t* input_device;
+    ret = hw_get_module(TV_INPUT_HARDWARE_MODULE_ID, &hw_module);
+    if (ret == 0 && hw_module->methods->open != nullptr) {
+        ret = hw_module->methods->open(hw_module, TV_INPUT_DEFAULT_DEVICE,
+                reinterpret_cast<hw_device_t**>(&input_device));
+        if (ret == 0) {
+            return new TvInput(input_device);
+        }
+        else {
+            LOG(ERROR) << "Passthrough failed to load legacy HAL.";
+            return nullptr;
+        }
+    }
+    else {
+        LOG(ERROR) << "hw_get_module " << name << " failed: " << ret;
+        return nullptr;
+    }
+}
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace input
+}  // namespace tv
+}  // namespace hardware
+}  // namespace android
diff --git a/tv/input/1.0/default/TvInput.h b/tv/input/1.0/default/TvInput.h
new file mode 100644 (file)
index 0000000..81cbb20
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ */
+#ifndef HIDL_GENERATED_android_hardware_tv_input_V1_0_TvInput_H_
+#define HIDL_GENERATED_android_hardware_tv_input_V1_0_TvInput_H_
+
+#include <android/hardware/tv/input/1.0/ITvInput.h>
+#include <hidl/Status.h>
+#include <hardware/tv_input.h>
+
+#include <hidl/MQDescriptor.h>
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace input {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::audio::common::V2_0::AudioDevice;
+using ::android::hardware::tv::input::V1_0::ITvInput;
+using ::android::hardware::tv::input::V1_0::ITvInputCallback;
+using ::android::hardware::tv::input::V1_0::Result;
+using ::android::hardware::tv::input::V1_0::TvInputEvent;
+using ::android::hardware::tv::input::V1_0::TvStreamConfig;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct TvInput : public ITvInput {
+    TvInput(tv_input_device_t* device);
+    ~TvInput();
+    Return<void> setCallback(const sp<ITvInputCallback>& callback)  override;
+    Return<void> getStreamConfigurations(int32_t deviceId,
+            getStreamConfigurations_cb _hidl_cb)  override;
+    Return<void> openStream(int32_t deviceId, int32_t streamId,
+            openStream_cb _hidl_cb)  override;
+    Return<Result> closeStream(int32_t deviceId, int32_t streamId)  override;
+
+    static void notify(struct tv_input_device* __unused, tv_input_event_t* event,
+            void* __unused);
+    static uint32_t getSupportedConfigCount(uint32_t configCount,
+            const tv_stream_config_t* configs);
+    static bool isSupportedStreamType(int type);
+
+    private:
+    static sp<ITvInputCallback> mCallback;
+    tv_input_callback_ops_t mCallbackOps;
+    tv_input_device_t* mDevice;
+};
+
+extern "C" ITvInput* HIDL_FETCH_ITvInput(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace input
+}  // namespace tv
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_tv_input_V1_0_TvInput_H_
diff --git a/tv/input/1.0/default/android.hardware.tv.input@1.0-service.rc b/tv/input/1.0/default/android.hardware.tv.input@1.0-service.rc
new file mode 100644 (file)
index 0000000..c5bc0b7
--- /dev/null
@@ -0,0 +1,4 @@
+service tv-input-1-0 /system/bin/hw/android.hardware.tv.input@1.0-service
+    class hal
+    user system
+    group system readproc
diff --git a/tv/input/1.0/default/service.cpp b/tv/input/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..d59c848
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.tv_input@1.0-service"
+
+#include <android/hardware/tv/input/1.0/ITvInput.h>
+
+#include <hidl/LegacySupport.h>
+
+using android::sp;
+
+// Generated HIDL files
+using android::hardware::tv::input::V1_0::ITvInput;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<ITvInput>("tv.input");
+}
diff --git a/tv/input/1.0/types.hal b/tv/input/1.0/types.hal
new file mode 100644 (file)
index 0000000..89a7acc
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * 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 android.hardware.tv.input@1.0;
+
+import android.hardware.audio.common@2.0;
+
+enum Result {
+    OK,
+    UNKNOWN,
+    NO_RESOURCE,
+    INVALID_ARGUMENTS,
+    INVALID_STATE,
+};
+
+/* Type of physical TV input. */
+enum TvInputType {
+    OTHER = 1,         // Generic hardware.
+    TUNER = 2,         // Tuner. e.g. built-in terrestrial tuner
+    COMPOSITE = 3,
+    SVIDEO = 4,
+    SCART = 5,
+    COMPONENT = 6,
+    VGA = 7,
+    DVI = 8,
+    HDMI = 9,          // Physical HDMI port. e.g. HDMI 1
+    DISPLAY_PORT = 10,
+};
+
+struct TvInputDeviceInfo {
+    int32_t deviceId;
+    TvInputType type;
+    uint32_t portId;          // HDMI port ID number. e.g. 2 for HDMI 2
+    AudioDevice audioType;    // Audio device type. e.g AudioDevice::IN_HDMI
+    uint8_t[32] audioAddress; // Audio device address. "" if N/A. If the text
+                              // length is less than 32, the remaining part
+                              // must be filled with 0s.
+};
+
+enum TvInputEventType {
+    /*
+     * Hardware notifies the framework that a device is available.
+     *
+     * Note that DEVICE_AVAILABLE and DEVICE_UNAVAILABLE events do not represent
+     * hotplug events (i.e. plugging cable into or out of the physical port).
+     * These events notify the framework whether the port is available or not.
+     * For a concrete example, when a user plugs in or pulls out the HDMI cable
+     * from a HDMI port, it does not generate DEVICE_AVAILABLE and/or
+     * DEVICE_UNAVAILABLE events. However, if a user inserts a pluggable USB
+     * tuner into the Android device, it must generate a DEVICE_AVAILABLE event
+     * and when the port is removed, it must generate a DEVICE_UNAVAILABLE
+     * event.
+     *
+     * For hotplug events, please see STREAM_CONFIGURATION_CHANGED for more
+     * details.
+     *
+     * HAL implementation must register devices by using this event when the
+     * device boots up. The framework must recognize device reported via this
+     * event only.
+     */
+    DEVICE_AVAILABLE = 1,
+
+    /*
+     * Hardware notifies the framework that a device is unavailable.
+     *
+     * HAL implementation must generate this event when a device registered
+     * by DEVICE_AVAILABLE is no longer available. For example,
+     * the event can indicate that a USB tuner is plugged out from the Android
+     * device.
+     *
+     * Note that this event is not for indicating cable plugged out of the port;
+     * for that purpose, the implementation must use
+     * STREAM_CONFIGURATION_CHANGED event. This event represents the port itself
+     * being no longer available.
+     */
+    DEVICE_UNAVAILABLE = 2,
+
+    /*
+     * Stream configurations are changed. Client must regard all open streams
+     * at the specific device are closed, and must call
+     * getStreamConfigurations() again, opening some of them if necessary.
+     *
+     * HAL implementation must generate this event when the available stream
+     * configurations change for any reason. A typical use case of this event
+     * is to notify the framework that the input signal has changed resolution,
+     * or that the cable is plugged out so that the number of available streams
+     * is 0.
+     *
+     * The implementation must use this event to indicate hotplug status of the
+     * port. the framework regards input devices with no available streams as
+     * disconnected, so the implementation can generate this event with no
+     * available streams to indicate that this device is disconnected, and vice
+     * versa.
+     */
+    STREAM_CONFIGURATIONS_CHANGED = 3,
+};
+
+struct TvInputEvent {
+    TvInputEventType type;
+    /*
+     * DEVICE_AVAILABLE: all fields are relevant.
+     * DEVICE_UNAVAILABLE: only deviceId is relevant.
+     * STREAM_CONFIGURATIONS_CHANGED: only deviceId is relevant.
+     */
+    TvInputDeviceInfo deviceInfo;
+};
+
+struct TvStreamConfig {
+    int32_t streamId;
+    uint32_t maxVideoWidth;  // Max width of the stream.
+    uint32_t maxVideoHeight; // Max height of the stream.
+};
diff --git a/vehicle/2.0/Android.bp b/vehicle/2.0/Android.bp
new file mode 100644 (file)
index 0000000..d51fe25
--- /dev/null
@@ -0,0 +1,59 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.vehicle@2.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.vehicle@2.0",
+    srcs: [
+        "types.hal",
+        "IVehicle.hal",
+        "IVehicleCallback.hal",
+    ],
+    out: [
+        "android/hardware/vehicle/2.0/types.cpp",
+        "android/hardware/vehicle/2.0/VehicleAll.cpp",
+        "android/hardware/vehicle/2.0/VehicleCallbackAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.vehicle@2.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.vehicle@2.0",
+    srcs: [
+        "types.hal",
+        "IVehicle.hal",
+        "IVehicleCallback.hal",
+    ],
+    out: [
+        "android/hardware/vehicle/2.0/types.h",
+        "android/hardware/vehicle/2.0/IVehicle.h",
+        "android/hardware/vehicle/2.0/IHwVehicle.h",
+        "android/hardware/vehicle/2.0/BnVehicle.h",
+        "android/hardware/vehicle/2.0/BpVehicle.h",
+        "android/hardware/vehicle/2.0/BsVehicle.h",
+        "android/hardware/vehicle/2.0/IVehicleCallback.h",
+        "android/hardware/vehicle/2.0/IHwVehicleCallback.h",
+        "android/hardware/vehicle/2.0/BnVehicleCallback.h",
+        "android/hardware/vehicle/2.0/BpVehicleCallback.h",
+        "android/hardware/vehicle/2.0/BsVehicleCallback.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.vehicle@2.0",
+    generated_sources: ["android.hardware.vehicle@2.0_genc++"],
+    generated_headers: ["android.hardware.vehicle@2.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.vehicle@2.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/vehicle/2.0/Android.mk b/vehicle/2.0/Android.mk
new file mode 100644 (file)
index 0000000..be63595
--- /dev/null
@@ -0,0 +1,1708 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.vehicle@2.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (StatusCode)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/StatusCode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.StatusCode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SubscribeFlags)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/SubscribeFlags.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.SubscribeFlags
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SubscribeOptions)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/SubscribeOptions.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.SubscribeOptions
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerBootupReason)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerBootupReason.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerBootupReason
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerSetState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerSetState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerSetState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerStateConfigFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerStateConfigFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerStateConfigFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerStateIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerStateIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerStateIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerStateShutdownParam)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerStateShutdownParam.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerStateShutdownParam
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleArea)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleArea.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleArea
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaConfig)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaConfig.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaConfig
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaDoor)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaDoor.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaDoor
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaMirror)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaMirror.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaMirror
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaSeat)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaSeat.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaSeat
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaWindow)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaWindow.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaWindow
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaZone)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaZone.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaZone
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioContextFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioContextFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioContextFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioExtFocusFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioExtFocusFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioExtFocusFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioFocusIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioFocusIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioFocusIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioFocusRequest)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioFocusRequest.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioFocusRequest
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioFocusState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioFocusState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioFocusState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioHwVariantConfigFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioHwVariantConfigFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioHwVariantConfigFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioRoutingPolicyIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioRoutingPolicyIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioRoutingPolicyIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioStream)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioStream.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioStream
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioStreamFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioStreamFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioStreamFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeCapabilityFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeCapabilityFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeCapabilityFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeLimitIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeLimitIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeLimitIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleDisplay)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleDisplay.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleDisplay
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleDrivingStatus)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleDrivingStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleDrivingStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleGear)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleGear.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleGear
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleHvacFanDirection)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleHvacFanDirection.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleHvacFanDirection
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleHwKeyInputAction)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleHwKeyInputAction.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleHwKeyInputAction
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleInstrumentClusterType)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleInstrumentClusterType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleInstrumentClusterType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePermissionModel)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePermissionModel.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePermissionModel
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropConfig)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropConfig.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropConfig
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropValue)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropValue.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropValue
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleProperty)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleProperty.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleProperty
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyAccess)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyAccess.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyAccess
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyChangeMode)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyChangeMode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyChangeMode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyGroup)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyGroup.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyGroup
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyOperation)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyOperation.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyOperation
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyType)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleRadioConstants)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleRadioConstants.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleRadioConstants
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleTurnSignal)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleTurnSignal.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleTurnSignal
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleUnit)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleUnit.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleUnit
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IVehicle.hal
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/IVehicle.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVehicle.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/IVehicleCallback.hal
+$(GEN): $(LOCAL_PATH)/IVehicleCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::IVehicle
+
+$(GEN): $(LOCAL_PATH)/IVehicle.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IVehicleCallback.hal
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/IVehicleCallback.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVehicleCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::IVehicleCallback
+
+$(GEN): $(LOCAL_PATH)/IVehicleCallback.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.vehicle@2.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (StatusCode)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/StatusCode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.StatusCode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SubscribeFlags)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/SubscribeFlags.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.SubscribeFlags
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (SubscribeOptions)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/SubscribeOptions.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.SubscribeOptions
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerBootupReason)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerBootupReason.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerBootupReason
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerSetState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerSetState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerSetState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerStateConfigFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerStateConfigFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerStateConfigFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerStateIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerStateIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerStateIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleApPowerStateShutdownParam)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleApPowerStateShutdownParam.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleApPowerStateShutdownParam
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleArea)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleArea.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleArea
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaConfig)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaConfig.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaConfig
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaDoor)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaDoor.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaDoor
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaMirror)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaMirror.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaMirror
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaSeat)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaSeat.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaSeat
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaWindow)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaWindow.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaWindow
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAreaZone)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAreaZone.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAreaZone
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioContextFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioContextFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioContextFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioExtFocusFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioExtFocusFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioExtFocusFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioFocusIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioFocusIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioFocusIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioFocusRequest)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioFocusRequest.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioFocusRequest
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioFocusState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioFocusState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioFocusState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioHwVariantConfigFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioHwVariantConfigFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioHwVariantConfigFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioRoutingPolicyIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioRoutingPolicyIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioRoutingPolicyIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioStream)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioStream.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioStream
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioStreamFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioStreamFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioStreamFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeCapabilityFlag)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeCapabilityFlag.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeCapabilityFlag
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeLimitIndex)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeLimitIndex.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeLimitIndex
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleAudioVolumeState)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleAudioVolumeState.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleAudioVolumeState
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleDisplay)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleDisplay.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleDisplay
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleDrivingStatus)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleDrivingStatus.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleDrivingStatus
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleGear)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleGear.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleGear
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleHvacFanDirection)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleHvacFanDirection.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleHvacFanDirection
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleHwKeyInputAction)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleHwKeyInputAction.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleHwKeyInputAction
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleInstrumentClusterType)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleInstrumentClusterType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleInstrumentClusterType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePermissionModel)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePermissionModel.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePermissionModel
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropConfig)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropConfig.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropConfig
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropValue)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropValue.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropValue
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleProperty)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleProperty.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleProperty
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyAccess)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyAccess.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyAccess
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyChangeMode)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyChangeMode.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyChangeMode
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyGroup)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyGroup.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyGroup
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyOperation)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyOperation.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyOperation
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehiclePropertyType)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehiclePropertyType.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehiclePropertyType
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleRadioConstants)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleRadioConstants.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleRadioConstants
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleTurnSignal)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleTurnSignal.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleTurnSignal
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build types.hal (VehicleUnit)
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/VehicleUnit.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::types.VehicleUnit
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IVehicle.hal
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/IVehicle.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVehicle.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/IVehicleCallback.hal
+$(GEN): $(LOCAL_PATH)/IVehicleCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::IVehicle
+
+$(GEN): $(LOCAL_PATH)/IVehicle.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IVehicleCallback.hal
+#
+GEN := $(intermediates)/android/hardware/vehicle/2.0/IVehicleCallback.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVehicleCallback.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vehicle@2.0::IVehicleCallback
+
+$(GEN): $(LOCAL_PATH)/IVehicleCallback.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/vehicle/2.0/IVehicle.hal b/vehicle/2.0/IVehicle.hal
new file mode 100644 (file)
index 0000000..5b0df67
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * 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 android.hardware.vehicle@2.0;
+
+import IVehicleCallback;
+
+interface IVehicle {
+  /**
+   * Returns a list of all property configurations supported by this vehicle
+   * HAL.
+   */
+  getAllPropConfigs() generates (vec<VehiclePropConfig> propConfigs);
+
+  /*
+   * Returns a list of property configurations for given properties.
+   *
+   * If requested VehicleProperty wasn't found it must return
+   * StatusCode::INVALID_ARG, otherwise a list of vehicle property
+   * configurations with StatusCode::OK
+   */
+  getPropConfigs(vec<VehicleProperty> props)
+          generates (StatusCode status, vec<VehiclePropConfig> propConfigs);
+
+  /**
+   * Get a vehicle property value.
+   *
+   * For VehiclePropertyChangeMode::STATIC properties, this method must always
+   * return the same value always.
+   * For VehiclePropertyChangeMode::ON_CHANGE properties, it must return the
+   * latest available value.
+   *
+   * Some properties like AUDIO_VOLUME requires to pass additional data in
+   * GET request in VehiclePropValue object.
+   *
+   * If there is no data available yet, which can happen during initial stage,
+   * this call must return immediately with an error code of
+   * StatusCode::TRY_AGAIN.
+   */
+  get(VehiclePropValue requestedPropValue)
+          generates (StatusCode status, VehiclePropValue propValue);
+
+  /**
+   * Set a vehicle property value.
+   *
+   * Timestamp of data must be ignored for set operation.
+   *
+   * Setting some properties require having initial state available. If initial
+   * data is not available yet this call must return StatusCode::TRY_AGAIN.
+   * For a property with separate power control this call must return
+   * StatusCode::NOT_AVAILABLE error if property is not powered on.
+   */
+  set(VehiclePropValue propValue) generates (StatusCode status);
+
+  /**
+   * Subscribes to property events.
+   *
+   * Clients must be able to subscribe to multiple properties at a time
+   * depending on data provided in options argument.
+   *
+   * @param listener This client must be called on appropriate event.
+   * @param options List of options to subscribe. SubscribeOption contains
+   *                information such as property Id, area Id, sample rate, etc.
+   */
+  subscribe(IVehicleCallback callback, vec<SubscribeOptions> options)
+          generates (StatusCode status);
+
+  /**
+   * Unsubscribes from property events.
+   *
+   * If this client wasn't subscribed to the given property, this method
+   * must return StatusCode::INVALID_ARG.
+   */
+  unsubscribe(IVehicleCallback callback, VehicleProperty propId)
+          generates (StatusCode status);
+
+  /**
+   * Print out debugging state for the vehicle hal.
+   *
+   * The text must be in ASCII encoding only.
+   *
+   * Performance requirements:
+   *
+   * The HAL must return from this call in less than 10ms. This call must avoid
+   * deadlocks, as it may be called at any point of operation. Any synchronization
+   * primitives used (such as mutex locks or semaphores) must be acquired
+   * with a timeout.
+   *
+   * TODO(pavelm): we cannot use handle here due to Java compatibility, it's
+   * better to pass file descriptor and write debug data directly in vehicle HAL
+   * rather than passing back a string.
+   */
+  debugDump() generates (string s);
+};
diff --git a/vehicle/2.0/IVehicleCallback.hal b/vehicle/2.0/IVehicleCallback.hal
new file mode 100644 (file)
index 0000000..e7e05bf
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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 android.hardware.vehicle@2.0;
+
+interface IVehicleCallback {
+
+    /*
+     * Event callback happens whenever a variable that the API user has
+     * subscribed to needs to be reported. This may be based purely on
+     * threshold and frequency (a regular subscription, see subscribe call's
+     * arguments) or when the IVehicle#set method was called and the actual
+     * change needs to be reported.
+     *
+     * These callbacks are chunked.
+     *
+     * @param values that has been updated.
+     */
+    oneway onPropertyEvent(vec<VehiclePropValue> propValues);
+
+    /*
+     * This method gets called if the client was subscribed to a property using
+     * SubscribeFlags::SET_CALL flag and IVehicle#set(...) method was called.
+     *
+     * These events must be delivered to subscriber immediately without any
+     * batching.
+     *
+     * @param value Value that was set by a client.
+     */
+    oneway onPropertySet(VehiclePropValue propValue);
+
+    /*
+     * Set property value is usually asynchronous operation. Thus even if
+     * client received StatusCode::OK from the IVehicle::set(...) this
+     * doesn't guarantee that the value was successfully propagated to the
+     * vehicle network. If such rare event occurs this method must be called.
+     *
+     * @param errorCode - any value from StatusCode enum.
+     * @param property - a property where error has happened.
+     * @param areaId - bitmask that specifies in which areas the problem has
+     *                 occurred, must be 0 for global properties
+     */
+    oneway onPropertySetError(StatusCode errorCode,
+                              VehicleProperty propId,
+                              int32_t areaId);
+};
diff --git a/vehicle/2.0/default/Android.mk b/vehicle/2.0/default/Android.mk
new file mode 100644 (file)
index 0000000..ccf18b6
--- /dev/null
@@ -0,0 +1,110 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+module_prefix = android.hardware.vehicle@2.0
+
+###############################################################################
+# Vehicle reference implementation lib
+###############################################################################
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(module_prefix)-manager-lib
+LOCAL_SRC_FILES := \
+    vehicle_hal_manager/SubscriptionManager.cpp \
+    vehicle_hal_manager/VehicleHalManager.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libbinder \
+    libhidl \
+    libhwbinder \
+    libutils \
+    $(module_prefix) \
+
+include $(BUILD_STATIC_LIBRARY)
+
+###############################################################################
+# Vehicle default VehicleHAL implementation
+###############################################################################
+include $(CLEAR_VARS)
+
+LOCAL_MODULE:= $(module_prefix)-default-impl-lib
+LOCAL_SRC_FILES:= \
+    impl/DefaultVehicleHal.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libbinder \
+    libhidl \
+    libhwbinder \
+    libutils \
+    $(module_prefix) \
+
+include $(BUILD_STATIC_LIBRARY)
+
+
+###############################################################################
+# Vehicle reference implementation unit tests
+###############################################################################
+include $(CLEAR_VARS)
+
+LOCAL_MODULE:= $(module_prefix)-manager-unit-tests
+
+LOCAL_WHOLE_STATIC_LIBRARIES := $(module_prefix)-manager-lib
+
+LOCAL_SRC_FILES:= \
+    tests/VehicleObjectPool_test.cpp \
+    tests/VehiclePropConfigIndex_test.cpp \
+    tests/SubscriptionManager_test.cpp \
+    tests/VehicleHalManager_test.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libbinder \
+    libhidl \
+    libhwbinder \
+    libutils \
+    $(module_prefix) \
+
+LOCAL_CFLAGS += -Wall -Wextra
+LOCAL_MODULE_TAGS := tests
+
+include $(BUILD_NATIVE_TEST)
+
+
+###############################################################################
+# Vehicle HAL service
+###############################################################################
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(module_prefix)-service
+LOCAL_INIT_RC := $(module_prefix)-service.rc
+LOCAL_MODULE_RELATIVE_PATH := hw
+
+LOCAL_SRC_FILES := \
+    VehicleService.cpp
+
+LOCAL_WHOLE_STATIC_LIBRARIES := \
+    $(module_prefix)-manager-lib \
+    $(module_prefix)-default-impl-lib \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libbinder \
+    libhidl \
+    libhwbinder \
+    libutils \
+    android.hardware.vehicle@2.0
+
+include $(BUILD_EXECUTABLE)
diff --git a/vehicle/2.0/default/VehicleHal.h b/vehicle/2.0/default/VehicleHal.h
new file mode 100644 (file)
index 0000000..2807f28
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_VehicleHal_H_
+#define android_hardware_vehicle_V2_0_VehicleHal_H_
+
+#include <android/hardware/vehicle/2.0/IVehicle.h>
+#include "vehicle_hal_manager/VehicleObjectPool.h"
+
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+/**
+ * This is a low-level vehicle hal interface that should be implemented by
+ * Vendor.
+ */
+class VehicleHal {
+public:
+    using VehiclePropValuePtr = recyclable_ptr<VehiclePropValue>;
+
+    using HalEventFunction = std::function<void(VehiclePropValuePtr)>;
+    using HalErrorFunction = std::function<void(
+            StatusCode errorCode, VehicleProperty property, int32_t areaId)>;
+
+    virtual ~VehicleHal() {}
+
+    virtual std::vector<VehiclePropConfig> listProperties() = 0;
+    virtual VehiclePropValuePtr get(const VehiclePropValue& requestedPropValue,
+                                    StatusCode* outStatus) = 0;
+
+    virtual StatusCode set(const VehiclePropValue& propValue) = 0;
+
+    /**
+     * Subscribe to HAL property events. This method might be called multiple
+     * times for the same vehicle property to update subscribed areas or sample
+     * rate.
+     *
+     * @param property to subscribe
+     * @param areas a bitwise vehicle areas or 0 for all supported areas
+     * @param sampleRate sample rate in Hz for properties that support sample
+     *                   rate, e.g. for properties with
+     *                   VehiclePropertyChangeMode::CONTINUOUS
+     */
+    virtual StatusCode subscribe(VehicleProperty property,
+                               int32_t areas,
+                               float sampleRate) = 0;
+
+    /**
+     * Unsubscribe from HAL events for given property
+     *
+     * @param property vehicle property to unsubscribe
+     */
+    virtual StatusCode unsubscribe(VehicleProperty property) = 0;
+
+    /**
+     * Override this method if you need to do one-time initialization.
+     */
+    virtual void onCreate() {}
+
+    void init(
+        VehiclePropValuePool* valueObjectPool,
+        const HalEventFunction& onHalEvent,
+        const HalErrorFunction& onHalError) {
+        mValuePool = valueObjectPool;
+        mOnHalEvent = onHalEvent;
+        mOnHalPropertySetError = onHalError;
+
+        onCreate();
+    }
+
+    VehiclePropValuePool* getValuePool() {
+        return mValuePool;
+    }
+protected:
+    /* Propagates property change events to vehicle HAL clients. */
+    void doHalEvent(VehiclePropValuePtr v) {
+        mOnHalEvent(std::move(v));
+    }
+
+    /* Propagates error during set operation to the vehicle HAL clients. */
+    void doHalPropertySetError(StatusCode errorCode,
+                               VehicleProperty propId, int32_t areaId) {
+        mOnHalPropertySetError(errorCode, propId, areaId);
+    }
+
+private:
+    HalEventFunction mOnHalEvent;
+    HalErrorFunction mOnHalPropertySetError;
+    VehiclePropValuePool* mValuePool;
+};
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+#endif //android_hardware_vehicle_V2_0_VehicleHal_H_
diff --git a/vehicle/2.0/default/VehicleService.cpp b/vehicle/2.0/default/VehicleService.cpp
new file mode 100644 (file)
index 0000000..e21dcd9
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.vehicle@2.0-service"
+#include <utils/Log.h>
+
+#include <iostream>
+
+#include <hwbinder/IPCThreadState.h>
+
+#include <vehicle_hal_manager/VehicleHalManager.h>
+#include <impl/DefaultVehicleHal.h>
+
+using namespace android;
+using namespace android::hardware;
+using namespace android::hardware::vehicle::V2_0;
+
+int main(int /* argc */, char* /* argv */ []) {
+    auto hal = std::make_unique<impl::DefaultVehicleHal>();
+    auto service = std::make_unique<VehicleHalManager>(hal.get());
+
+    ALOGI("Registering as service...");
+    service->registerAsService("Vehicle");
+
+    ALOGI("Ready");
+    ProcessState::self()->setThreadPoolMaxThreadCount(0);
+    ProcessState::self()->startThreadPool();
+    IPCThreadState::self()->joinThreadPool();
+}
diff --git a/vehicle/2.0/default/android.hardware.vehicle@2.0-service.rc b/vehicle/2.0/default/android.hardware.vehicle@2.0-service.rc
new file mode 100644 (file)
index 0000000..7c96da6
--- /dev/null
@@ -0,0 +1,4 @@
+service vehicle-hal-2.0 /system/bin/hw/android.hardware.vehicle@2.0-service
+    class hal
+    user system
+    group system
diff --git a/vehicle/2.0/default/impl/DefaultConfig.h b/vehicle/2.0/default/impl/DefaultConfig.h
new file mode 100644 (file)
index 0000000..7985737
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_impl_DefaultConfig_H_
+#define android_hardware_vehicle_V2_0_impl_DefaultConfig_H_
+
+#include <android/hardware/vehicle/2.0/IVehicle.h>
+#include <vehicle_hal_manager/VehicleUtils.h>
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+namespace impl {
+
+const VehiclePropConfig kVehicleProperties[] = {
+    {
+        .prop = VehicleProperty::INFO_MAKE,
+        .access = VehiclePropertyAccess::READ,
+        .changeMode = VehiclePropertyChangeMode::STATIC,
+        .permissionModel = VehiclePermissionModel::OEM_ONLY,
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_POWER_ON,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = toInt(VehicleAreaZone::ROW_1)
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_DEFROSTER,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas =
+                VehicleAreaWindow::FRONT_WINDSHIELD
+                | VehicleAreaWindow::REAR_WINDSHIELD
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_RECIRC_ON,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = toInt(VehicleAreaZone::ROW_1)
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_AC_ON,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = toInt(VehicleAreaZone::ROW_1)
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_AUTO_ON,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = toInt(VehicleAreaZone::ROW_1)
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_FAN_SPEED,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = toInt(VehicleAreaZone::ROW_1),
+        .areaConfigs = init_hidl_vec({
+                VehicleAreaConfig {
+                    .areaId = toInt(VehicleAreaZone::ROW_1),
+                    .minInt32Value = 1,
+                    .maxInt32Value = 7
+                }})
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_FAN_DIRECTION,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = toInt(VehicleAreaZone::ROW_1),
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_TEMPERATURE_SET,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas =
+                VehicleAreaZone::ROW_1_LEFT
+                | VehicleAreaZone::ROW_1_RIGHT,
+        .areaConfigs = init_hidl_vec({
+            VehicleAreaConfig {
+                .areaId = toInt(VehicleAreaZone::ROW_1_LEFT),
+                .minFloatValue = 16,
+                .maxFloatValue = 32,
+            },
+            VehicleAreaConfig {
+                .areaId = toInt(VehicleAreaZone::ROW_1_RIGHT),
+                .minFloatValue = 16,
+                .maxFloatValue = 32,
+            }})
+    },
+
+    {
+        .prop = VehicleProperty::NIGHT_MODE,
+        .access = VehiclePropertyAccess::READ,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+    },
+
+    {
+        .prop = VehicleProperty::GEAR_SELECTION,
+        .access = VehiclePropertyAccess::READ,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+    },
+
+    {
+        .prop = VehicleProperty::INFO_FUEL_CAPACITY,
+        .access = VehiclePropertyAccess::READ,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::OEM_ONLY,
+        .areaConfigs = init_hidl_vec({
+                                         VehicleAreaConfig {
+                                             .minFloatValue = 0,
+                                             .maxFloatValue = 1.0
+                                         }
+                                     })
+    },
+
+    {
+        .prop = VehicleProperty::DISPLAY_BRIGHTNESS,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::OEM_ONLY,
+        .areaConfigs = init_hidl_vec({
+                                         VehicleAreaConfig {
+                                             .minInt32Value = 0,
+                                             .maxInt32Value = 10
+                                         }
+                                     })
+    }
+};
+
+}  // impl
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+#endif // android_hardware_vehicle_V2_0_impl_DefaultConfig_H_
diff --git a/vehicle/2.0/default/impl/DefaultVehicleHal.cpp b/vehicle/2.0/default/impl/DefaultVehicleHal.cpp
new file mode 100644 (file)
index 0000000..c56248b
--- /dev/null
@@ -0,0 +1,196 @@
+/*
+ * 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.
+ */
+
+#include "DefaultVehicleHal.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+namespace impl {
+
+VehicleHal::VehiclePropValuePtr DefaultVehicleHal::get(
+        const VehiclePropValue& requestedPropValue, StatusCode* outStatus) {
+    *outStatus = StatusCode::OK;
+
+    VehiclePropValuePtr v;
+    VehicleProperty property = requestedPropValue.prop;
+    int32_t areaId = requestedPropValue.areaId;
+    auto& pool = *getValuePool();
+
+    switch (property) {
+        case VehicleProperty::INFO_MAKE:
+            v = pool.obtainString("Default Car");
+            break;
+        case VehicleProperty::HVAC_FAN_SPEED:
+            v = pool.obtainInt32(mFanSpeed);
+            break;
+        case VehicleProperty::HVAC_POWER_ON:
+            v = pool.obtainBoolean(mHvacPowerOn);
+            break;
+        case VehicleProperty::HVAC_RECIRC_ON:
+            v = pool.obtainBoolean(mHvacRecircOn);
+            break;
+        case VehicleProperty::HVAC_AC_ON:
+            v = pool.obtainBoolean(mHvacAcOn);
+            break;
+        case VehicleProperty::HVAC_AUTO_ON:
+            v = pool.obtainBoolean(mHvacAutoOn);
+            break;
+        case VehicleProperty::HVAC_FAN_DIRECTION:
+            v = pool.obtainInt32(toInt(mFanDirection));
+            break;
+        case VehicleProperty::HVAC_DEFROSTER:
+            bool defroster;
+            *outStatus = getHvacDefroster(areaId, &defroster);
+            if (StatusCode::OK == *outStatus) {
+                v = pool.obtainBoolean(defroster);
+            }
+            break;
+        case VehicleProperty::HVAC_TEMPERATURE_SET:
+            float value;
+            *outStatus = getHvacTemperature(requestedPropValue.areaId,
+                                            &value);
+            if (StatusCode::OK == *outStatus) {
+                v = pool.obtainFloat(value);
+            }
+            break;
+        case VehicleProperty::INFO_FUEL_CAPACITY:
+            v = pool.obtainFloat(0.75f);
+            break;
+        case VehicleProperty::DISPLAY_BRIGHTNESS:
+            v = pool.obtainInt32(mBrightness);
+            break;
+        case VehicleProperty::NIGHT_MODE:
+            v = pool.obtainBoolean(false);
+            break;
+        case VehicleProperty::GEAR_SELECTION:
+            v = pool.obtainInt32(toInt(VehicleGear::GEAR_PARK));
+            break;
+        default:
+            *outStatus = StatusCode::INVALID_ARG;
+    }
+
+    if (StatusCode::OK == *outStatus && v.get() != nullptr) {
+        v->prop = property;
+        v->areaId = areaId;
+        v->timestamp = elapsedRealtimeNano();
+    }
+
+    return v;
+}
+
+StatusCode DefaultVehicleHal::set(const VehiclePropValue& propValue) {
+    auto property = propValue.prop;
+    const auto& v = propValue.value;
+
+    StatusCode status = StatusCode::OK;
+
+    switch (property) {
+        case VehicleProperty::HVAC_POWER_ON:
+            mHvacPowerOn = v.int32Values[0] == 1;
+            break;
+        case VehicleProperty::HVAC_RECIRC_ON:
+            mHvacRecircOn = v.int32Values[0] == 1;
+            break;
+        case VehicleProperty::HVAC_AC_ON:
+            mHvacAcOn = v.int32Values[0] == 1;
+            break;
+        case VehicleProperty::HVAC_AUTO_ON:
+            mHvacAutoOn = v.int32Values[0] == 1;
+            break;
+        case VehicleProperty::HVAC_DEFROSTER:
+            status = setHvacDefroster(propValue.areaId, v.int32Values[0] == 1);
+            break;
+        case VehicleProperty::HVAC_FAN_DIRECTION:
+            mFanDirection =
+                    static_cast<VehicleHvacFanDirection>(v.int32Values[0]);
+            break;
+        case VehicleProperty::HVAC_FAN_SPEED:
+            mFanSpeed = v.int32Values[0];
+            break;
+        case VehicleProperty::HVAC_TEMPERATURE_SET:
+            status = setHvacTemperature(propValue.areaId, v.floatValues[0]);
+            break;
+        case VehicleProperty::DISPLAY_BRIGHTNESS:
+            mBrightness = v.int32Values[0];
+            break;
+        default:
+            status = StatusCode::INVALID_ARG;
+    }
+
+    return status;
+}
+
+StatusCode DefaultVehicleHal::getHvacTemperature(int32_t areaId,
+                                                 float* outValue)  {
+    if (areaId == toInt(VehicleAreaZone::ROW_1_LEFT)) {
+        *outValue = mRow1LeftHvacTemperatureSet;
+    } else if (areaId == toInt(VehicleAreaZone::ROW_1_RIGHT)) {
+        *outValue = mRow1RightHvacTemperatureSet;
+    } else {
+        return StatusCode::INVALID_ARG;
+    }
+    return StatusCode::OK;
+}
+
+StatusCode DefaultVehicleHal::setHvacTemperature(
+    int32_t areaId, float value) {
+    if (areaId == toInt(VehicleAreaZone::ROW_1_LEFT)) {
+        mRow1LeftHvacTemperatureSet = value;
+    } else if (areaId == toInt(VehicleAreaZone::ROW_1_RIGHT)) {
+        mRow1RightHvacTemperatureSet = value;
+    } else {
+        return StatusCode::INVALID_ARG;
+    }
+    return StatusCode::OK;
+}
+
+StatusCode DefaultVehicleHal::getHvacDefroster(int32_t areaId,
+                                               bool* outValue) {
+    ALOGI("Getting Hvac defroster for area: 0x%x", areaId);
+
+    if (areaId == toInt(VehicleAreaWindow::FRONT_WINDSHIELD)) {
+        *outValue = mFrontDefroster;
+    } else if (areaId == toInt(VehicleAreaWindow::REAR_WINDSHIELD)) {
+        *outValue = mRearDefroster;
+    } else {
+        ALOGE("Unable to get hvac defroster for area: 0x%x", areaId);
+        return StatusCode::INVALID_ARG;
+    }
+
+    ALOGI("Getting Hvac defroster for area: 0x%x, OK", areaId);
+    return StatusCode::OK;
+}
+
+StatusCode DefaultVehicleHal::setHvacDefroster(int32_t areaId, bool value) {
+    if (areaId == toInt(VehicleAreaWindow::FRONT_WINDSHIELD)) {
+        mFrontDefroster = value;
+    } else if (areaId == toInt(VehicleAreaWindow::REAR_WINDSHIELD)) {
+        mRearDefroster = value;
+    } else {
+        return StatusCode::INVALID_ARG;
+    }
+    return StatusCode::OK;
+}
+
+}  // impl
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
diff --git a/vehicle/2.0/default/impl/DefaultVehicleHal.h b/vehicle/2.0/default/impl/DefaultVehicleHal.h
new file mode 100644 (file)
index 0000000..231f2b2
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_impl_DefaultVehicleHal_H_
+#define android_hardware_vehicle_V2_0_impl_DefaultVehicleHal_H_
+
+#include <VehicleHal.h>
+#include <impl/DefaultConfig.h>
+#include <utils/SystemClock.h>
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+namespace impl {
+
+class DefaultVehicleHal : public VehicleHal {
+public:
+    std::vector<VehiclePropConfig> listProperties() override {
+        return std::vector<VehiclePropConfig>(std::begin(kVehicleProperties),
+                                              std::end(kVehicleProperties));
+    }
+
+    VehiclePropValuePtr get(const VehiclePropValue& requestedPropValue,
+                            StatusCode* outStatus) override;
+
+    StatusCode set(const VehiclePropValue& propValue) override;
+
+    StatusCode subscribe(VehicleProperty property,
+                       int32_t areas,
+                       float sampleRate) {
+        // TODO(pavelm): implement
+        return StatusCode::OK;
+    }
+
+    StatusCode unsubscribe(VehicleProperty property) {
+        // TODO(pavelm): implement
+        return StatusCode::OK;
+    }
+
+private:
+    StatusCode getHvacTemperature(int32_t areaId, float* outValue);
+    StatusCode setHvacTemperature(int32_t areaId, float value);
+    StatusCode getHvacDefroster(int32_t areaId, bool* outValue);
+    StatusCode setHvacDefroster(int32_t areaId, bool value);
+private:
+    int32_t mFanSpeed = 3;
+    int32_t mBrightness = 7;
+    float mRow1LeftHvacTemperatureSet = 16;
+    float mRow1RightHvacTemperatureSet = 22;
+    bool mFrontDefroster = false;
+    bool mRearDefroster = false;
+    bool mHvacPowerOn = true;
+    bool mHvacRecircOn = true;
+    bool mHvacAcOn = true;
+    bool mHvacAutoOn = true;
+    VehicleHvacFanDirection mFanDirection = VehicleHvacFanDirection::FACE;
+};
+
+}  // impl
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+
+#endif  // android_hardware_vehicle_V2_0_impl_DefaultVehicleHal_H_
diff --git a/vehicle/2.0/default/tests/SubscriptionManager_test.cpp b/vehicle/2.0/default/tests/SubscriptionManager_test.cpp
new file mode 100644 (file)
index 0000000..19b11e6
--- /dev/null
@@ -0,0 +1,203 @@
+/*
+ * 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.
+ */
+
+#include <unordered_map>
+#include <iostream>
+
+#include <gtest/gtest.h>
+
+#include <vehicle_hal_manager/VehiclePropConfigIndex.h>
+#include <VehicleHal.h>
+#include <vehicle_hal_manager/VehicleHalManager.h>
+#include "vehicle_hal_manager/SubscriptionManager.h"
+
+#include "VehicleHalTestUtils.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+namespace {
+
+using namespace std::placeholders;
+
+class SubscriptionManagerTest : public ::testing::Test {
+public:
+    SubscriptionManager manager;
+
+    const VehicleProperty PROP1 = VehicleProperty::HVAC_FAN_SPEED;
+    const VehicleProperty PROP2 = VehicleProperty::DISPLAY_BRIGHTNESS;
+
+    sp<IVehicleCallback> cb1 = new MockedVehicleCallback();
+    sp<IVehicleCallback> cb2 = new MockedVehicleCallback();
+    sp<IVehicleCallback> cb3 = new MockedVehicleCallback();
+
+    hidl_vec<SubscribeOptions> subscrToProp1 = init_hidl_vec(
+        {
+            SubscribeOptions {
+                .propId = PROP1,
+                .vehicleAreas = toInt(VehicleAreaZone::ROW_1_LEFT),
+                .flags = SubscribeFlags::HAL_EVENT
+            },
+        });
+
+    hidl_vec<SubscribeOptions> subscrToProp2 = init_hidl_vec(
+        {
+            SubscribeOptions {
+                .propId = PROP2,
+                .flags = SubscribeFlags::HAL_EVENT
+            },
+        });
+
+    hidl_vec<SubscribeOptions> subscrToProp1and2 = init_hidl_vec(
+        {
+            SubscribeOptions {
+                .propId = PROP1,
+                .vehicleAreas = toInt(VehicleAreaZone::ROW_1_LEFT),
+                .flags = SubscribeFlags::HAL_EVENT
+            },
+            SubscribeOptions {
+                .propId = PROP2,
+                .flags = SubscribeFlags::HAL_EVENT
+            },
+        });
+
+    static std::list<sp<IVehicleCallback>> extractCallbacks(
+            const std::list<sp<HalClient>>& clients) {
+        std::list<sp<IVehicleCallback>> callbacks;
+        for (auto c : clients) {
+            callbacks.push_back(c->getCallback());
+        }
+        return callbacks;
+    }
+
+    std::list<sp<HalClient>> clientsToProp1() {
+        return manager.getSubscribedClients(PROP1,
+                                            toInt(VehicleAreaZone::ROW_1_LEFT),
+                                            SubscribeFlags::DEFAULT);
+    }
+
+    std::list<sp<HalClient>> clientsToProp2() {
+        return manager.getSubscribedClients(PROP2, 0,
+                                            SubscribeFlags::DEFAULT);
+    }
+};
+
+
+TEST_F(SubscriptionManagerTest, multipleClients) {
+    manager.addOrUpdateSubscription(cb1, subscrToProp1);
+    manager.addOrUpdateSubscription(cb2, subscrToProp1);
+
+    auto clients = manager.getSubscribedClients(
+            PROP1,
+            toInt(VehicleAreaZone::ROW_1_LEFT),
+            SubscribeFlags::HAL_EVENT);
+
+    ASSERT_ALL_EXISTS({cb1, cb2}, extractCallbacks(clients));
+}
+
+TEST_F(SubscriptionManagerTest, negativeCases) {
+    manager.addOrUpdateSubscription(cb1, subscrToProp1);
+
+    // Wrong zone
+    auto clients = manager.getSubscribedClients(
+            PROP1,
+            toInt(VehicleAreaZone::ROW_2_LEFT),
+            SubscribeFlags::HAL_EVENT);
+    ASSERT_TRUE(clients.empty());
+
+    // Wrong prop
+    clients = manager.getSubscribedClients(
+            VehicleProperty::AP_POWER_BOOTUP_REASON,
+            toInt(VehicleAreaZone::ROW_1_LEFT),
+            SubscribeFlags::HAL_EVENT);
+    ASSERT_TRUE(clients.empty());
+
+    // Wrong flag
+    clients = manager.getSubscribedClients(
+            PROP1,
+            toInt(VehicleAreaZone::ROW_1_LEFT),
+            SubscribeFlags::SET_CALL);
+    ASSERT_TRUE(clients.empty());
+}
+
+TEST_F(SubscriptionManagerTest, mulipleSubscriptions) {
+    manager.addOrUpdateSubscription(cb1, subscrToProp1);
+
+    auto clients = manager.getSubscribedClients(
+            PROP1,
+            toInt(VehicleAreaZone::ROW_1_LEFT),
+            SubscribeFlags::DEFAULT);
+    ASSERT_EQ((size_t) 1, clients.size());
+    ASSERT_EQ(cb1, clients.front()->getCallback());
+
+    // Same property, but different zone, to make sure we didn't unsubscribe
+    // from previous zone.
+    manager.addOrUpdateSubscription(cb1, init_hidl_vec(
+        {
+            SubscribeOptions {
+                .propId = PROP1,
+                .vehicleAreas = toInt(VehicleAreaZone::ROW_2),
+                .flags = SubscribeFlags::DEFAULT
+            }
+        }));
+
+    clients = manager.getSubscribedClients(PROP1,
+                                           toInt(VehicleAreaZone::ROW_1_LEFT),
+                                           SubscribeFlags::DEFAULT);
+    ASSERT_ALL_EXISTS({cb1}, extractCallbacks(clients));
+
+    clients = manager.getSubscribedClients(PROP1,
+                                           toInt(VehicleAreaZone::ROW_2),
+                                           SubscribeFlags::DEFAULT);
+    ASSERT_ALL_EXISTS({cb1}, extractCallbacks(clients));
+}
+
+TEST_F(SubscriptionManagerTest, unsubscribe) {
+    manager.addOrUpdateSubscription(cb1, subscrToProp1);
+    manager.addOrUpdateSubscription(cb2, subscrToProp2);
+    manager.addOrUpdateSubscription(cb3, subscrToProp1and2);
+
+    ASSERT_ALL_EXISTS({cb1, cb3}, extractCallbacks(clientsToProp1()));
+    ASSERT_ALL_EXISTS({cb2, cb3}, extractCallbacks(clientsToProp2()));
+
+    ASSERT_FALSE(manager.unsubscribe(cb1, PROP1));
+    ASSERT_ALL_EXISTS({cb3}, extractCallbacks(clientsToProp1()));
+
+    // Make sure nothing changed in PROP2 so far.
+    ASSERT_ALL_EXISTS({cb2, cb3}, extractCallbacks(clientsToProp2()));
+
+    // No one subscribed to PROP1, subscription for PROP2 is not affected.
+    ASSERT_TRUE(manager.unsubscribe(cb3, PROP1));
+    ASSERT_ALL_EXISTS({cb2, cb3}, extractCallbacks(clientsToProp2()));
+
+    ASSERT_FALSE(manager.unsubscribe(cb3, PROP2));
+    ASSERT_ALL_EXISTS({cb2}, extractCallbacks(clientsToProp2()));
+
+    // The last client unsubscribed from this property.
+    ASSERT_TRUE(manager.unsubscribe(cb2, PROP2));
+
+    // No one was subscribed, return false.
+    ASSERT_FALSE(manager.unsubscribe(cb1, PROP1));
+}
+
+}  // namespace anonymous
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
diff --git a/vehicle/2.0/default/tests/VehicleHalManager_test.cpp b/vehicle/2.0/default/tests/VehicleHalManager_test.cpp
new file mode 100644 (file)
index 0000000..6ef1205
--- /dev/null
@@ -0,0 +1,446 @@
+/*
+ * 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.
+ */
+
+#include <unordered_map>
+#include <iostream>
+
+#include <gtest/gtest.h>
+
+#include <vehicle_hal_manager/VehiclePropConfigIndex.h>
+#include <VehicleHal.h>
+#include <vehicle_hal_manager/VehicleHalManager.h>
+#include <utils/SystemClock.h>
+#include "vehicle_hal_manager/SubscriptionManager.h"
+
+#include "VehicleHalTestUtils.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+namespace {
+
+using namespace std::placeholders;
+
+constexpr char kCarMake[] = "Default Car";
+constexpr int kRetriablePropMockedAttempts = 3;
+
+class MockedVehicleHal : public VehicleHal {
+public:
+    MockedVehicleHal() {
+        mConfigs.assign(std::begin(kVehicleProperties),
+                        std::end(kVehicleProperties));
+    }
+
+    std::vector<VehiclePropConfig> listProperties() override {
+        return mConfigs;
+    }
+
+    VehiclePropValuePtr get(const VehiclePropValue& requestedPropValue,
+             StatusCode* outStatus) override {
+        *outStatus = StatusCode::OK;
+        VehiclePropValuePtr pValue;
+        VehicleProperty property = requestedPropValue.prop;
+        int32_t areaId = requestedPropValue.areaId;
+
+        switch (property) {
+            case VehicleProperty::INFO_MAKE:
+                pValue = getValuePool()->obtainString(kCarMake);
+                break;
+            case VehicleProperty::INFO_FUEL_CAPACITY:
+                if (fuelCapacityAttemptsLeft-- > 0) {
+                    // Emulate property not ready yet.
+                    *outStatus = StatusCode::TRY_AGAIN;
+                } else {
+                    pValue = getValuePool()->obtainFloat(42.42);
+                }
+                break;
+            default:
+                auto key = makeKey(property, areaId);
+                if (mValues.count(key) == 0) {
+                    ALOGW("");
+                }
+                pValue = getValuePool()->obtain(mValues[key]);
+        }
+
+        if (*outStatus == StatusCode::OK && pValue.get() != nullptr) {
+            pValue->prop = property;
+            pValue->areaId = areaId;
+            pValue->timestamp = elapsedRealtimeNano();
+        }
+
+        return pValue;
+    }
+
+    StatusCode set(const VehiclePropValue& propValue) override {
+        if (VehicleProperty::MIRROR_FOLD == propValue.prop
+                && mirrorFoldAttemptsLeft-- > 0) {
+            return StatusCode::TRY_AGAIN;
+        }
+
+        mValues[makeKey(propValue)] = propValue;
+        return StatusCode::OK;
+    }
+
+    StatusCode subscribe(VehicleProperty property,
+                       int32_t areas,
+                       float sampleRate) override {
+        return StatusCode::OK;
+    }
+
+    StatusCode unsubscribe(VehicleProperty property) override {
+        return StatusCode::OK;
+    }
+
+    void sendPropEvent(recyclable_ptr<VehiclePropValue> value) {
+        doHalEvent(std::move(value));
+    }
+
+    void sendHalError(StatusCode error, VehicleProperty property,
+                      int32_t areaId) {
+        doHalPropertySetError(error, property, areaId);
+    }
+
+public:
+    int fuelCapacityAttemptsLeft = kRetriablePropMockedAttempts;
+    int mirrorFoldAttemptsLeft = kRetriablePropMockedAttempts;
+
+private:
+    int64_t makeKey(const VehiclePropValue& v) const {
+        return makeKey(v.prop, v.areaId);
+    }
+
+    int64_t makeKey(VehicleProperty prop, int32_t area) const {
+        return (static_cast<int64_t>(prop) << 32) | area;
+    }
+
+private:
+    std::vector<VehiclePropConfig> mConfigs;
+    std::unordered_map<int64_t, VehiclePropValue> mValues;
+};
+
+class VehicleHalManagerTest : public ::testing::Test {
+protected:
+    void SetUp() override {
+        hal.reset(new MockedVehicleHal);
+        manager.reset(new VehicleHalManager(hal.get()));
+
+        objectPool = hal->getValuePool();
+    }
+
+    void TearDown() override {
+        manager.reset(nullptr);
+        hal.reset(nullptr);
+    }
+public:
+    void invokeGet(VehicleProperty property, int32_t areaId) {
+        VehiclePropValue requestedValue {};
+        requestedValue.prop = property;
+        requestedValue.areaId = areaId;
+
+        invokeGet(requestedValue);
+    }
+
+    void invokeGet(const VehiclePropValue& requestedPropValue) {
+        actualValue = VehiclePropValue {};  // reset previous values
+
+        StatusCode refStatus;
+        VehiclePropValue refValue;
+        bool called = false;
+        manager->get(requestedPropValue, [&refStatus, &refValue, &called]
+            (StatusCode status, const VehiclePropValue& value) {
+            refStatus = status;
+            refValue = value;
+            called = true;
+        });
+        ASSERT_TRUE(called) << "callback wasn't called for prop: "
+                            << enumToHexString(requestedPropValue.prop);
+
+        actualValue = refValue;
+        actualStatusCode = refStatus;
+    }
+
+public:
+    VehiclePropValue actualValue;
+    StatusCode actualStatusCode;
+
+    VehiclePropValuePool* objectPool;
+    std::unique_ptr<MockedVehicleHal> hal;
+    std::unique_ptr<VehicleHalManager> manager;
+};
+
+TEST_F(VehicleHalManagerTest, getPropConfigs) {
+    hidl_vec<VehicleProperty> properties = init_hidl_vec(
+        { VehicleProperty::HVAC_FAN_SPEED,VehicleProperty::INFO_MAKE} );
+    bool called = false;
+
+    manager->getPropConfigs(properties,
+            [&called] (StatusCode status,
+                       const hidl_vec<VehiclePropConfig>& c) {
+        ASSERT_EQ(StatusCode::OK, status);
+        ASSERT_EQ(2u, c.size());
+        called = true;
+    });
+
+    ASSERT_TRUE(called);  // Verify callback received.
+
+    called = false;
+    manager->getPropConfigs(init_hidl_vec({VehicleProperty::HVAC_FAN_SPEED}),
+            [&called] (StatusCode status,
+                       const hidl_vec<VehiclePropConfig>& c) {
+        ASSERT_EQ(StatusCode::OK, status);
+        ASSERT_EQ(1u, c.size());
+        ASSERT_EQ(toString(kVehicleProperties[1]), toString(c[0]));
+        called = true;
+    });
+    ASSERT_TRUE(called);  // Verify callback received.
+
+    // TODO(pavelm): add case case when property was not declared.
+}
+
+TEST_F(VehicleHalManagerTest, getAllPropConfigs) {
+    bool called = false;
+    manager->getAllPropConfigs(
+            [&called] (const hidl_vec<VehiclePropConfig>& propConfigs) {
+        ASSERT_EQ(arraysize(kVehicleProperties), propConfigs.size());
+
+        for (size_t i = 0; i < propConfigs.size(); i++) {
+            ASSERT_EQ(toString(kVehicleProperties[i]),
+                      toString(propConfigs[i]));
+        }
+        called = true;
+    });
+    ASSERT_TRUE(called);  // Verify callback received.
+}
+
+TEST_F(VehicleHalManagerTest, halErrorEvent) {
+    const VehicleProperty PROP = VehicleProperty::DISPLAY_BRIGHTNESS;
+
+    sp<MockedVehicleCallback> cb = new MockedVehicleCallback();
+
+    hidl_vec<SubscribeOptions> options = init_hidl_vec(
+        {
+            SubscribeOptions {
+                .propId = PROP,
+                .flags = SubscribeFlags::DEFAULT
+            },
+        });
+
+    StatusCode res = manager->subscribe(cb, options);
+    ASSERT_EQ(StatusCode::OK, res);
+
+    hal->sendHalError(StatusCode::TRY_AGAIN, PROP, 0 /* area id*/);
+}
+
+TEST_F(VehicleHalManagerTest, subscribe) {
+    const VehicleProperty PROP = VehicleProperty::DISPLAY_BRIGHTNESS;
+
+    sp<MockedVehicleCallback> cb = new MockedVehicleCallback();
+
+    hidl_vec<SubscribeOptions> options = init_hidl_vec(
+        {
+            SubscribeOptions {
+                .propId = PROP,
+                .flags = SubscribeFlags::DEFAULT
+            },
+        });
+
+    StatusCode res = manager->subscribe(cb, options);
+    ASSERT_EQ(StatusCode::OK, res);
+
+    auto unsubscribedValue = objectPool->obtain(VehiclePropertyType::INT32);
+    unsubscribedValue->prop = VehicleProperty::HVAC_FAN_SPEED;
+
+    hal->sendPropEvent(std::move(unsubscribedValue));
+    auto& receivedEnvents = cb->getReceivedEvents();
+
+    ASSERT_TRUE(cb->waitForExpectedEvents(0)) << " Unexpected events received: "
+                                              << receivedEnvents.size()
+                                              << (receivedEnvents.size() > 0
+                                                  ? toString(receivedEnvents.front()[0]) : "");
+
+    auto subscribedValue = objectPool->obtain(VehiclePropertyType::INT32);
+    subscribedValue->prop = PROP;
+    subscribedValue->value.int32Values[0] = 42;
+
+    cb->reset();
+    VehiclePropValue actualValue(*subscribedValue.get());
+    hal->sendPropEvent(std::move(subscribedValue));
+
+    ASSERT_TRUE(cb->waitForExpectedEvents(1)) << "Events received: "
+                                              << receivedEnvents.size();
+
+    ASSERT_EQ(toString(actualValue),
+              toString(cb->getReceivedEvents().front()[0]));
+}
+
+TEST_F(VehicleHalManagerTest, subscribe_WriteOnly) {
+    const VehicleProperty PROP = VehicleProperty::HVAC_SEAT_TEMPERATURE;
+
+    sp<MockedVehicleCallback> cb = new MockedVehicleCallback();
+
+    hidl_vec<SubscribeOptions> options = init_hidl_vec(
+        {
+            SubscribeOptions {
+                .propId = PROP,
+                .flags = SubscribeFlags::HAL_EVENT
+            },
+        });
+
+    StatusCode res = manager->subscribe(cb, options);
+    // Unable to subscribe on Hal Events for write-only properties.
+    ASSERT_EQ(StatusCode::INVALID_ARG, res);
+
+
+    options[0].flags = SubscribeFlags::SET_CALL;
+
+    res = manager->subscribe(cb, options);
+    // OK to subscribe on SET method call for write-only properties.
+    ASSERT_EQ(StatusCode::OK, res);
+}
+
+TEST_F(VehicleHalManagerTest, get_StaticString) {
+    invokeGet(VehicleProperty::INFO_MAKE, 0);
+
+    ASSERT_EQ(StatusCode::OK, actualStatusCode);
+    ASSERT_EQ(VehicleProperty::INFO_MAKE, actualValue.prop);
+    ASSERT_STREQ(kCarMake, actualValue.value.stringValue.c_str());
+}
+
+TEST_F(VehicleHalManagerTest, get_NegativeCases) {
+    // Write-only property must fail.
+    invokeGet(VehicleProperty::HVAC_SEAT_TEMPERATURE, 0);
+    ASSERT_EQ(StatusCode::INVALID_ARG, actualStatusCode);
+
+    // Unknown property must fail.
+    invokeGet(VehicleProperty::MIRROR_Z_MOVE, 0);
+    ASSERT_EQ(StatusCode::INVALID_ARG, actualStatusCode);
+}
+
+TEST_F(VehicleHalManagerTest, get_Retriable) {
+    actualStatusCode = StatusCode::TRY_AGAIN;
+    int attempts = 0;
+    while (StatusCode::TRY_AGAIN == actualStatusCode && ++attempts < 10) {
+        invokeGet(VehicleProperty::INFO_FUEL_CAPACITY, 0);
+
+    }
+    ASSERT_EQ(StatusCode::OK, actualStatusCode);
+    ASSERT_EQ(kRetriablePropMockedAttempts + 1, attempts);
+    ASSERT_FLOAT_EQ(42.42, actualValue.value.floatValues[0]);
+}
+
+TEST_F(VehicleHalManagerTest, set_Basic) {
+    const auto PROP = VehicleProperty::DISPLAY_BRIGHTNESS;
+    const auto VAL = 7;
+
+    auto expectedValue = hal->getValuePool()->obtainInt32(VAL);
+    expectedValue->prop = PROP;
+    expectedValue->areaId = 0;
+
+    actualStatusCode = manager->set(*expectedValue.get());
+    ASSERT_EQ(StatusCode::OK, actualStatusCode);
+
+    invokeGet(PROP, 0);
+    ASSERT_EQ(StatusCode::OK, actualStatusCode);
+    ASSERT_EQ(PROP, actualValue.prop);
+    ASSERT_EQ(VAL, actualValue.value.int32Values[0]);
+}
+
+TEST_F(VehicleHalManagerTest, set_DifferentAreas) {
+    const auto PROP = VehicleProperty::HVAC_FAN_SPEED;
+    const auto VAL1 = 1;
+    const auto VAL2 = 2;
+    const auto AREA1 = toInt(VehicleAreaZone::ROW_1_LEFT);
+    const auto AREA2 = toInt(VehicleAreaZone::ROW_1_RIGHT);
+
+    {
+        auto expectedValue1 = hal->getValuePool()->obtainInt32(VAL1);
+        expectedValue1->prop = PROP;
+        expectedValue1->areaId = AREA1;
+        actualStatusCode = manager->set(*expectedValue1.get());
+        ASSERT_EQ(StatusCode::OK, actualStatusCode);
+
+        auto expectedValue2 = hal->getValuePool()->obtainInt32(VAL2);
+        expectedValue2->prop = PROP;
+        expectedValue2->areaId = AREA2;
+        actualStatusCode = manager->set(*expectedValue2.get());
+        ASSERT_EQ(StatusCode::OK, actualStatusCode);
+    }
+
+    {
+        invokeGet(PROP, AREA1);
+        ASSERT_EQ(StatusCode::OK, actualStatusCode);
+        ASSERT_EQ(PROP, actualValue.prop);
+        ASSERT_EQ(AREA1, actualValue.areaId);
+        ASSERT_EQ(VAL1, actualValue.value.int32Values[0]);
+
+        invokeGet(PROP, AREA2);
+        ASSERT_EQ(StatusCode::OK, actualStatusCode);
+        ASSERT_EQ(PROP, actualValue.prop);
+        ASSERT_EQ(AREA2, actualValue.areaId);
+        ASSERT_EQ(VAL2, actualValue.value.int32Values[0]);
+    }
+}
+
+TEST_F(VehicleHalManagerTest, set_Retriable) {
+    const auto PROP = VehicleProperty::MIRROR_FOLD;
+
+    auto v = hal->getValuePool()->obtainBoolean(true);
+    v->prop = PROP;
+    v->areaId = 0;
+
+    actualStatusCode = StatusCode::TRY_AGAIN;
+    int attempts = 0;
+    while (StatusCode::TRY_AGAIN == actualStatusCode && ++attempts < 10) {
+        actualStatusCode = manager->set(*v.get());
+    }
+
+    ASSERT_EQ(StatusCode::OK, actualStatusCode);
+    ASSERT_EQ(kRetriablePropMockedAttempts + 1, attempts);
+
+    invokeGet(PROP, 0);
+    ASSERT_EQ(StatusCode::OK, actualStatusCode);
+    ASSERT_TRUE(actualValue.value.int32Values[0]);
+}
+
+TEST(HalClientVectorTest, basic) {
+    HalClientVector clients;
+    sp<IVehicleCallback> callback1 = new MockedVehicleCallback();
+
+    sp<HalClient> c1 = new HalClient(callback1, 10, 20);
+    sp<HalClient> c2 = new HalClient(callback1, 10, 20);
+
+    clients.addOrUpdate(c1);
+    clients.addOrUpdate(c1);
+    clients.addOrUpdate(c2);
+    ASSERT_EQ(2u, clients.size());
+    ASSERT_FALSE(clients.isEmpty());
+    ASSERT_GE(0, clients.indexOf(c1));
+    ASSERT_GE(0, clients.remove(c1));
+    ASSERT_GE(0, clients.indexOf(c1));
+    ASSERT_GE(0, clients.remove(c1));
+    ASSERT_GE(0, clients.remove(c2));
+
+    ASSERT_TRUE(clients.isEmpty());
+}
+
+}  // namespace anonymous
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
diff --git a/vehicle/2.0/default/tests/VehicleHalTestUtils.h b/vehicle/2.0/default/tests/VehicleHalTestUtils.h
new file mode 100644 (file)
index 0000000..16d0be9
--- /dev/null
@@ -0,0 +1,272 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_VehicleDebugUtils_H_
+#define android_hardware_vehicle_V2_0_VehicleDebugUtils_H_
+
+#include <android/hardware/vehicle/2.0/types.h>
+#include <vehicle_hal_manager/VehicleUtils.h>
+#include <ios>
+#include <sstream>
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+const VehiclePropConfig kVehicleProperties[] = {
+    {
+        .prop = VehicleProperty::INFO_MAKE,
+        .access = VehiclePropertyAccess::READ,
+        .changeMode = VehiclePropertyChangeMode::STATIC,
+        .permissionModel = VehiclePermissionModel::OEM_ONLY,
+        .configString = "Some=config,options=if,you=have_any",
+    },
+
+    {
+        .prop = VehicleProperty::HVAC_FAN_SPEED,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = static_cast<int32_t>(
+            VehicleAreaZone::ROW_1_LEFT | VehicleAreaZone::ROW_1_RIGHT),
+        .areaConfigs = init_hidl_vec({
+             VehicleAreaConfig {
+                 .areaId = toInt(VehicleAreaZone::ROW_1_LEFT),
+                 .minInt32Value = 1,
+                 .maxInt32Value = 7},
+             VehicleAreaConfig {
+                 .areaId = toInt(VehicleAreaZone::ROW_1_RIGHT),
+                 .minInt32Value = 1,
+                 .maxInt32Value = 5,
+             }
+         }),
+    },
+
+    // Write-only property
+    {
+        .prop = VehicleProperty::HVAC_SEAT_TEMPERATURE,
+        .access = VehiclePropertyAccess::WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_SET,
+        .permissionModel = VehiclePermissionModel::NO_RESTRICTION,
+        .supportedAreas = static_cast<int32_t>(
+            VehicleAreaZone::ROW_1_LEFT | VehicleAreaZone::ROW_1_RIGHT),
+        .areaConfigs = init_hidl_vec({
+             VehicleAreaConfig {
+                 .areaId = toInt(VehicleAreaZone::ROW_1_LEFT),
+                 .minInt32Value = 64,
+                 .maxInt32Value = 80},
+             VehicleAreaConfig {
+                 .areaId = toInt(VehicleAreaZone::ROW_1_RIGHT),
+                 .minInt32Value = 64,
+                 .maxInt32Value = 80,
+             }
+         }),
+    },
+
+    {
+        .prop = VehicleProperty::INFO_FUEL_CAPACITY,
+        .access = VehiclePropertyAccess::READ,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::OEM_ONLY,
+        .areaConfigs = init_hidl_vec({
+                                         VehicleAreaConfig {
+                                             .minFloatValue = 0,
+                                             .maxFloatValue = 1.0
+                                         }
+                                     })
+    },
+
+    {
+        .prop = VehicleProperty::DISPLAY_BRIGHTNESS,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::OEM_ONLY,
+        .areaConfigs = init_hidl_vec({
+                                         VehicleAreaConfig {
+                                             .minInt32Value = 0,
+                                             .maxInt32Value = 10
+                                         }
+                                     })
+    },
+
+    {
+        .prop = VehicleProperty::MIRROR_FOLD,
+        .access = VehiclePropertyAccess::READ_WRITE,
+        .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+        .permissionModel = VehiclePermissionModel::OEM_ONLY,
+
+    }
+};
+
+constexpr auto kTimeout = std::chrono::milliseconds(500);
+
+class MockedVehicleCallback : public IVehicleCallback {
+private:
+    using MuxGuard = std::lock_guard<std::mutex>;
+    using HidlVecOfValues = hidl_vec<VehiclePropValue>;
+public:
+    // Methods from ::android::hardware::vehicle::V2_0::IVehicleCallback follow.
+    Return<void> onPropertyEvent(
+            const hidl_vec<VehiclePropValue>& values) override {
+        {
+            MuxGuard  g(mLock);
+            mReceivedEvents.push_back(values);
+        }
+        mEventCond.notify_one();
+        return Return<void>();
+    }
+    Return<void> onPropertySet(const VehiclePropValue& value) override {
+        return Return<void>();
+    }
+    Return<void> onPropertySetError(StatusCode errorCode,
+                                    VehicleProperty propId,
+                                    int32_t areaId) override {
+        return Return<void>();
+    }
+
+    bool waitForExpectedEvents(size_t expectedEvents) {
+        std::unique_lock<std::mutex> g(mLock);
+
+        if (expectedEvents == 0 && mReceivedEvents.size() == 0) {
+            // No events expected, let's sleep a little bit to make sure
+            // nothing will show up.
+            return mEventCond.wait_for(g, kTimeout) == std::cv_status::timeout;
+        }
+
+        while (expectedEvents != mReceivedEvents.size()) {
+            if (mEventCond.wait_for(g, kTimeout) == std::cv_status::timeout) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    void reset() {
+        mReceivedEvents.clear();
+    }
+
+    const std::vector<HidlVecOfValues>& getReceivedEvents() {
+        return mReceivedEvents;
+    }
+
+private:
+    std::mutex mLock;
+    std::condition_variable mEventCond;
+    std::vector<HidlVecOfValues> mReceivedEvents;
+};
+
+template<typename T>
+inline std::string hexString(T value) {
+    std::stringstream ss;
+    ss << std::showbase << std::hex << value;
+    return ss.str();
+}
+
+template <typename T, typename Collection>
+inline void assertAllExistsAnyOrder(
+        std::initializer_list<T> expected,
+        const Collection& actual,
+        const char* msg) {
+    std::set<T> expectedSet = expected;
+
+    for (auto a: actual) {
+        ASSERT_EQ(1u, expectedSet.erase(a))
+                << msg << "\nContains not unexpected value.\n";
+    }
+
+    ASSERT_EQ(0u, expectedSet.size())
+            << msg
+            << "\nDoesn't contain expected value.";
+}
+
+#define ASSERT_ALL_EXISTS(...) \
+    assertAllExistsAnyOrder(__VA_ARGS__, (std::string("Called from: ") + \
+            std::string(__FILE__) + std::string(":") + \
+            std::to_string(__LINE__)).c_str()); \
+
+template<typename T>
+inline std::string enumToHexString(T value) {
+    return hexString(toInt(value));
+}
+
+template <typename T>
+inline std::string toString(const hidl_vec<T>& vec) {
+    std::stringstream ss("[");
+    for (size_t i = 0; i < vec.size(); i++) {
+        if (i != 0) ss << ",";
+        ss << vec[i];
+    }
+    ss << "]";
+    return ss.str();
+}
+
+inline std::string toString(const VehiclePropValue &v) {
+    std::stringstream ss;
+    ss << "VehiclePropValue {n"
+       << "  prop: " << enumToHexString(v.prop) << ",\n"
+       << "  areaId: " << hexString(v.areaId) << ",\n"
+       << "  timestamp: " << v.timestamp << ",\n"
+       << "  value {\n"
+       << "    int32Values: " << toString(v.value.int32Values) << ",\n"
+       << "    floatValues: " << toString(v.value.floatValues) << ",\n"
+       << "    int64Values: " << toString(v.value.int64Values) << ",\n"
+       << "    bytes: " << toString(v.value.bytes) << ",\n"
+       << "    string: " << v.value.stringValue.c_str() << ",\n"
+       << "  }\n"
+       << "}\n";
+
+    return ss.str();
+}
+
+inline std::string toString(const VehiclePropConfig &config) {
+    std::stringstream ss;
+    ss << "VehiclePropConfig {\n"
+       << "  prop: " << enumToHexString(config.prop) << ",\n"
+       << "  supportedAreas: " << hexString(config.supportedAreas) << ",\n"
+       << "  access: " << enumToHexString(config.access) << ",\n"
+       << "  permissionModel: " << enumToHexString(config.permissionModel) << ",\n"
+       << "  changeMode: " << enumToHexString(config.changeMode) << ",\n"
+       << "  configFlags: " << hexString(config.configFlags) << ",\n"
+       << "  minSampleRate: " << config.minSampleRate << ",\n"
+       << "  maxSampleRate: " << config.maxSampleRate << ",\n"
+       << "  configString: " << config.configString.c_str() << ",\n";
+
+    ss << "  areaConfigs {\n";
+    for (size_t i = 0; i < config.areaConfigs.size(); i++) {
+        const auto &area = config.areaConfigs[i];
+        ss << "    areaId: " << hexString(area.areaId) << ",\n"
+           << "    minFloatValue: " << area.minFloatValue << ",\n"
+           << "    minFloatValue: " << area.maxFloatValue << ",\n"
+           << "    minInt32Value: " << area.minInt32Value << ",\n"
+           << "    minInt32Value: " << area.maxInt32Value << ",\n"
+           << "    minInt64Value: " << area.minInt64Value << ",\n"
+           << "    minInt64Value: " << area.maxInt64Value << ",\n";
+    }
+    ss << "  }\n"
+       << "}\n";
+
+    return ss.str();
+}
+
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+
+#endif //VEHICLEHALDEBUGUTILS_H
diff --git a/vehicle/2.0/default/tests/VehicleObjectPool_test.cpp b/vehicle/2.0/default/tests/VehicleObjectPool_test.cpp
new file mode 100644 (file)
index 0000000..88b1be0
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * 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.
+ */
+
+#include <thread>
+
+#include <gtest/gtest.h>
+
+#include <vehicle_hal_manager/VehicleObjectPool.h>
+#include <utils/SystemClock.h>
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+namespace {
+
+class VehicleObjectPoolTest : public ::testing::Test {
+protected:
+    void SetUp() override {
+        stats = PoolStats::instance();
+        resetStats();
+        valuePool.reset(new VehiclePropValuePool);
+    }
+
+    void TearDown() override {
+        // At the end, all created objects should be either recycled or deleted.
+        // Some objects could be recycled multiple times, that's why it's <=
+        ASSERT_EQ(stats->Obtained, stats->Recycled);
+        ASSERT_LE(stats->Created, stats->Recycled);
+    }
+private:
+    void resetStats() {
+        stats->Obtained = 0;
+        stats->Created = 0;
+        stats->Recycled = 0;
+    }
+
+public:
+    PoolStats* stats;
+    std::unique_ptr<VehiclePropValuePool> valuePool;
+};
+
+TEST_F(VehicleObjectPoolTest, valuePoolBasicCorrectness) {
+    void* raw = valuePool->obtain(VehiclePropertyType::INT32).get();
+    // At this point, v1 should be recycled and the only object in the pool.
+    ASSERT_EQ(raw, valuePool->obtain(VehiclePropertyType::INT32).get());
+    // Obtaining value of another type - should return a new object
+    ASSERT_NE(raw, valuePool->obtain(VehiclePropertyType::FLOAT).get());
+
+    ASSERT_EQ(3u, stats->Obtained);
+    ASSERT_EQ(2u, stats->Created);
+}
+
+TEST_F(VehicleObjectPoolTest, valuePoolStrings) {
+    valuePool->obtain(VehiclePropertyType::STRING);
+    auto vs = valuePool->obtain(VehiclePropertyType::STRING);
+    vs->value.stringValue = "Hello";
+    void* raw = vs.get();
+    vs.reset();  // delete the pointer
+
+    auto vs2 = valuePool->obtain(VehiclePropertyType::STRING);
+    ASSERT_EQ(0u, vs2->value.stringValue.size());
+    ASSERT_NE(raw, valuePool->obtain(VehiclePropertyType::STRING).get());
+
+    ASSERT_EQ(0u, stats->Obtained);
+}
+
+TEST_F(VehicleObjectPoolTest, valuePoolMultithreadedBenchmark) {
+    // In this test we have T threads that concurrently in C cycles
+    // obtain and release O VehiclePropValue objects of FLOAT / INT32 types.
+
+    const auto T = 2;
+    const auto C  = 500;
+    const auto O = 100;
+
+    auto poolPtr = valuePool.get();
+
+    std::vector<std::thread> threads;
+    auto start = elapsedRealtimeNano();
+    for (int i = 0; i < T; i++) {
+        threads.push_back(std::thread([&poolPtr] () {
+            for (int j = 0; j < C; j++) {
+                std::vector<recyclable_ptr<VehiclePropValue>> vec;
+                for (int k = 0; k < O; k++) {
+                    vec.push_back(
+                        poolPtr->obtain(k % 2 == 0
+                                        ? VehiclePropertyType::FLOAT
+                                        : VehiclePropertyType::INT32));
+                }
+            }
+        }));
+    }
+
+    for (auto& t : threads) {
+        t.join();
+    }
+    auto finish = elapsedRealtimeNano();
+
+    ASSERT_EQ(T * C * O, stats->Obtained);
+    ASSERT_EQ(T * C * O, stats->Recycled);
+    // Created less than obtained.
+    ASSERT_GE(T * O, stats->Created);
+
+    auto elapsedMs = (finish - start) / 1000000;
+    ASSERT_GE(1000, elapsedMs);  // Less a second to access 100K objects.
+                                 // Typically it takes about 0.1s on Nexus6P.
+}
+
+}  // namespace anonymous
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
diff --git a/vehicle/2.0/default/tests/VehiclePropConfigIndex_test.cpp b/vehicle/2.0/default/tests/VehiclePropConfigIndex_test.cpp
new file mode 100644 (file)
index 0000000..aae7e62
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ */
+
+#include <gtest/gtest.h>
+
+#include <vehicle_hal_manager/VehiclePropConfigIndex.h>
+
+#include "VehicleHalTestUtils.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+namespace {
+
+class PropConfigTest : public ::testing::Test {
+protected:
+    void SetUp() override {
+        configs.assign(std::begin(kVehicleProperties),
+                       std::end(kVehicleProperties));
+    }
+
+    void TearDown() override {}
+
+public:
+    std::vector<VehiclePropConfig> configs;
+};
+
+TEST_F(PropConfigTest, hasConfig) {
+    VehiclePropConfigIndex index(configs);
+
+    ASSERT_TRUE(index.hasConfig(VehicleProperty::HVAC_FAN_SPEED));
+    ASSERT_TRUE(index.hasConfig(VehicleProperty::INFO_MAKE));
+    ASSERT_TRUE(index.hasConfig(VehicleProperty::INFO_FUEL_CAPACITY));
+
+    ASSERT_FALSE(index.hasConfig(VehicleProperty::INVALID));
+}
+
+TEST_F(PropConfigTest, getAllConfig) {
+    VehiclePropConfigIndex index(configs);
+
+    std::vector<VehiclePropConfig> actualConfigs = index.getAllConfigs();
+    ASSERT_EQ(configs.size(), actualConfigs.size());
+
+    for (size_t i = 0; i < actualConfigs.size(); i++) {
+        ASSERT_EQ(toString(configs[i]), toString(actualConfigs[i]));
+    }
+}
+
+TEST_F(PropConfigTest, getConfigs) {
+    VehiclePropConfigIndex index(configs);
+    auto actualConfig = index.getConfig(VehicleProperty::HVAC_FAN_SPEED);
+    ASSERT_EQ(toString(configs[1]), toString(actualConfig));
+}
+
+}  // namespace anonymous
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
\ No newline at end of file
diff --git a/vehicle/2.0/default/vehicle_hal_manager/ConcurrentQueue.h b/vehicle/2.0/default/vehicle_hal_manager/ConcurrentQueue.h
new file mode 100644 (file)
index 0000000..485f3dc
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_ConcurrentQueue_H_
+#define android_hardware_vehicle_V2_0_ConcurrentQueue_H_
+
+#include <queue>
+#include <atomic>
+#include <thread>
+#include <condition_variable>
+#include <iostream>
+
+namespace android {
+
+template<typename T>
+class ConcurrentQueue {
+public:
+    void waitForItems() {
+        std::unique_lock<std::mutex> g(mLock);
+        while (mQueue.empty() && mIsActive) {
+            mCond.wait(g);
+        }
+    }
+
+    std::vector<T> flush() {
+        std::vector<T> items;
+
+        MuxGuard g(mLock);
+        if (mQueue.empty() || !mIsActive) {
+            return items;
+        }
+        while (!mQueue.empty()) {
+            items.push_back(std::move(mQueue.front()));
+            mQueue.pop();
+        }
+        return items;
+    }
+
+    void push(T&& item) {
+        {
+            MuxGuard g(mLock);
+            if (!mIsActive) {
+                return;
+            }
+            mQueue.push(std::move(item));
+        }
+        mCond.notify_one();
+    }
+
+    /* Deactivates the queue, thus no one can push items to it, also
+     * notifies all waiting thread.
+     */
+    void deactivate() {
+        {
+            MuxGuard g(mLock);
+            mIsActive = false;
+        }
+        mCond.notify_all();  // To unblock all waiting consumers.
+    }
+
+    ConcurrentQueue() = default;
+
+    ConcurrentQueue(const ConcurrentQueue &) = delete;
+    ConcurrentQueue &operator=(const ConcurrentQueue &) = delete;
+private:
+    using MuxGuard = std::lock_guard<std::mutex>;
+
+    bool mIsActive = true;
+    mutable std::mutex mLock;
+    std::condition_variable mCond;
+    std::queue<T> mQueue;
+};
+
+template<typename T>
+class BatchingConsumer {
+private:
+    enum class State {
+        INIT = 0,
+        RUNNING = 1,
+        STOP_REQUESTED = 2,
+        STOPPED = 3,
+    };
+
+public:
+    BatchingConsumer() : mState(State::INIT) {}
+
+    BatchingConsumer(const BatchingConsumer &) = delete;
+    BatchingConsumer &operator=(const BatchingConsumer &) = delete;
+
+    using OnBatchReceivedFunc = std::function<void(const std::vector<T>& vec)>;
+
+    void run(ConcurrentQueue<T>* queue,
+             std::chrono::nanoseconds batchInterval,
+             const OnBatchReceivedFunc& func) {
+        mQueue = queue;
+        mBatchInterval = batchInterval;
+
+        std::thread(&BatchingConsumer<T>::runInternal, this, func).detach();
+    }
+
+    void requestStop() {
+        if (mState.exchange(State::STOP_REQUESTED) != State::RUNNING) {
+            mState = State::STOPPED;
+            mCondStopped.notify_one();
+        }
+    }
+
+    void waitStopped() {
+        std::unique_lock<std::mutex> g(mLock);
+        while (State::STOPPED != mState) {
+            mCondStopped.wait(g);
+        }
+    }
+
+private:
+    void runInternal(const OnBatchReceivedFunc& onBatchReceived) {
+        if (mState.exchange(State::RUNNING) == State::INIT) {
+            while (State::RUNNING == mState) {
+                mQueue->waitForItems();
+                if (State::STOP_REQUESTED == mState) break;
+
+                std::this_thread::sleep_for(mBatchInterval);
+                if (State::STOP_REQUESTED == mState) break;
+
+                std::vector<T> items = mQueue->flush();
+
+                if (items.size() > 0) {
+                    onBatchReceived(items);
+                }
+            }
+        }
+
+        mState = State::STOPPED;
+        mCondStopped.notify_one();
+    }
+
+private:
+    std::mutex mLock;
+    std::condition_variable mCondStopped;
+
+    std::atomic<State> mState;
+    std::chrono::nanoseconds mBatchInterval;
+    ConcurrentQueue<T>* mQueue;
+};
+
+}  // namespace android
+
+#endif //android_hardware_vehicle_V2_0_ConcurrentQueue_H_
diff --git a/vehicle/2.0/default/vehicle_hal_manager/SubscriptionManager.cpp b/vehicle/2.0/default/vehicle_hal_manager/SubscriptionManager.cpp
new file mode 100644 (file)
index 0000000..910413e
--- /dev/null
@@ -0,0 +1,255 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.vehicle@2.0-impl"
+
+#include <cmath>
+
+#include <utils/Errors.h>
+
+#include "VehicleUtils.h"
+#include "SubscriptionManager.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+bool mergeSubscribeOptions(const SubscribeOptions &oldOpts,
+                           const SubscribeOptions &newOpts,
+                           SubscribeOptions *outResult) {
+
+    int32_t updatedAreas = oldOpts.vehicleAreas;
+    if (updatedAreas != kAllSupportedAreas) {
+        updatedAreas = newOpts.vehicleAreas != kAllSupportedAreas
+            ? updatedAreas | newOpts.vehicleAreas
+            : kAllSupportedAreas;
+    }
+
+    float updatedRate = std::max(oldOpts.sampleRate, newOpts.sampleRate);
+    SubscribeFlags updatedFlags = SubscribeFlags(oldOpts.flags | newOpts.flags);
+
+    bool updated = updatedRate > oldOpts.sampleRate
+                   || updatedAreas != oldOpts.vehicleAreas
+                   || updatedFlags != oldOpts.flags;
+    if (updated) {
+        *outResult = oldOpts;
+        outResult->vehicleAreas = updatedAreas;
+        outResult->sampleRate = updatedRate;
+        outResult->flags = updatedFlags;
+    }
+
+    return updated;
+}
+
+void HalClient::addOrUpdateSubscription(const SubscribeOptions &opts)  {
+    auto it = mSubscriptions.find(opts.propId);
+    if (it == mSubscriptions.end()) {
+        mSubscriptions.emplace(opts.propId, opts);
+    } else {
+        const SubscribeOptions& oldOpts = it->second;
+        SubscribeOptions updatedOptions;
+        if (mergeSubscribeOptions(oldOpts, opts, &updatedOptions)) {
+            mSubscriptions.erase(it);
+            mSubscriptions.emplace(opts.propId, updatedOptions);
+        }
+    }
+}
+
+bool HalClient::isSubscribed(VehicleProperty propId, int32_t areaId, SubscribeFlags flags) {
+    auto it = mSubscriptions.find(propId);
+    if (it == mSubscriptions.end()) {
+        return false;
+    }
+    const SubscribeOptions& opts = it->second;
+    bool res = (opts.flags & flags)
+           && (opts.vehicleAreas == 0 || areaId == 0 || opts.vehicleAreas & areaId);
+    return res;
+}
+
+std::list<SubscribeOptions> SubscriptionManager::addOrUpdateSubscription(
+        const sp<IVehicleCallback> &callback,
+        const hidl_vec<SubscribeOptions> &optionList) {
+    std::list<SubscribeOptions> updatedSubscriptions;
+
+    MuxGuard g(mLock);
+
+    const sp<HalClient>& client = getOrCreateHalClientLocked(callback);
+
+    for (size_t i = 0; i < optionList.size(); i++) {
+        const SubscribeOptions& opts = optionList[i];
+        client->addOrUpdateSubscription(opts);
+
+        addClientToPropMapLocked(opts.propId, client);
+
+        if (SubscribeFlags::HAL_EVENT & opts.flags) {
+            SubscribeOptions updated;
+            if (updateHalEventSubscriptionLocked(opts, &updated)) {
+                updatedSubscriptions.push_back(updated);
+            }
+        }
+    }
+
+    return updatedSubscriptions;
+}
+
+std::list<HalClientValues> SubscriptionManager::distributeValuesToClients(
+        const std::vector<recyclable_ptr<VehiclePropValue>>& propValues,
+        SubscribeFlags flags) const {
+    std::map<sp<HalClient>, std::list<VehiclePropValue*>> clientValuesMap;
+
+    {
+        MuxGuard g(mLock);
+        for (const auto& propValue: propValues) {
+            VehiclePropValue* v = propValue.get();
+            auto clients = getSubscribedClientsLocked(
+                v->prop, v->areaId, flags);
+            for (const auto& client : clients) {
+                clientValuesMap[client].push_back(v);
+            }
+        }
+    }
+
+    std::list<HalClientValues> clientValues;
+    for (const auto& entry : clientValuesMap) {
+        clientValues.push_back(HalClientValues {
+            .client = entry.first,
+            .values = entry.second
+        });
+    }
+
+    return clientValues;
+}
+
+std::list<sp<HalClient>> SubscriptionManager::getSubscribedClients(
+    VehicleProperty propId, int32_t area, SubscribeFlags flags) const {
+    MuxGuard g(mLock);
+    return getSubscribedClientsLocked(propId, area, flags);
+}
+
+std::list<sp<HalClient>> SubscriptionManager::getSubscribedClientsLocked(
+        VehicleProperty propId, int32_t area, SubscribeFlags flags) const {
+    std::list<sp<HalClient>> subscribedClients;
+
+    sp<HalClientVector> propClients = getClientsForPropertyLocked(propId);
+    if (propClients.get() != nullptr) {
+        for (size_t i = 0; i < propClients->size(); i++) {
+            const auto& client = propClients->itemAt(i);
+            if (client->isSubscribed(propId, area, flags)) {
+                subscribedClients.push_back(client);
+            }
+        }
+    }
+
+    return subscribedClients;
+}
+
+bool SubscriptionManager::updateHalEventSubscriptionLocked(
+        const SubscribeOptions &opts, SubscribeOptions *outUpdated) {
+    bool updated = false;
+    auto it = mHalEventSubscribeOptions.find(opts.propId);
+    if (it == mHalEventSubscribeOptions.end()) {
+        *outUpdated = opts;
+        mHalEventSubscribeOptions.emplace(opts.propId, opts);
+        updated = true;
+    } else {
+        const SubscribeOptions& oldOpts = it->second;
+
+        if (mergeSubscribeOptions(oldOpts, opts, outUpdated)) {
+            mHalEventSubscribeOptions.erase(opts.propId);
+            mHalEventSubscribeOptions.emplace(opts.propId, *outUpdated);
+            updated = true;
+        }
+    }
+
+    return updated;
+}
+
+void SubscriptionManager::addClientToPropMapLocked(
+        VehicleProperty propId, const sp<HalClient> &client) {
+    auto it = mPropToClients.find(propId);
+    sp<HalClientVector> propClients;
+    if (it == mPropToClients.end()) {
+        propClients = new HalClientVector();
+        mPropToClients.insert(std::make_pair(propId, propClients));
+    } else {
+        propClients = it->second;
+    }
+    propClients->addOrUpdate(client);
+}
+
+sp<HalClientVector> SubscriptionManager::getClientsForPropertyLocked(
+        VehicleProperty propId) const {
+    auto it = mPropToClients.find(propId);
+    return it == mPropToClients.end() ? nullptr : it->second;
+}
+
+sp<HalClient> SubscriptionManager::getOrCreateHalClientLocked(
+        const sp<IVehicleCallback>& callback) {
+    auto it = mClients.find(callback);
+    if (it == mClients.end()) {
+        IPCThreadState* self = IPCThreadState::self();
+        pid_t pid = self->getCallingPid();
+        uid_t uid = self->getCallingUid();
+        sp<HalClient> client = new HalClient(callback, pid, uid);
+        mClients.emplace(callback, client);
+        return client;
+    } else {
+        return it->second;
+    }
+}
+
+bool SubscriptionManager::unsubscribe(const sp<IVehicleCallback>& callback,
+                                      VehicleProperty propId) {
+    MuxGuard g(mLock);
+    auto propertyClients = getClientsForPropertyLocked(propId);
+    auto clientIter = mClients.find(callback);
+    if (clientIter == mClients.end()) {
+        ALOGW("Unable to unsubscribe: no callback found, propId: 0x%x", propId);
+    } else {
+        auto client = clientIter->second;
+
+        if (propertyClients != nullptr) {
+            propertyClients->remove(client);
+
+            if (propertyClients->isEmpty()) {
+                mPropToClients.erase(propId);
+            }
+        }
+
+        bool isClientSubscribedToOtherProps = false;
+        for (const auto& propClient : mPropToClients) {
+            if (propClient.second->indexOf(client) >= 0) {
+                isClientSubscribedToOtherProps = true;
+                break;
+            }
+        }
+
+        if (!isClientSubscribedToOtherProps) {
+            mClients.erase(clientIter);
+        }
+    }
+
+    return (propertyClients == nullptr || propertyClients->isEmpty())
+            ? mHalEventSubscribeOptions.erase(propId) == 1
+            : false;
+}
+
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
diff --git a/vehicle/2.0/default/vehicle_hal_manager/SubscriptionManager.h b/vehicle/2.0/default/vehicle_hal_manager/SubscriptionManager.h
new file mode 100644 (file)
index 0000000..903bde5
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_SubscriptionManager_H_
+#define android_hardware_vehicle_V2_0_SubscriptionManager_H_
+
+#include <memory>
+#include <map>
+#include <set>
+#include <list>
+
+#include <utils/Log.h>
+#include <hwbinder/IPCThreadState.h>
+
+#include <android/hardware/vehicle/2.0/IVehicle.h>
+
+#include "ConcurrentQueue.h"
+#include "VehicleObjectPool.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+class HalClient : public android::RefBase {
+public:
+    HalClient(const sp<IVehicleCallback> &callback,
+              int32_t pid,
+              int32_t uid)
+        : mCallback(callback), mPid(pid), mUid(uid) {}
+
+    virtual ~HalClient() {}
+public:
+    sp<IVehicleCallback> getCallback() const {
+        return mCallback;
+    }
+
+    void addOrUpdateSubscription(const SubscribeOptions &opts);
+
+    bool isSubscribed(VehicleProperty propId,
+                      int32_t areaId,
+                      SubscribeFlags flags);
+
+private:
+    const sp<IVehicleCallback> mCallback;
+    const int32_t mPid;
+    const int32_t mUid;
+
+    std::map<VehicleProperty, SubscribeOptions> mSubscriptions;
+};
+
+class HalClientVector : private SortedVector<sp<HalClient>> , public RefBase {
+public:
+    virtual ~HalClientVector() {}
+
+    inline void addOrUpdate(const sp<HalClient> &client) {
+        SortedVector::add(client);
+    }
+
+    using SortedVector::remove;
+    using SortedVector::size;
+    using SortedVector::indexOf;
+    using SortedVector::itemAt;
+    using SortedVector::isEmpty;
+};
+
+struct HalClientValues {
+    sp<HalClient> client;
+    std::list<VehiclePropValue *> values;
+};
+
+class SubscriptionManager {
+public:
+    virtual ~SubscriptionManager() {}
+
+    /**
+     * Updates subscription. Returns the vector of properties subscription that
+     * needs to be updated in VehicleHAL.
+     */
+    std::list<SubscribeOptions> addOrUpdateSubscription(
+            const sp<IVehicleCallback>& callback,
+            const hidl_vec<SubscribeOptions>& optionList);
+
+    /**
+     * Returns a list of IVehicleCallback -> list of VehiclePropValue ready for
+     * dispatching to its clients.
+     */
+    std::list<HalClientValues> distributeValuesToClients(
+            const std::vector<recyclable_ptr<VehiclePropValue>>& propValues,
+            SubscribeFlags flags) const;
+
+    std::list<sp<HalClient>> getSubscribedClients(
+        VehicleProperty propId, int32_t area, SubscribeFlags flags) const;
+
+    /**
+     * Returns true the client was unsubscribed successfully and there are
+     * no more clients subscribed to given propId.
+     */
+    bool unsubscribe(const sp<IVehicleCallback>& callback,
+                     VehicleProperty propId);
+private:
+    std::list<sp< HalClient>> getSubscribedClientsLocked(
+            VehicleProperty propId, int32_t area, SubscribeFlags flags) const;
+
+    bool updateHalEventSubscriptionLocked(const SubscribeOptions &opts,
+                                          SubscribeOptions *out);
+
+    void addClientToPropMapLocked(VehicleProperty propId,
+                                  const sp<HalClient> &client);
+
+    sp<HalClientVector> getClientsForPropertyLocked(
+            VehicleProperty propId) const;
+
+    sp<HalClient> getOrCreateHalClientLocked(
+            const sp<IVehicleCallback> &callback);
+
+private:
+    using MuxGuard = std::lock_guard<std::mutex>;
+
+    mutable std::mutex mLock;
+
+    std::map<sp<IVehicleCallback>, sp<HalClient>> mClients;
+    std::map<VehicleProperty, sp<HalClientVector>> mPropToClients;
+    std::map<VehicleProperty, SubscribeOptions> mHalEventSubscribeOptions;
+};
+
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+
+#endif // android_hardware_vehicle_V2_0_SubscriptionManager_H_
diff --git a/vehicle/2.0/default/vehicle_hal_manager/VehicleHalManager.cpp b/vehicle/2.0/default/vehicle_hal_manager/VehicleHalManager.cpp
new file mode 100644 (file)
index 0000000..a84f991
--- /dev/null
@@ -0,0 +1,341 @@
+/*
+ * 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.
+ */
+#define LOG_TAG "android.hardware.vehicle@2.0-impl"
+
+#include <cmath>
+
+#include <utils/Errors.h>
+#include <utils/Log.h>
+#include <hidl/Status.h>
+#include <future>
+#include <bitset>
+
+#include "VehicleHalManager.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+using namespace std::placeholders;
+
+constexpr std::chrono::milliseconds kHalEventBatchingTimeWindow(10);
+
+const VehiclePropValue kEmptyValue{};
+
+/**
+ * Indicates what's the maximum size of hidl_vec<VehiclePropValue> we want
+ * to store in reusable object pool.
+ */
+constexpr auto kMaxHidlVecOfVehiclPropValuePoolSize = 20;
+
+Return<void> VehicleHalManager::getAllPropConfigs(
+        getAllPropConfigs_cb _hidl_cb) {
+    ALOGI("getAllPropConfigs called");
+    hidl_vec<VehiclePropConfig> hidlConfigs;
+    auto& halConfig = mConfigIndex->getAllConfigs();
+
+    hidlConfigs.setToExternal(
+            const_cast<VehiclePropConfig *>(halConfig.data()),
+            halConfig.size());
+
+    ALOGI("getAllPropConfigs calling callback");
+    _hidl_cb(hidlConfigs);
+
+    ALOGI("getAllPropConfigs done");
+    return Void();
+}
+
+Return<void> VehicleHalManager::getPropConfigs(
+        const hidl_vec<VehicleProperty> &properties,
+        getPropConfigs_cb _hidl_cb) {
+    std::vector<VehiclePropConfig> configs;
+    for (size_t i = 0; i < properties.size(); i++) {
+        VehicleProperty prop = properties[i];
+        if (mConfigIndex->hasConfig(prop)) {
+            configs.push_back(mConfigIndex->getConfig(prop));
+        } else {
+            ALOGW("Requested config for undefined property: 0x%x", prop);
+            _hidl_cb(StatusCode::INVALID_ARG, hidl_vec<VehiclePropConfig>());
+        }
+    }
+
+    _hidl_cb(StatusCode::OK, configs);
+
+    return Void();
+}
+
+Return<void> VehicleHalManager::get(
+        const VehiclePropValue& requestedPropValue, get_cb _hidl_cb) {
+    const auto* config = getPropConfigOrNull(requestedPropValue.prop);
+    if (config == nullptr) {
+        ALOGE("Failed to get value: config not found, property: 0x%x",
+              requestedPropValue.prop);
+        _hidl_cb(StatusCode::INVALID_ARG, kEmptyValue);
+        return Void();
+    }
+
+    if (!checkReadPermission(*config, getCallee())) {
+        _hidl_cb(StatusCode::INVALID_ARG, kEmptyValue);
+        return Void();
+    }
+
+    StatusCode status;
+    auto value = mHal->get(requestedPropValue, &status);
+    _hidl_cb(status, value.get() ? *value : kEmptyValue);
+
+
+    return Void();
+}
+
+Return<StatusCode> VehicleHalManager::set(const VehiclePropValue &value) {
+    auto prop = value.prop;
+    const auto* config = getPropConfigOrNull(prop);
+    if (config == nullptr) {
+        ALOGE("Failed to set value: config not found, property: 0x%x", prop);
+        return StatusCode::INVALID_ARG;
+    }
+
+    if (!checkWritePermission(*config, getCallee())) {
+        return StatusCode::INVALID_ARG;
+    }
+
+    handlePropertySetEvent(value);
+
+    auto status = mHal->set(value);
+
+    return Return<StatusCode>(status);
+}
+
+Return<StatusCode> VehicleHalManager::subscribe(
+        const sp<IVehicleCallback> &callback,
+        const hidl_vec<SubscribeOptions> &options) {
+    hidl_vec<SubscribeOptions> verifiedOptions(options);
+    for (size_t i = 0; i < verifiedOptions.size(); i++) {
+        SubscribeOptions& ops = verifiedOptions[i];
+        VehicleProperty prop = ops.propId;
+
+        const auto* config = getPropConfigOrNull(prop);
+        if (config == nullptr) {
+            ALOGE("Failed to subscribe: config not found, property: 0x%x",
+                  prop);
+            return StatusCode::INVALID_ARG;
+        }
+
+        if (!isSubscribable(*config, ops.flags)) {
+            ALOGE("Failed to subscribe: property 0x%x is not subscribable",
+                  prop);
+            return StatusCode::INVALID_ARG;
+        }
+
+        int32_t areas = isGlobalProp(prop) ? 0 : ops.vehicleAreas;
+        if (areas != 0 && ((areas & config->supportedAreas) != areas)) {
+            ALOGE("Failed to subscribe property 0x%x. Requested areas 0x%x are "
+                  "out of supported range of 0x%x", prop, ops.vehicleAreas,
+                  config->supportedAreas);
+            return StatusCode::INVALID_ARG;
+        }
+
+        ops.vehicleAreas = areas;
+        ops.sampleRate = checkSampleRate(*config, ops.sampleRate);
+    }
+
+    std::list<SubscribeOptions> updatedOptions =
+        mSubscriptionManager.addOrUpdateSubscription(callback, verifiedOptions);
+
+    for (auto opt : updatedOptions) {
+        mHal->subscribe(opt.propId, opt.vehicleAreas, opt.sampleRate);
+    }
+    // TODO(pavelm): link to death callback (not implemented yet in HIDL)
+
+    return StatusCode::OK;
+}
+
+Return<StatusCode> VehicleHalManager::unsubscribe(
+        const sp<IVehicleCallback>& callback, VehicleProperty propId) {
+    if (mSubscriptionManager.unsubscribe(callback, propId)) {
+        mHal->unsubscribe(propId);
+    }
+    return StatusCode::OK;
+}
+
+Return<void> VehicleHalManager::debugDump(IVehicle::debugDump_cb _hidl_cb) {
+    _hidl_cb("");
+    return Void();
+}
+
+void VehicleHalManager::init() {
+    ALOGI("VehicleHalManager::init");
+
+    mHidlVecOfVehiclePropValuePool.resize(kMaxHidlVecOfVehiclPropValuePoolSize);
+
+
+    mBatchingConsumer.run(&mEventQueue,
+                          kHalEventBatchingTimeWindow,
+                          std::bind(&VehicleHalManager::onBatchHalEvent,
+                                    this, _1));
+
+    mHal->init(&mValueObjectPool,
+               std::bind(&VehicleHalManager::onHalEvent, this, _1),
+               std::bind(&VehicleHalManager::onHalPropertySetError, this,
+                         _1, _2, _3));
+
+    // Initialize index with vehicle configurations received from VehicleHal.
+    mConfigIndex.reset(new VehiclePropConfigIndex(mHal->listProperties()));
+}
+
+VehicleHalManager::~VehicleHalManager() {
+    mBatchingConsumer.requestStop();
+    mEventQueue.deactivate();
+    // We have to wait until consumer thread is fully stopped because it may
+    // be in a state of running callback (onBatchHalEvent).
+    mBatchingConsumer.waitStopped();
+    ALOGI("VehicleHalManager::dtor");
+}
+
+void VehicleHalManager::onHalEvent(VehiclePropValuePtr v) {
+    mEventQueue.push(std::move(v));
+}
+
+void VehicleHalManager::onHalPropertySetError(StatusCode errorCode,
+                                              VehicleProperty property,
+                                              int32_t areaId) {
+    const auto& clients = mSubscriptionManager.getSubscribedClients(
+            property, 0, SubscribeFlags::HAL_EVENT);
+
+    for (auto client : clients) {
+        client->getCallback()->onPropertySetError(errorCode, property, areaId);
+    }
+}
+
+void VehicleHalManager::onBatchHalEvent(
+        const std::vector<VehiclePropValuePtr>& values) {
+    const auto& clientValues = mSubscriptionManager.distributeValuesToClients(
+            values, SubscribeFlags::HAL_EVENT);
+
+    for (const HalClientValues& cv : clientValues) {
+        auto vecSize = cv.values.size();
+        hidl_vec<VehiclePropValue> vec;
+        if (vecSize < kMaxHidlVecOfVehiclPropValuePoolSize) {
+            vec.setToExternal(&mHidlVecOfVehiclePropValuePool[0], vecSize);
+        } else {
+            vec.resize(vecSize);
+        }
+
+        int i = 0;
+        for (VehiclePropValue* pValue : cv.values) {
+            shallowCopy(&(vec)[i++], *pValue);
+        }
+        cv.client->getCallback()->onPropertyEvent(vec);
+    }
+}
+
+bool VehicleHalManager::isSampleRateFixed(VehiclePropertyChangeMode mode) {
+    return (mode & VehiclePropertyChangeMode::ON_SET)
+           || (mode & VehiclePropertyChangeMode::ON_CHANGE);
+}
+
+float VehicleHalManager::checkSampleRate(const VehiclePropConfig &config,
+                                         float sampleRate) {
+    if (isSampleRateFixed(config.changeMode)) {
+        if (std::abs(sampleRate) > std::numeric_limits<float>::epsilon()) {
+            ALOGW("Sample rate is greater than zero for on change type. "
+                      "Ignoring it.");
+        }
+        return 0.0;
+    } else {
+        if (sampleRate > config.maxSampleRate) {
+            ALOGW("Sample rate %f is higher than max %f. Setting sampling rate "
+                      "to max.", sampleRate, config.maxSampleRate);
+            return config.maxSampleRate;
+        }
+        if (sampleRate < config.minSampleRate) {
+            ALOGW("Sample rate %f is lower than min %f. Setting sampling rate "
+                      "to min.", sampleRate, config.minSampleRate);
+            return config.minSampleRate;
+        }
+    }
+    return sampleRate;  // Provided sample rate was good, no changes.
+}
+
+bool VehicleHalManager::isSubscribable(const VehiclePropConfig& config,
+                                       SubscribeFlags flags) {
+    bool isReadable = config.access & VehiclePropertyAccess::READ;
+
+    if (!isReadable && (SubscribeFlags::HAL_EVENT & flags)) {
+        ALOGW("Cannot subscribe, property 0x%x is not readable", config.prop);
+        return false;
+    }
+    if (config.changeMode == VehiclePropertyChangeMode::STATIC) {
+        ALOGW("Cannot subscribe, property 0x%x is static", config.prop);
+        return false;
+    }
+
+    //TODO: extend to support event notification for set from android
+    if (config.changeMode == VehiclePropertyChangeMode::POLL) {
+        ALOGW("Cannot subscribe, property 0x%x is poll only", config.prop);
+        return false;
+    }
+    return true;
+}
+
+bool VehicleHalManager::checkWritePermission(const VehiclePropConfig &config,
+                                             const Callee& callee) {
+    if (!(config.access & VehiclePropertyAccess::WRITE)) {
+        ALOGW("Property 0%x has no write access", config.prop);
+        return false;
+    }
+    //TODO(pavelm): check pid/uid has write access
+    return true;
+}
+
+bool VehicleHalManager::checkReadPermission(const VehiclePropConfig &config,
+                                            const Callee& callee) {
+    if (!(config.access & VehiclePropertyAccess::READ)) {
+        ALOGW("Property 0%x has no read access", config.prop);
+        return false;
+    }
+    //TODO(pavelm): check pid/uid has read access
+    return true;
+}
+
+void VehicleHalManager::handlePropertySetEvent(const VehiclePropValue& value) {
+    auto clients = mSubscriptionManager.getSubscribedClients(
+            value.prop, value.areaId, SubscribeFlags::SET_CALL);
+    for (auto client : clients) {
+        client->getCallback()->onPropertySet(value);
+    }
+}
+
+const VehiclePropConfig* VehicleHalManager::getPropConfigOrNull(
+        VehicleProperty prop) const {
+    return mConfigIndex->hasConfig(prop)
+           ? &mConfigIndex->getConfig(prop) : nullptr;
+}
+
+Callee VehicleHalManager::getCallee() {
+    Callee callee;
+    IPCThreadState* self = IPCThreadState::self();
+    callee.pid = self->getCallingPid();
+    callee.uid = self->getCallingUid();
+
+    return callee;
+}
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
diff --git a/vehicle/2.0/default/vehicle_hal_manager/VehicleHalManager.h b/vehicle/2.0/default/vehicle_hal_manager/VehicleHalManager.h
new file mode 100644 (file)
index 0000000..8353679
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2015 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_hardware_vehicle_V2_0_VehicleHalManager_H_
+#define android_hardware_vehicle_V2_0_VehicleHalManager_H_
+
+#include <stdint.h>
+#include <inttypes.h>
+#include <sys/types.h>
+#include <memory>
+#include <map>
+#include <set>
+#include <list>
+
+#include <hwbinder/IPCThreadState.h>
+
+#include <android/hardware/vehicle/2.0/IVehicle.h>
+
+#include "VehicleHal.h"
+#include "VehiclePropConfigIndex.h"
+#include "ConcurrentQueue.h"
+#include "SubscriptionManager.h"
+#include "VehicleObjectPool.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+struct Callee {
+    pid_t pid;
+    uid_t uid;
+};
+
+/**
+ * This class is a thick proxy between IVehicle HIDL interface and vendor's implementation.
+ *
+ * It has some boilerplate code like batching and caching property values, checking permissions,
+ * etc. Vendors must implement VehicleHal class.
+ */
+class VehicleHalManager : public IVehicle {
+public:
+    VehicleHalManager(VehicleHal* vehicleHal)
+        : mHal(vehicleHal) {
+        init();
+    }
+
+    virtual ~VehicleHalManager();
+
+    void init();
+
+    // ---------------------------------------------------------------------------------------------
+    // Methods derived from IVehicle
+    Return<void> getAllPropConfigs(getAllPropConfigs_cb _hidl_cb)  override;
+    Return<void> getPropConfigs(const hidl_vec<VehicleProperty>& properties,
+                                getPropConfigs_cb _hidl_cb)  override;
+    Return<void> get(const VehiclePropValue& requestedPropValue,
+                     get_cb _hidl_cb)  override;
+    Return<StatusCode> set(const VehiclePropValue& value)  override;
+    Return<StatusCode> subscribe(const sp<IVehicleCallback>& callback,
+                                const hidl_vec<SubscribeOptions>& options)  override;
+    Return<StatusCode> unsubscribe(const sp<IVehicleCallback>& callback,
+                                   VehicleProperty propId)  override;
+    Return<void> debugDump(debugDump_cb _hidl_cb = nullptr) override;
+
+private:
+    using VehiclePropValuePtr = VehicleHal::VehiclePropValuePtr;
+    // Returns true if needs to call again shortly.
+    using RetriableAction = std::function<bool()>;
+
+    // ---------------------------------------------------------------------------------------------
+    // Events received from VehicleHal
+    void onHalEvent(VehiclePropValuePtr  v);
+    void onHalPropertySetError(StatusCode errorCode, VehicleProperty property,
+                               int32_t areaId);
+
+    // ---------------------------------------------------------------------------------------------
+    // This method will be called from BatchingConsumer thread
+    void onBatchHalEvent(const std::vector<VehiclePropValuePtr >& values);
+
+    void handlePropertySetEvent(const VehiclePropValue& value);
+
+    const VehiclePropConfig* getPropConfigOrNull(VehicleProperty prop) const;
+
+    static bool isSubscribable(const VehiclePropConfig& config,
+                               SubscribeFlags flags);
+    static bool isSampleRateFixed(VehiclePropertyChangeMode mode);
+    static float checkSampleRate(const VehiclePropConfig& config,
+                                 float sampleRate);
+    static bool checkWritePermission(const VehiclePropConfig &config,
+                                     const Callee& callee);
+    static bool checkReadPermission(const VehiclePropConfig &config,
+                                    const Callee& callee);
+
+    static Callee getCallee();
+
+private:
+    VehicleHal* mHal;
+    std::unique_ptr<VehiclePropConfigIndex> mConfigIndex;
+    SubscriptionManager mSubscriptionManager;
+
+    hidl_vec<VehiclePropValue> mHidlVecOfVehiclePropValuePool;
+
+    ConcurrentQueue<VehiclePropValuePtr> mEventQueue;
+    BatchingConsumer<VehiclePropValuePtr> mBatchingConsumer;
+    VehiclePropValuePool mValueObjectPool;
+};
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+
+#endif // android_hardware_vehicle_V2_0_VehicleHalManager_H_
diff --git a/vehicle/2.0/default/vehicle_hal_manager/VehicleObjectPool.h b/vehicle/2.0/default/vehicle_hal_manager/VehicleObjectPool.h
new file mode 100644 (file)
index 0000000..b4a4b3e
--- /dev/null
@@ -0,0 +1,343 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_VehicleObjectPool_H_
+#define android_hardware_vehicle_V2_0_VehicleObjectPool_H_
+
+#include <iostream>
+#include <memory>
+#include <deque>
+#include <string>
+#include <map>
+#include <mutex>
+
+#include <android/hardware/vehicle/2.0/types.h>
+
+#include "VehicleUtils.h"
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+using android::hardware::hidl_vec;
+
+// Handy metric mostly for unit tests and debug.
+#define INC_METRIC_IF_DEBUG(val) PoolStats::instance()->val++;
+struct PoolStats {
+    std::atomic<uint32_t> Obtained {0};
+    std::atomic<uint32_t> Created {0};
+    std::atomic<uint32_t> Recycled {0};
+
+    static PoolStats* instance() {
+        static PoolStats inst;
+        return &inst;
+    }
+};
+
+/**
+ * Generic abstract object pool class. Users of this class must implement
+ * #createObject method.
+ *
+ * This class is thread-safe. Concurrent calls to #obtain(...) method from
+ * multiple threads is OK, also client can obtain an object in one thread and
+ * then move ownership to another thread.
+ *
+ */
+template<typename T>
+class ObjectPool {
+public:
+    ObjectPool() = default;
+    virtual ~ObjectPool() = default;
+
+    struct Deleter  {
+        using OnDeleteFunc = std::function<void(T*)>;
+
+        Deleter(const OnDeleteFunc& f) : mOnDelete(f) {};
+
+        Deleter() = default;
+        Deleter(const Deleter&) = default;
+
+        void operator()(T* o) {
+            mOnDelete(o);
+        }
+    private:
+        OnDeleteFunc mOnDelete;
+    };
+
+    using RecyclableType = std::unique_ptr<T, Deleter>;
+
+    virtual RecyclableType obtain() {
+        std::lock_guard<std::mutex> g(mLock);
+        INC_METRIC_IF_DEBUG(Obtained)
+        if (mObjects.empty()) {
+            INC_METRIC_IF_DEBUG(Created)
+            return wrap(createObject());
+        }
+
+        auto o = wrap(mObjects.front().release());
+        mObjects.pop_front();
+
+        return o;
+    }
+
+    ObjectPool& operator =(const ObjectPool &) = delete;
+    ObjectPool(const ObjectPool &) = delete;
+
+protected:
+    virtual T* createObject() = 0;
+
+    virtual void recycle(T* o) {
+        INC_METRIC_IF_DEBUG(Recycled)
+        std::lock_guard<std::mutex> g(mLock);
+        mObjects.push_back(std::unique_ptr<T> { o } );
+    }
+
+private:
+    const Deleter& getDeleter() {
+        if (!mDeleter.get()) {
+            Deleter *d = new Deleter(std::bind(&ObjectPool::recycle,
+                                               this,
+                                               std::placeholders::_1));
+            mDeleter.reset(d);
+        }
+        return *mDeleter.get();
+    }
+
+    RecyclableType wrap(T* raw) {
+        return RecyclableType { raw, getDeleter() };
+    }
+
+private:
+    mutable std::mutex mLock;
+    std::deque<std::unique_ptr<T>> mObjects;
+    std::unique_ptr<Deleter> mDeleter;
+};
+
+/**
+ * This is std::unique_ptr<> with custom delete operation that typically moves
+ * the pointer it holds back to ObectPool.
+ */
+template <typename T>
+using recyclable_ptr = typename ObjectPool<T>::RecyclableType;
+
+/**
+ * This class provides a pool of recycable VehiclePropertyValue objects.
+ *
+ * It has only one overloaded public method - obtain(...), users must call this
+ * method when new object is needed with given VehiclePropertyType and vector
+ * size (for vector properties). This method returns a recycable smart pointer
+ * to VehiclePropertyValue, essentially this is a std::unique_ptr with custom
+ * delete function, so recycable object has only one owner and developers can
+ * safely pass it around. Once this object goes out of scope, it will be
+ * returned the the object pool.
+ *
+ * Some objects are not recycable: strings and vector data types with
+ * vector length > maxRecyclableVectorSize (provided in the constructor). These
+ * objects will be deleted immediately once the go out of scope. There's no
+ * synchornization penalty for these objects since we do not store them in the
+ * pool.
+ *
+ * This class is thread-safe. Users can obtain an object in one thread and pass
+ * it to another.
+ *
+ * Sample usage:
+ *
+ *   VehiclePropValuePool pool;
+ *   auto v = pool.obtain(VehiclePropertyType::INT32);
+ *   v->propId = VehicleProperty::HVAC_FAN_SPEED;
+ *   v->areaId = VehicleAreaZone::ROW_1_LEFT;
+ *   v->timestamp = elapsedRealtimeNano();
+ *   v->value->int32Values[0] = 42;
+ *
+ *
+ */
+class VehiclePropValuePool {
+public:
+    using RecyclableType = recyclable_ptr<VehiclePropValue>;
+
+    /**
+     * Creates VehiclePropValuePool
+     *
+     * @param maxRecyclableVectorSize - vector value types (e.g.
+     * VehiclePropertyType::INT32_VEC) with size equal or less to this value
+     * will be stored in the pool. If users tries to obtain value with vector
+     * size greater than maxRecyclableVectorSize user will receive appropriate
+     * object, but once it goes out of scope it will be deleted immediately, not
+     * returning back to the object pool.
+     *
+     */
+    VehiclePropValuePool(size_t maxRecyclableVectorSize = 4) :
+        mMaxRecyclableVectorSize(maxRecyclableVectorSize) { };
+
+    RecyclableType obtain(VehiclePropertyType type) {
+        return obtain(type, 1);
+    }
+
+    RecyclableType obtain(VehiclePropertyType type, size_t vecSize) {
+        return isDisposable(type, vecSize)
+                ? obtainDisposable(type, vecSize)
+                : obtainRecylable(type, vecSize);
+    }
+
+    RecyclableType obtain(const VehiclePropValue& src) {
+        if (src.prop == VehicleProperty::INVALID) {
+            ALOGE("Unable to obtain an object from pool for unknown property");
+            return RecyclableType();
+        }
+        VehiclePropertyType type = getPropType(src.prop);
+        size_t vecSize = getVehicleRawValueVectorSize(src.value, type);;
+        auto dest = obtain(type, vecSize);
+
+        dest->prop = src.prop;
+        dest->areaId = src.areaId;
+        dest->timestamp = src.timestamp;
+        copyVehicleRawValue(&dest->value, src.value);
+
+        return dest;
+    }
+
+    RecyclableType obtainBoolean(bool value) {
+        return obtainInt32(value);
+    }
+
+    RecyclableType obtainInt32(int32_t value) {
+        auto val = obtain(VehiclePropertyType::INT32);
+        val->value.int32Values[0] = value;
+        return val;
+    }
+
+    RecyclableType obtainInt64(int64_t value) {
+        auto val = obtain(VehiclePropertyType::INT64);
+        val->value.int64Values[0] = value;
+        return val;
+    }
+
+    RecyclableType obtainFloat(float value) {
+        auto val = obtain(VehiclePropertyType::FLOAT);
+        val->value.floatValues[0] = value;
+        return val;
+    }
+
+    RecyclableType obtainString(const char* cstr) {
+        auto val = obtain(VehiclePropertyType::STRING);
+        val->value.stringValue = cstr;
+        return val;
+    }
+
+    VehiclePropValuePool(VehiclePropValuePool& ) = delete;
+    VehiclePropValuePool& operator=(VehiclePropValuePool&) = delete;
+
+private:
+    bool isDisposable(VehiclePropertyType type, size_t vecSize) const {
+        return vecSize > mMaxRecyclableVectorSize ||
+               VehiclePropertyType::STRING == type;
+    }
+
+    RecyclableType obtainDisposable(VehiclePropertyType valueType,
+                                    size_t vectorSize) const {
+        return RecyclableType {
+            createVehiclePropValue(valueType, vectorSize).release(),
+            mDisposableDeleter
+        };
+    }
+
+    RecyclableType obtainRecylable(VehiclePropertyType type, size_t vecSize) {
+        // VehiclePropertyType is not overlapping with vectorSize.
+        int32_t key = static_cast<int32_t>(type)
+                      | static_cast<int32_t>(vecSize);
+
+        std::lock_guard<std::mutex> g(mLock);
+        auto it = mValueTypePools.find(key);
+
+        if (it == mValueTypePools.end()) {
+            auto newPool(std::make_unique<InternalPool>(type, vecSize));
+            it = mValueTypePools.emplace(key, std::move(newPool)).first;
+        }
+        return it->second->obtain();
+    }
+
+    class InternalPool: public ObjectPool<VehiclePropValue> {
+    public:
+        InternalPool(VehiclePropertyType type, size_t vectorSize)
+            : mPropType(type), mVectorSize(vectorSize) {
+        }
+
+        RecyclableType obtain() {
+            return ObjectPool<VehiclePropValue>::obtain();
+        }
+    protected:
+        VehiclePropValue* createObject() override {
+            return createVehiclePropValue(mPropType, mVectorSize).release();
+        }
+
+        void recycle(VehiclePropValue* o) override {
+            ALOGE_IF(o == nullptr, "Attempt to recycle nullptr");
+
+            if (!check(&o->value)) {
+                ALOGE("Discarding value for prop 0x%x because it contains "
+                          "data that is not consistent with this pool. "
+                          "Expected type: %d, vector size: %d",
+                      o->prop, mPropType, mVectorSize);
+                delete o;
+            }
+            ObjectPool<VehiclePropValue>::recycle(o);
+        }
+
+    private:
+        bool check(VehiclePropValue::RawValue* v) {
+            return check(&v->int32Values,
+                         (VehiclePropertyType::INT32 == mPropType
+                             || VehiclePropertyType::INT32_VEC == mPropType
+                             || VehiclePropertyType::BOOLEAN == mPropType))
+                    && check(&v->floatValues,
+                             (VehiclePropertyType::FLOAT == mPropType
+                              || VehiclePropertyType::FLOAT_VEC == mPropType))
+                    && check(&v->int64Values,
+                             VehiclePropertyType::INT64 == mPropType)
+                    && check(&v->bytes,
+                             VehiclePropertyType::BYTES == mPropType)
+                    && v->stringValue.size() == 0;
+        }
+
+        template <typename VecType>
+        bool check(hidl_vec<VecType>* vec, bool expected) {
+            return vec->size() == (expected ? mVectorSize : 0);
+        }
+    private:
+        VehiclePropertyType mPropType;
+        size_t mVectorSize;
+    };
+
+private:
+    const ObjectPool<VehiclePropValue>::Deleter mDisposableDeleter {
+        [] (VehiclePropValue* v) {
+            delete v;
+        }
+    };
+
+private:
+    mutable std::mutex mLock;
+    const size_t mMaxRecyclableVectorSize;
+    std::map<int32_t, std::unique_ptr<InternalPool>> mValueTypePools;
+};
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+#endif // android_hardware_vehicle_V2_0_VehicleObjectPool_H_
diff --git a/vehicle/2.0/default/vehicle_hal_manager/VehiclePropConfigIndex.h b/vehicle/2.0/default/vehicle_hal_manager/VehiclePropConfigIndex.h
new file mode 100644 (file)
index 0000000..540fc33
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_VehiclePropConfigIndex_H_
+#define android_hardware_vehicle_V2_0_VehiclePropConfigIndex_H_
+
+#include <utils/KeyedVector.h>
+
+#include <android/hardware/vehicle/2.0/IVehicle.h>
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+/*
+ * This is thread-safe immutable class to hold vehicle property configuration
+ * data.
+ */
+class VehiclePropConfigIndex {
+public:
+    VehiclePropConfigIndex(
+        const std::vector<VehiclePropConfig>& properties)
+        : mConfigs(properties), mPropToConfig(mConfigs)
+    {}
+
+    bool hasConfig(VehicleProperty property) const {
+        return mPropToConfig.indexOfKey(property) >= 0;
+    }
+
+    const VehiclePropConfig& getConfig(VehicleProperty property) const {
+        return *mPropToConfig.valueFor(property);
+    }
+
+    const std::vector<VehiclePropConfig>& getAllConfigs() const {
+        return mConfigs;
+    }
+
+private:
+    typedef KeyedVector<VehicleProperty, const VehiclePropConfig*> PropConfigMap;
+    class ImmutablePropConfigMap : private PropConfigMap {
+    public:
+        ImmutablePropConfigMap(const std::vector<VehiclePropConfig>& configs) {
+            setCapacity(configs.size());
+            for (auto& config : configs) {
+                add(config.prop, &config);
+            }
+        }
+    public:
+        using PropConfigMap::valueFor;
+        using PropConfigMap::indexOfKey;
+    };
+
+private:
+    const std::vector<VehiclePropConfig> mConfigs;
+    const ImmutablePropConfigMap mPropToConfig;  // mConfigs must be declared
+                                                 // first.
+};
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+#endif // android_hardware_vehicle_V2_0_VehiclePropConfigIndex_H_
diff --git a/vehicle/2.0/default/vehicle_hal_manager/VehicleUtils.h b/vehicle/2.0/default/vehicle_hal_manager/VehicleUtils.h
new file mode 100644 (file)
index 0000000..5751eb1
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+ * 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.
+ */
+
+#ifndef android_hardware_vehicle_V2_0_VehicleUtils_H_
+#define android_hardware_vehicle_V2_0_VehicleUtils_H_
+
+#include <memory>
+
+#include <hidl/HidlSupport.h>
+
+#include <android/hardware/vehicle/2.0/types.h>
+
+namespace android {
+namespace hardware {
+namespace vehicle {
+namespace V2_0 {
+
+/** Represents all supported areas for a property. Can be used is  */
+constexpr int32_t kAllSupportedAreas = 0;
+
+template <typename T>
+inline hidl_vec<T> init_hidl_vec(std::initializer_list<const T> values) {
+    hidl_vec<T> vector;
+    vector.resize(values.size());
+    size_t i = 0;
+    for (auto& c : values) {
+        vector[i++] = c;
+    }
+    return vector;
+}
+
+/**
+ * Logical 'and' operator for class enums. The return type will be enum's
+ * underline type
+ */
+template <typename ENUM>
+inline typename std::underlying_type<ENUM>::type operator &(ENUM v1, ENUM v2) {
+    return static_cast<typename std::underlying_type<ENUM>::type>(v1)
+           & static_cast<typename std::underlying_type<ENUM>::type>(v2);
+}
+
+/** Returns underlying (integer) value for given enum. */
+template <typename ENUM>
+inline typename std::underlying_type<ENUM>::type toInt(ENUM const value) {
+    return static_cast<typename std::underlying_type<ENUM>::type>(value);
+}
+
+inline VehiclePropertyType getPropType(VehicleProperty prop) {
+    return static_cast<VehiclePropertyType>(
+            static_cast<int32_t>(prop)
+            & static_cast<int32_t>(VehiclePropertyType::MASK));
+}
+
+inline VehiclePropertyGroup getPropGroup(VehicleProperty prop) {
+    return static_cast<VehiclePropertyGroup>(
+                static_cast<int32_t>(prop)
+                & static_cast<int32_t>(VehiclePropertyGroup::MASK));
+}
+
+inline VehicleArea getPropArea(VehicleProperty prop) {
+    return static_cast<VehicleArea>(
+        static_cast<int32_t>(prop) & static_cast<int32_t>(VehicleArea::MASK));
+}
+
+inline bool isGlobalProp(VehicleProperty prop) {
+    return getPropArea(prop) == VehicleArea::GLOBAL;
+}
+
+inline bool checkPropType(VehicleProperty prop, VehiclePropertyType type) {
+    return getPropType(prop) == type;
+}
+
+inline bool isSystemProperty(VehicleProperty prop) {
+    return VehiclePropertyGroup::SYSTEM == getPropGroup(prop);
+}
+
+inline std::unique_ptr<VehiclePropValue> createVehiclePropValue(
+    VehiclePropertyType type, size_t vecSize) {
+    auto val = std::unique_ptr<VehiclePropValue>(new VehiclePropValue);
+    switch (type) {
+        case VehiclePropertyType::INT32:      // fall through
+        case VehiclePropertyType::INT32_VEC:  // fall through
+        case VehiclePropertyType::BOOLEAN:
+            val->value.int32Values.resize(vecSize);
+            break;
+        case VehiclePropertyType::FLOAT:
+        case VehiclePropertyType::FLOAT_VEC:  // fall through
+            val->value.floatValues.resize(vecSize);
+            break;
+        case VehiclePropertyType::INT64:
+            val->value.int64Values.resize(vecSize);
+            break;
+        case VehiclePropertyType::BYTES:
+            val->value.bytes.resize(vecSize);
+            break;
+        case VehiclePropertyType::STRING:
+            break; // Valid, but nothing to do.
+        default:
+            ALOGE("createVehiclePropValue: unknown type: %d", type);
+            val.reset(nullptr);
+    }
+    return val;
+}
+
+inline size_t getVehicleRawValueVectorSize(
+        const VehiclePropValue::RawValue& value, VehiclePropertyType type) {
+    switch (type) {
+        case VehiclePropertyType::INT32:      // fall through
+        case VehiclePropertyType::INT32_VEC:  // fall through
+        case VehiclePropertyType::BOOLEAN:
+            return value.int32Values.size();
+        case VehiclePropertyType::FLOAT:      // fall through
+        case VehiclePropertyType::FLOAT_VEC:
+            return value.floatValues.size();
+        case VehiclePropertyType::INT64:
+            return value.int64Values.size();
+        case VehiclePropertyType::BYTES:
+            return value.bytes.size();
+        default:
+            return 0;
+    }
+}
+
+/** Copies vector src to dest, dest should have enough space. */
+template <typename T>
+inline void copyHidlVec(hidl_vec<T>* dest, const hidl_vec<T>& src) {
+    for (size_t i = 0; i < std::min(dest->size(), src.size()); i++) {
+        (*dest)[i] = src[i];
+    }
+}
+
+inline void copyVehicleRawValue(VehiclePropValue::RawValue* dest,
+                                const VehiclePropValue::RawValue& src) {
+    copyHidlVec(&dest->int32Values, src.int32Values);
+    copyHidlVec(&dest->floatValues, src.floatValues);
+    copyHidlVec(&dest->int64Values, src.int64Values);
+    copyHidlVec(&dest->bytes, src.bytes);
+    dest->stringValue = src.stringValue;
+}
+
+template <typename T>
+inline void shallowCopyHidlVec(hidl_vec<T>* dest, const hidl_vec<T>& src) {
+    if (src.size() > 0) {
+        dest->setToExternal(const_cast<T*>(&src[0]), src.size());
+    } else if (dest->size() > 0) {
+        dest->resize(0);
+    }
+}
+
+inline void shallowCopyHidlStr(hidl_string* dest, const hidl_string& src ) {
+    if (!src.empty()) {
+        dest->setToExternal(src.c_str(), src.size());
+    } else if (dest->size() > 0) {
+        dest->setToExternal(0, 0);
+    }
+}
+
+inline void shallowCopy(VehiclePropValue* dest,
+                        const VehiclePropValue& src) {
+    dest->prop = src.prop;
+    dest->areaId = src.areaId;
+    dest->timestamp = src.timestamp;
+    shallowCopyHidlVec(&dest->value.int32Values, src.value.int32Values);
+    shallowCopyHidlVec(&dest->value.int64Values, src.value.int64Values);
+    shallowCopyHidlVec(&dest->value.floatValues, src.value.floatValues);
+    shallowCopyHidlVec(&dest->value.bytes, src.value.bytes);
+    shallowCopyHidlStr(&dest->value.stringValue, src.value.stringValue);
+}
+
+}  // namespace V2_0
+}  // namespace vehicle
+}  // namespace hardware
+}  // namespace android
+
+#endif // android_hardware_vehicle_V2_0_VehicleUtils_H_
diff --git a/vehicle/2.0/types.hal b/vehicle/2.0/types.hal
new file mode 100644 (file)
index 0000000..b19621c
--- /dev/null
@@ -0,0 +1,2501 @@
+/*
+ * 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 android.hardware.vehicle@2.0;
+
+/*
+ * Enumerates supported data types for VehicleProperty.
+ *
+ * This is a bitwise flag that supposed to be used in VehicleProperty enum.
+ */
+enum VehiclePropertyType : int32_t {
+    STRING         = 0x00100000,
+    BOOLEAN        = 0x00200000,
+    INT32          = 0x00400000,
+    INT32_VEC      = 0x00410000,
+    INT64          = 0x00500000,
+    FLOAT          = 0x00600000,
+    FLOAT_VEC      = 0x00610000,
+    BYTES          = 0x00700000,
+
+    MASK           = 0x00ff0000
+};
+
+/*
+ * Some properties may be associated with particular vehicle areas. For
+ * example, VehicleProperty:DOOR_LOCK property must be associated with
+ * particular door, thus this property must be marked with
+ * VehicleArea:DOOR flag.
+ *
+ * Other properties may not be associated with particular vehicle area,
+ * these kind of properties must have VehicleArea:GLOBAL flag.
+ *
+ * This is a bitwise flag that supposed to be used in VehicleProperty enum.
+ */
+enum VehicleArea : int32_t {
+      GLOBAL       = 0x01000000,
+      ZONE         = 0x02000000,
+      WINDOW       = 0x03000000,
+      MIRROR       = 0x04000000,
+      SEAT         = 0x05000000,
+      DOOR         = 0x06000000,
+
+      MASK         = 0x0f000000,
+};
+
+/*
+ * Enumerates property groups.
+ *
+ * This is a bitwise flag that supposed to be used in VehicleProperty enum.
+ */
+enum VehiclePropertyGroup : int32_t {
+    /*
+     * Properties declared in AOSP must have this flag.
+     */
+    SYSTEM         = 0x10000000,
+
+    /*
+     * Properties declared by vendors must have this flag.
+     */
+    VENDOR         = 0x20000000,
+
+    MASK           = 0xf0000000,
+};
+
+/*
+ * Declares all vehicle properties. VehicleProperty has a bitwise structure.
+ * Each property must have:
+ *   - an unique id from range 0x0100 - 0xffff
+ *   - associated data type using VehiclePropertyType
+ *   - property group (VehiclePropertyGroup)
+ *   - vehicle area (VehicleArea)
+ *
+ * Vendors are allowed to extend this enum with their own properties. In this
+ * case they must use VehiclePropertyGroup:VENDOR flag when property is
+ * declared.
+ */
+enum VehicleProperty: int32_t {
+
+    /* Undefined property. */
+    INVALID = 0x00000000,
+
+    /*
+     * VIN of vehicle
+     *
+     * @change_mode VehiclePropertyChangeMode:STATIC
+     * @access VehiclePropertyAccess:READ
+     */
+    INFO_VIN= (
+        0x0100
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:STRING
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Maker name of vehicle
+     *
+     * @change_mode VehiclePropertyChangeMode:STATIC
+     * @access VehiclePropertyAccess:READ
+     */
+    INFO_MAKE = (
+        0x0101
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:STRING
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Model of vehicle
+     *
+     * @change_mode VehiclePropertyChangeMode:STATIC
+     * @access VehiclePropertyAccess:READ
+     */
+    INFO_MODEL = (
+        0x0102
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:STRING
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Model year of vehicle.
+     *
+     * @change_mode VehiclePropertyChangeMode:STATIC
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:YEAR
+     */
+    INFO_MODEL_YEAR = (
+        0x0103
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Fuel capacity of the vehicle
+     *
+     * @change_mode VehiclePropertyChangeMode:STATIC
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:MILLILITER
+     */
+    INFO_FUEL_CAPACITY = (
+        0x0104
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Current odometer value of the vehicle
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE | VehiclePropertyChangeMode:CONTINUOUS
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:KILOMETER
+     */
+    PERF_ODOMETER = (
+        0x0204
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Speed of the vehicle
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE|VehiclePropertyChangeMode:CONTINUOUS
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:METER_PER_SEC
+     */
+    PERF_VEHICLE_SPEED = (
+        0x0207
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Temperature of engine coolant
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE|VehiclePropertyChangeMode:CONTINUOUS
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:CELCIUS
+     */
+    ENGINE_COOLANT_TEMP = (
+        0x0301
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Temperature of engine oil
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE|VehiclePropertyChangeMode:CONTINUOUS
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:CELCIUS
+     */
+    ENGINE_OIL_TEMP = (
+        0x0304
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Engine rpm
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE|VehiclePropertyChangeMode:CONTINUOUS
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:RPM
+     */
+    ENGINE_RPM = (
+        0x0305
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Currently selected gear
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     * @data_enum VehicleGear
+     */
+    GEAR_SELECTION = (
+        0x0400
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Current gear. In non-manual case, selected gear does not necessarily
+     * match the current gear.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     * @data_enum VehicleGear
+     */
+    CURRENT_GEAR = (
+        0x0401
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Parking brake state.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     */
+    PARKING_BRAKE_ON = (
+        0x0402
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Driving status policy.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     * @data_enum VehicleDrivingStatus
+     */
+    DRIVING_STATUS = (
+        0x0404
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Warning for fuel low level.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     */
+    FUEL_LEVEL_LOW = (
+        0x0405
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Night mode or not.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     */
+    NIGHT_MODE = (
+        0x0407
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:GLOBAL),
+
+    /*
+     * State of the vehicles turn signals
+     *
+     * Values from VehicleTurnSignal
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     */
+    TURN_SIGNAL_STATE = (
+        0x0408
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Fan speed setting
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @data_enum TODO
+     * @allow_out_of_range_value : OFF
+     */
+    HVAC_FAN_SPEED = (
+        0x0500
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:ZONE),
+
+    /*
+     * Fan direction setting
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @data_enum TODO
+     * @allow_out_of_range_value : OFF
+     */
+    HVAC_FAN_DIRECTION = (
+        0x0501
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:ZONE),
+
+    /*
+     * HVAC current temperature.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_TEMPERATURE_CURRENT = (
+        0x0502
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:ZONE),
+
+    /*
+     * HVAC, target temperature set.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @allow_out_of_range_value : MIN / MAX / OFF
+     */
+    HVAC_TEMPERATURE_SET = (
+        0x0503
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:ZONE),
+
+    /*
+     * On/off defrost
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_DEFROSTER = (
+        0x0504
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:WINDOW),
+
+    /*
+     * On/off AC
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @config_flags Supported zones
+     */
+    HVAC_AC_ON = (
+        0x0505
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:ZONE),
+
+    /*
+     * On/off max AC
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_MAX_AC_ON = (
+        0x0506
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:ZONE),
+
+    /*
+     * On/off max defrost
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_MAX_DEFROST_ON = (
+        0x0507
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:ZONE),
+
+    /*
+     * On/off re-circulation
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_RECIRC_ON = (
+        0x0508
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:ZONE),
+
+    /*
+     * On/off dual. This must be defined per each row.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_DUAL_ON = (
+        0x0509
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:ZONE),
+
+    /*
+     * On/off automatic mode
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_AUTO_ON = (
+        0x050A
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:ZONE),
+
+    /*
+     * Seat temperature
+     *
+     * Negative values indicate cooling.
+     * 0 indicates off.
+     * Positive values indicate heating.
+     *
+     * Some vehicles may have multiple levels of heating and cooling. The
+     * min/max range defines the allowable range and number of steps in each
+     * direction.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    HVAC_SEAT_TEMPERATURE = (
+        0x050B
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /**
+     * Side Mirror Heat
+     *
+     * Increase values denote higher heating levels for side mirrors.
+     * 0 indicates heating is turned off.
+     *
+     * @change_mode VEHICLE_PROP_CHANGE_MODE_ON_CHANGE
+     * @access VEHICLE_PROP_ACCESS_READ_WRITE
+     */
+    HVAC_SIDE_MIRROR_HEAT = (
+        0x050C
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:MIRROR),
+
+    /**
+     * Steering Wheel Temperature
+     *
+     * Sets the temperature for the steering wheel
+     * Positive value indicates heating.
+     * Negative value indicates cooling.
+     * 0 indicates temperature control is off.
+     *
+     * @change_mode VEHICLE_PROP_CHANGE_MODE_ON_CHANGE
+     * @access VEHICLE_PROP_ACCESS_READ_WRITE
+     */
+    HVAC_STEERING_WHEEL_TEMP = (
+        0x050D
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /**
+     * Temperature units
+     *
+     * Indicates whether the temperature is in Celsius, Fahrenheit, or a
+     * different unit from VehicleUnit enum.
+     * This parameter affects all HVAC temperatures in the system.
+     *
+     * @change_mode VEHICLE_PROP_CHANGE_MODE_ON_CHANGE
+     * @access VEHICLE_PROP_ACCESS_READ
+     */
+    HVAC_TEMPERATURE_UNITS = (
+        0x050E
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:ZONE),
+
+    /**
+     * Actual fan speed
+     *
+     * @change_mode VEHICLE_PROP_CHANGE_MODE_ON_CHANGE
+     * @access VEHICLE_PROP_ACCESS_READ
+     * @allow_out_of_range_value : OFF
+     */
+    HVAC_ACTUAL_FAN_SPEED_RPM = (
+        0x050F
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:ZONE),
+
+    /**
+     * Fan Positions Available
+     *
+     * This is a bit mask of fan positions available for the zone.  Each entry in
+     * vehicle_hvac_fan_direction is selected by bit position.  For instance, if
+     * only the FAN_DIRECTION_FACE (0x1) and FAN_DIRECTION_DEFROST (0x4) are available,
+     * then this value shall be set to 0x12.
+     *
+     * 0x12 = (1 << 1) | (1 << 4)
+     *
+     * @change_mode VEHICLE_PROP_CHANGE_MODE_STATIC
+     * @access VEHICLE_PROP_ACCESS_READ
+     * @allow_out_of_range_value : OFF
+     */
+    HVAC_FAN_DIRECTION_AVAILABLE = (
+        0x0511
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:ZONE),
+
+    /*
+     * Represents power state for HVAC. Some HVAC properties must require
+     * matching power to be turned on to get out of OFF state. For non-zoned
+     * HVAC properties, VEHICLE_ALL_ZONE corresponds to global power state.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @config_string list of HVAC properties whose power is controlled by this
+     *                property. Format is hexa-decimal number (0x...) separated
+     *                by comma like "0x500,0x503". All zones defined in these
+     *                affected properties must be available in the property.
+     */
+    HVAC_POWER_ON = (
+        0x0510
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:ZONE),
+
+    /*
+     * Outside temperature
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE|VehiclePropertyChangeMode:CONTINUOUS
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:CELCIUS
+     */
+    ENV_OUTSIDE_TEMPERATURE = (
+        0x0703
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Cabin temperature
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE|VehiclePropertyChangeMode:CONTINUOUS
+     * @access VehiclePropertyAccess:READ
+     * @unit VehicleUnit:CELCIUS
+     */
+    ENV_CABIN_TEMPERATURE = (
+        0x0704
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:FLOAT
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Radio presets stored on the Car radio module. The data type used is int32
+     * array with the following fields:
+     * <ul>
+     *    <li> int32Values[0]: Preset number </li>
+     *    <li> int32Values[1]: Band type (see #RADIO_BAND_FM in
+     *    system/core/include/system/radio.h).
+     *    <li> int32Values[2]: Channel number </li>
+     *    <li> int32Values[3]: Sub channel number </li>
+     * </ul>
+     *
+     * NOTE: When getting a current preset config ONLY set preset number (i.e.
+     * int32Values[0]). For setting a preset other fields are required.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @config_flags Number of presets supported
+     */
+    RADIO_PRESET = (
+        0x0801
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Represents audio focus state of Android side. Note that car's audio
+     * module must own audio focus and grant audio focus to Android side when
+     * requested by Android side. The focus has both per stream characteristics
+     * and global characteristics.
+     *
+     * Focus request (get of this property) must take the following form:
+     *   int32Values[0]: VehicleAudioFocusRequest type
+     *   int32Values[1]: bit flags of streams requested by this focus request.
+     *                   There can be up to 32 streams.
+     *   int32Values[2]: External focus state flags. For request, only flag like
+     *                   VehicleAudioExtFocusFlag#PLAY_ONLY_FLAG or
+     *                   VehicleAudioExtFocusFlag#MUTE_MEDIA_FLAG can be
+     *                   used.
+     *                   VehicleAudioExtFocusFlag#PLAY_ONLY_FLAG is for case
+     *                   like radio where android side app still needs to hold
+     *                   focus but playback is done outside Android.
+     *                   VehicleAudioExtFocusFlag#MUTE_MEDIA_FLAG is for
+     *                   muting media channel including radio.
+     *                   VehicleAudioExtFocusFlag#PLAY_ONLY_FLAG can be set
+     *                   even if android side releases focus (request type
+     *                   REQUEST_RELEASE). In that case, audio module must
+     *                   maintain mute state until user's explicit action to
+     *                   play some media.
+     *   int32Values[3]: Currently active audio contexts. Use combination of
+     *                   flags from VehicleAudioContextFlag.
+     *                   This can be used as a hint to adjust audio policy or
+     *                   other policy decision.
+     *                   Note that there can be multiple context active at the
+     *                   same time. And android can send the same focus request
+     *                   type gain due to change in audio contexts.
+     * Note that each focus request can request multiple streams that is
+     * expected to be used for the current request. But focus request itself
+     * is global behavior as GAIN or GAIN_TRANSIENT expects all sounds played
+     * by car's audio module to stop. Note that stream already allocated to
+     * android before this focus request must not be affected by focus
+     * request.
+     *
+     * Focus response (set and subscription callback for this property) must
+     * take the following form:
+     *   int32Values[0]: VehicleAudioFocusState type
+     *   int32Values[1]: bit flags of streams allowed.
+     *   int32Values[2]: External focus state: bit flags of currently active
+     *                   audio focus in car side (outside Android). Active
+     *                   audio focus does not necessarily mean currently
+     *                   playing, but represents the state of having focus or
+     *                   waiting for focus (pause state).
+     *                   One or combination of flags from
+     *                   VehicleAudioExtFocusFlag.
+     *                   0 means no active audio focus holder outside Android.
+     *                   The state must have following values for each
+     *                   VehicleAudioFocusState:
+     *                   GAIN: 0 or VehicleAudioExtFocusFlag#PLAY_ONLY_FLAG
+     *                       when radio is active in Android side.
+     *                   GAIN_TRANSIENT: 0. Can be
+     *                       VehicleAudioExtFocusFlag#PERMANENT_FLAG or
+     *                       VehicleAudioExtFocusFlag#TRANSIENT_FLAG if android
+     *                       side has requested
+     *                       REQUEST_GAIN_TRANSIENT_MAY_DUCK and car side is
+     *                       ducking.
+     *                   LOSS: 0 when no focus is audio is active in car side.
+     *                       VehicleAudioExtFocusFlag#PERMANENT_FLAG when car
+     *                       side is playing something permanent.
+     *                   LOSS_TRANSIENT: always must be
+     *                       VehicleAudioExtFocusFlag#PERMANENT_FLAG
+     *   int32Values[3]: context requested by android side when responding to
+     *                   focus request. When car side is taking focus away,
+     *                   this must be zero.
+     *
+     * A focus response must be sent per each focus request even if there is
+     * no change in focus state. This can happen in case like focus request
+     * only involving context change where android side still needs matching
+     * focus response to confirm that audio module has made necessary changes.
+     *
+     * If car does not support AUDIO_FOCUS, focus is assumed to be granted
+     * always.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    AUDIO_FOCUS = (
+        0x0900
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property to control audio volume of each audio context.
+     *
+     * VehiclePropConfig
+     *   configArray[0] : bit flags of all supported audio contexts from
+     *                    VehicleAudioContextFlag. If this is 0, audio volume is
+     *                    controlled per physical stream.
+     *   configArray[1] : flags defined in VehicleAudioVolumeCapabilityFlag to
+     *                    represent audio module's capability.
+     *   configArray[2..3] : reserved
+     *   configArray[4..N+3] : maximum values for each audio context, where N is
+     *                         the number of audio contexts provided in
+     *                         configArray[0], minimum value is always 0 which
+     *                         indicates mute state.
+     *
+     * Data type looks like:
+     *   int32Values[0] : stream context as defined in VehicleAudioContextFlag.
+     *                    If only physical stream is supported
+     *                    (configArray[0] == 0), this must represent physical
+     *                    stream number.
+     *   int32Values[1] : volume level, valid range is 0 (mute) to max level
+     *                    defined in the config.
+     *   int32Values[2] : One of VehicleAudioVolumeState.
+     *
+     * This property requires per stream based get. HAL implementation must
+     * check stream number in get call to return the right volume.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @config_flags all audio contexts supported.
+     */
+    AUDIO_VOLUME = (
+        0x0901
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property for handling volume limit set by user. This limits maximum
+     * volume that can be set per each context or physical stream.
+     *
+     * VehiclePropConfig
+     *   configArray[0] : bit flags of all supported audio contexts. If this is
+     *                    0, audio volume is controlled per physical stream.
+     *   configArray[1] : flags defined in VehicleAudioVolumeCapabilityFlag
+     *                    to represent audio module's capability.
+     *
+     * Data type looks like:
+     *   int32Values[0] : stream context as defined in VehicleAudioFocusFlag.
+     *                    If only physical stream is supported
+     *                    (configArray[0] == 0), this must represent physical
+     *                    stream number.
+     *   int32Values[1] : maximum volume set to the stream. If there is no
+     *                    restriction, this value must be  bigger than
+     *                    AUDIO_VOLUME's max value.
+     *
+     * If car does not support this feature, this property must not be
+     * populated by HAL.
+     * This property requires per stream based get. HAL implementation must
+     * check stream number in get call to return the right volume.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @config_flags all audio contexts supported.
+     */
+    AUDIO_VOLUME_LIMIT = (
+        0x0902
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property to share audio routing policy of android side. This property is
+     * set at the beginning to pass audio policy in android side down to
+     * vehicle HAL and car audio module.
+     * This can be used as a hint to adjust audio policy or other policy
+     * decision.
+     *
+     *   int32Values[0] : audio stream where the audio for the application
+     *                    context must be routed by default. Note that this is
+     *                    the default setting from system, but each app may
+     *                    still use different audio stream for whatever reason.
+     *   int32Values[1] : All audio contexts that must be sent through the
+     *                     physical stream. Flag is defined in
+     *                     VehicleAudioFocusFlag.
+
+     * Setting of this property must be done for all available physical streams
+     * based on audio H/W variant information acquired from AUDIO_HW_VARIANT
+     * property.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:WRITE
+     */
+    AUDIO_ROUTING_POLICY = (
+        0x0903
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property to return audio H/W variant type used in this car. This allows
+     * android side to support different audio policy based on H/W variant used.
+     * Note that other components like CarService may need overlay update to
+     * support additional variants. If this property does not
+     * exist, default audio policy must be used.
+     *
+     * @change_mode VehiclePropertyChangeMode:STATIC
+     * @access VehiclePropertyAccess:READ
+     * @config_flags Additional info on audio H/W. Must use
+     *               VehicleAudioHwVariantConfigFlag for this.
+     */
+    AUDIO_HW_VARIANT = (
+        0x0904
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property to pass hint on external audio routing. When android side
+     * request focus with VehicleAudioExtFocusflag, this
+     * property must be set before setting AUDIO_FOCUS property as a hint for
+     * external audio source routing.
+     * Note that setting this property alone must not trigger any change.
+     * Audio routing must be changed only when AUDIO_FOCUS property is set.
+     * Note that this property allows passing custom value as long as it is
+     * defined in VehiclePropConfig#configString. This allows supporting
+     * non-standard routing options through this property.
+     * It is recommended to use separate name space for custom property to
+     * prevent conflict in future android releases.
+     * Enabling each external routing option is done by enabling each bit flag
+     * for the routing.
+     * This property can support up to 128 external routings.
+     * To give full flexibility, there is no standard definition for each bit
+     * flag and assigning each big flag to specific routing type is decided by
+     * VehiclePropConfig#configString.  VehiclePropConfig#configString has
+     * format of each entry separated by ',' and each entry has format of
+     * bitFlagPositon:typeString[:physicalStreamNumber].
+     *  bitFlagPosition: represents which big flag will be set to enable this
+     *  routing. 0 means
+     *    LSB in int32Values[0]. 31 will be MSB in int32Values[0]. 127 will MSB
+     *    in int32Values[3].
+     *  typeString: string representation of external routing. Some types are
+     *    already defined in AUDIO_EXT_ROUTING_SOURCE_* and use them first
+     *    before adding something custom. Applications will find each routing
+     *    using this string.
+     *  physicalStreamNumber: This part is optional and represents physical
+     *    stream to android which will be disabled when this routing is enabled.
+     *    If not specified, this routing must not affect physical streams to
+     *    android.
+     * As an example, let's assume a system with two physical streams, 0 for
+     * media and 1 for nav guidance. And let's assume external routing option
+     * of am fm radio, external navigation guidance, satellite radio, and one
+     * custom. Let's assume that radio and satellite replaces physical stream 0
+     * and external navigation replaces physical stream 1. And bit flag will be
+     * assigned in the order listed above. This configuration will look like
+     * this in config_string:
+     *  "0:RADIO_AM_FM:0,1:EXT_NAV_GUIDANCE:1,2:RADIO_SATELLITE:0,3:com.test.SOMETHING_CUSTOM"
+     * When android requests RADIO_AM_FM, int32Values[0] will be set to 0x1.
+     * When android requests RADIO_SATELLITE + EXT_NAV_GUIDANCE, int32Values[0]
+     * will be set to 0x2|0x4.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @config_string List of all avaiable external source in the system.
+     */
+    AUDIO_EXT_ROUTING_HINT = (
+        0x0905
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Index in int32Values for AP_POWER_STATE property.
+     */
+    AP_POWER_STATE = (0x00000A00),
+
+  /*
+   * Property to represent brightness of the display. Some cars have single
+   * control for the brightness of all displays and this property is to share
+   * change in that control.
+   *
+   * If this is writable, android side can set this value when user changes
+   * display brightness from Settings. If this is read only, user may still
+   * change display brightness from Settings, but that will not be reflected
+   * to other displays.
+   *
+   * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+   * @access VehiclePropertyAccess:READ_WRITE
+   */
+    DISPLAY_BRIGHTNESS = (
+        0x0A01
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property to report bootup reason for the current power on. This is a
+     * static property that will not change for the whole duration until power
+     * off. For example, even if user presses power on button after automatic
+     * power on with door unlock, bootup reason must stay with 
+     * VehicleApPowerBootupReason#USER_UNLOCK.
+     *
+     * int32Values[0] must be VehicleApPowerBootupReason.
+     *
+     * @change_mode VehiclePropertyChangeMode:STATIC
+     * @access VehiclePropertyAccess:READ
+    */
+    AP_POWER_BOOTUP_REASON = (
+        0x0A02
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property to feed H/W input events to android
+     *
+     * int32Values[0] : action defined by VehicleHwKeyInputAction
+     * int32Values[1] : key code, must use standard android key code
+     * int32Values[2] : target display defined in VehicleDisplay. Events not
+     *                  tied to specific display must be sent to
+     *                  VehicleDisplay#MAIN.
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ
+     * @config_flags
+     */
+    HW_KEY_INPUT = (
+        0x0A10
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Property to define instrument cluster information.
+     * For VehicleInstrumentClusterType:EXTERNAL_DISPLAY:
+     *  READ:
+     *   int32Values[0] : The current screen mode index. Screen mode is defined
+     *                    as a configuration in car service and represents
+     *                    which area of screen is renderable.
+     *   int32Values[1] : Android can render to instrument cluster (=1) or
+     *                    not(=0). When this is 0, instrument cluster may be
+     *                    rendering some information in the area allocated for
+     *                    android and android side rendering is invisible.
+     *  WRITE from android:
+     *   int32Values[0] : Preferred mode for android side. Depending on the app
+     *                    rendering to instrument cluster, preferred mode can
+     *                    change. Instrument cluster still needs to send
+     *                    event with new mode to trigger actual mode change.
+     *   int32Values[1] : The current app context relevant for instrument
+     *                    cluster. Use the same flag with VehicleAudioFocusFlag
+     *                    but this context represents active apps, not
+     *                    active audio. Instrument cluster side may change mode
+     *                    depending on the currently active contexts.
+     *  When system boots up, Android side will write {0, 0, 0, 0} when it is
+     *  ready to render to instrument cluster. Before this message, rendering
+     *  from android must not be visible in the cluster.
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @configArray 0:VehicleInstrumentClusterType 1:hw type
+     */
+    INSTRUMENT_CLUSTER_INFO = (
+        0x0A20
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32_VEC
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Current date and time, encoded as Unix time.
+     * This value denotes the number of seconds that have elapsed since
+     * 1/1/1970.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_SET
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @unit VehicleUnit:SECS
+     */
+    UNIX_TIME = (
+        0x0A30
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT64
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Current time only.
+     * Some vehicles may not keep track of date.  This property only affects
+     * the current time, in seconds during the day.  Thus, the max value for
+     * this parameter is 86,400 (24 * 60 * 60)
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_SET
+     * @access VehiclePropertyAccess:READ_WRITE
+     * @unit VehicleUnit:SECS
+     */
+    CURRENT_TIME_IN_SECONDS = (
+        0x0A31
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Door position
+     *
+     * This is an integer in case a door may be set to a particular position.
+     * Max value indicates fully open, min value (0) indicates fully closed.
+     *
+     * Some vehicles (minivans) can open the door electronically.  Hence, the
+     * ability to write this property.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    DOOR_POS = (
+        0x0B00
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:DOOR),
+
+    /*
+     * Door move
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    DOOR_MOVE = (
+        0x0B01
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:DOOR),
+
+    /*
+     * Door lock
+     *
+     * 'true' indicates door is locked
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    DOOR_LOCK = (
+        0x0B02
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:DOOR),
+
+    /*
+     * Mirror Z Position
+     *
+     * Positive value indicates tilt upwards, negative value is downwards
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    MIRROR_Z_POS = (
+        0x0B40
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:MIRROR),
+
+    /*
+     * Mirror Z Move
+     *
+     * Positive value indicates tilt upwards, negative value is downwards
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    MIRROR_Z_MOVE = (
+        0x0B41
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:MIRROR),
+
+    /*
+     * Mirror Y Position
+     *
+     * Positive value indicate tilt right, negative value is left
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    MIRROR_Y_POS = (
+        0x0B42
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:MIRROR),
+
+    /*
+     * Mirror Y Move
+     *
+     * Positive value indicate tilt right, negative value is left
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    MIRROR_Y_MOVE = (
+        0x0B43
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:MIRROR),
+
+    /*
+     * Mirror Lock
+     *
+     * True indicates mirror positions are locked and not changeable
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    MIRROR_LOCK = (
+        0x0B44
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Mirror Fold
+     *
+     * True indicates mirrors are folded
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    MIRROR_FOLD = (
+        0x0B45
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Seat memory select
+     *
+     * This parameter selects the memory preset to use to select the seat
+     * position. The minValue is always 0, and the maxValue determines the
+     * number of seat positions available.
+     *
+     * For instance, if the driver's seat has 3 memory presets, the maxValue
+     * will be 3. When the user wants to select a preset, the desired preset
+     * number (1, 2, or 3) is set.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:WRITE
+     */
+    SEAT_MEMORY_SELECT = (
+        0x0B80
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat memory set
+     *
+     * This setting allows the user to save the current seat position settings
+     * into the selected preset slot.  The maxValue for each seat position
+     * shall match the maxValue for SEAT_MEMORY_SELECT.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:WRITE
+     */
+    SEAT_MEMORY_SET = (
+        0x0B81
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seatbelt buckled
+     *
+     * True indicates belt is buckled.
+     *
+     * Write access indicates automatic seat buckling capabilities.  There are
+     * no known cars at this time, but you never know...
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_BELT_BUCKLED = (
+        0x0B82
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:SEAT),
+
+    /*
+     * Seatbelt height position
+     *
+     * Adjusts the shoulder belt anchor point.
+     * Max value indicates highest position
+     * Min value indicates lowest position
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_BELT_HEIGHT_POS = (
+        0x0B83
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seatbelt height move
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_BELT_HEIGHT_MOVE = (
+        0x0B84
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat fore/aft position
+     *
+     * Sets the seat position forward (closer to steering wheel) and backwards.
+     * Max value indicates closest to wheel, min value indicates most rearward
+     * position.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_FORE_AFT_POS = (
+        0x0B85
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat fore/aft move
+     *
+     * Moves the seat position forward and aft.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_FORE_AFT_MOVE = (
+        0x0B86
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat backrest angle 1 position
+     *
+     * Backrest angle 1 is the actuator closest to the bottom of the seat.
+     * Max value indicates angling forward towards the steering wheel.
+     * Min value indicates full recline.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_BACKREST_ANGLE_1_POS = (
+        0x0B87
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat backrest angle 1 move
+     *
+     * Moves the backrest forward or recline.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_BACKREST_ANGLE_1_MOVE = (
+        0x0B88
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat backrest angle 2 position
+     *
+     * Backrest angle 2 is the next actuator up from the bottom of the seat.
+     * Max value indicates angling forward towards the steering wheel.
+     * Min value indicates full recline.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_BACKREST_ANGLE_2_POS = (
+        0x0B89
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat backrest angle 2 move
+     *
+     * Moves the backrest forward or recline.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_BACKREST_ANGLE_2_MOVE = (
+        0x0B8A
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat height position
+     *
+     * Sets the seat height.
+     * Max value indicates highest position.
+     * Min value indicates lowest position.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEIGHT_POS = (
+        0x0B8B
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat height move
+     *
+     * Moves the seat height.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEIGHT_MOVE = (
+        0x0B8C
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat depth position
+     *
+     * Sets the seat depth, distance from back rest to front edge of seat.
+     * Max value indicates longest depth position.
+     * Min value indicates shortest position.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_DEPTH_POS = (
+        0x0B8D
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat depth move
+     *
+     * Adjusts the seat depth.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_DEPTH_MOVE = (
+        0x0B8E
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat tilt position
+     *
+     * Sets the seat tilt.
+     * Max value indicates front edge of seat higher than back edge.
+     * Min value indicates front edge of seat lower than back edge.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_TILT_POS = (
+        0x0B8F
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Seat tilt move
+     *
+     * Tilts the seat.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_TILT_MOVE = (
+        0x0B90
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Lumber fore/aft position
+     *
+     * Pushes the lumbar support forward and backwards
+     * Max value indicates most forward position.
+     * Min value indicates most rearward position.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_LUMBAR_FORE_AFT_POS = (
+        0x0B91
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Lumbar fore/aft move
+     *
+     * Adjusts the lumbar support.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_LUMBAR_FORE_AFT_MOVE = (
+        0x0B92
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Lumbar side support position
+     *
+     * Sets the amount of lateral lumbar support.
+     * Max value indicates widest lumbar setting (i.e. least support)
+     * Min value indicates thinnest lumbar setting.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_LUMBAR_SIDE_SUPPORT_POS = (
+        0x0B93
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Lumbar side support move
+     *
+     * Adjusts the amount of lateral lumbar support.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_LUMBAR_SIDE_SUPPORT_MOVE = (
+        0x0B94
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Headrest height position
+     *
+     * Sets the headrest height.
+     * Max value indicates tallest setting.
+     * Min value indicates shortest setting.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEADREST_HEIGHT_POS = (
+        0x0B95
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Headrest height move
+     *
+     * Moves the headrest up and down.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEADREST_HEIGHT_MOVE = (
+        0x0B96
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Headrest angle position
+     *
+     * Sets the angle of the headrest.
+     * Max value indicates most upright angle.
+     * Min value indicates shallowest headrest angle.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEADREST_ANGLE_POS = (
+        0x0B97
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Headrest angle move
+     *
+     * Adjusts the angle of the headrest
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEADREST_ANGLE_MOVE = (
+        0x0B98
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Headrest fore/aft position
+     *
+     * Adjusts the headrest forwards and backwards.
+     * Max value indicates position closest to front of car.
+     * Min value indicates position closest to rear of car.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEADREST_FORE_AFT_POS = (
+        0x0B99
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Headrest fore/aft move
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    SEAT_HEADREST_FORE_AFT_MOVE = (
+        0x0B9A
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:SEAT),
+
+    /*
+     * Window Position
+     *
+     * Max = window up / closed
+     * Min = window down / open
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    WINDOW_POS = (
+        0x0BC0
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Window Move
+     *
+     * Max = window up / closed
+     * Min = window down / open
+     * Magnitude denotes relative speed.  I.e. +2 is faster than +1 in raising
+     * the window.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    WINDOW_MOVE = (
+        0x0BC1
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Window Vent Position
+     *
+     * This feature is used to control the vent feature on a sunroof.
+     *
+     * Max = vent open
+     * Min = vent closed
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    WINDOW_VENT_POS = (
+        0x0BC2
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Window Vent Move
+     *
+     * This feature is used to control the vent feature on a sunroof.
+     *
+     * Max = vent open
+     * Min = vent closed
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    WINDOW_VENT_MOVE = (
+        0x0BC3
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:INT32
+        | VehicleArea:GLOBAL),
+
+    /*
+     * Window Lock
+     *
+     * True indicates windows are locked and can't be moved.
+     *
+     * @change_mode VehiclePropertyChangeMode:ON_CHANGE
+     * @access VehiclePropertyAccess:READ_WRITE
+     */
+    WINDOW_LOCK = (
+        0x0BC4
+        | VehiclePropertyGroup:SYSTEM
+        | VehiclePropertyType:BOOLEAN
+        | VehicleArea:GLOBAL),
+};
+
+/*
+ * Bit flags for fan direction
+ */
+enum VehicleHvacFanDirection : int32_t {
+  FACE = 0x1,
+  FLOOR = 0x2,
+  FACE_AND_FLOOR = 0x3,
+  DEFROST = 0x4,
+  DEFROST_AND_FLOOR = 0x5,
+};
+
+/*
+ * Constants relevant to radio.
+ */
+enum VehicleRadioConstants : int32_t {
+  /* Minimum value for the radio preset */
+  VEHICLE_RADIO_PRESET_MIN_VALUE = 1,
+};
+
+enum VehicleAudioFocusRequest : int32_t {
+  REQUEST_GAIN = 0x1,
+  REQUEST_GAIN_TRANSIENT = 0x2,
+  REQUEST_GAIN_TRANSIENT_MAY_DUCK = 0x3,
+  /*
+   * This is for the case where android side plays sound like UI feedback
+   * and car side does not need to duck existing playback as long as
+   * requested stream is available.
+   */
+  REQUEST_GAIN_TRANSIENT_NO_DUCK = 0x4,
+  REQUEST_RELEASE = 0x5,
+
+};
+
+enum VehicleAudioFocusState : int32_t {
+  /*
+   * Android side has permanent focus and can play allowed streams.
+   */
+  STATE_GAIN = 0x1,
+
+  /*
+   * Android side has transient focus and can play allowed streams.
+   */
+  STATE_GAIN_TRANSIENT = 0x2,
+
+  /*
+   * Car audio module is playing guidance kind of sound outside Android.
+   * Android side can still play through allowed streams with ducking.
+   */
+  STATE_LOSS_TRANSIENT_CAN_DUCK = 0x3,
+
+  /*
+   * Car audio module is playing transient sound outside Android. Android side
+   * must stop playing any sounds.
+   */
+  STATE_LOSS_TRANSIENT = 0x4,
+
+  /*
+   * Android side has lost focus and cannot play any sound.
+   */
+  STATE_LOSS = 0x5,
+
+  /*
+   * car audio module is playing safety critical sound, and Android side cannot
+   * request focus until the current state is finished. car audio module
+   * restore it to the previous state when it can allow Android to play.
+   */
+  STATE_LOSS_TRANSIENT_EXLCUSIVE = 0x6,
+
+};
+
+/*
+ * Flags to represent multiple streams by combining these.
+ */
+enum VehicleAudioStreamFlag : int32_t {
+  STREAM0_FLAG = (0x1 << 0),
+  STREAM1_FLAG = (0x1 << 1),
+  STREAM2_FLAG = (0x1 << 2),
+};
+
+/*
+ * Represents stream number (always 0 to N -1 where N is max number of streams).
+ * Can be used for audio related property expecting one stream.
+ */
+enum VehicleAudioStream : int32_t {
+  STREAM0 = 0,
+  STREAM1 = 1,
+};
+
+/*
+ * Flag to represent external focus state (outside Android).
+ */
+enum VehicleAudioExtFocusFlag : int32_t {
+  /*
+   * No external focus holder.
+   */
+  NONE_FLAG = 0x0,
+
+  /*
+   * Car side (outside Android) has component holding GAIN kind of focus state.
+   */
+  PERMANENT_FLAG = 0x1,
+
+  /*
+   * Car side (outside Android) has component holding GAIN_TRANSIENT kind of
+   * focus state.
+   */
+  TRANSIENT_FLAG = 0x2,
+
+  /*
+   * Car side is expected to play something while focus is held by Android side.
+   * One example can be radio attached in car side. But Android's radio app
+   * still must have focus, and Android side must be in GAIN state, but
+   * media stream will not be allocated to Android side and car side can play
+   * radio any time while this flag is active.
+   */
+  PLAY_ONLY_FLAG = 0x4,
+
+  /*
+   * Car side must mute any media including radio. This can be used with any
+   * focus request including GAIN* and RELEASE.
+   */
+  MUTE_MEDIA_FLAG = 0x8,
+};
+
+/*
+ * Index in int32Values for VehicleProperty#AUDIO_FOCUS property.
+ */
+enum VehicleAudioFocusIndex : int32_t {
+  FOCUS = 0,
+  STREAMS = 1,
+  EXTERNAL_FOCUS_STATE = 2,
+  AUDIO_CONTEXTS = 3,
+};
+
+/*
+ * Flags to tell the current audio context.
+ */
+enum VehicleAudioContextFlag : int32_t {
+  /* Music playback is currently active. */
+  MUSIC_FLAG = 0x1,
+
+  /* Navigation is currently running. */
+  NAVIGATION_FLAG = 0x2,
+
+  /* Voice command session is currently running. */
+  VOICE_COMMAND_FLAG = 0x4,
+
+  /* Voice call is currently active. */
+  CALL_FLAG = 0x8,
+
+  /*
+   * Alarm is active.
+   * This must be only used in VehicleProperty#AUDIO_ROUTING_POLICY.
+   */
+  ALARM_FLAG = 0x10,
+
+  /*
+   * Notification sound is active.
+   * This must be only used in VehicleProperty#AUDIO_ROUTING_POLICY.
+   */
+  NOTIFICATION_FLAG = 0x20,
+
+  /*
+   * Context unknown. Only used for VehicleProperty#AUDIO_ROUTING_POLICY to
+   * represent default stream for unknown contents.
+   */
+  UNKNOWN_FLAG = 0x40,
+
+  /* Safety alert / warning is played. */
+  SAFETY_ALERT_FLAG = 0x80,
+
+  /* CD / DVD kind of audio is played */
+  CD_ROM_FLAG = 0x100,
+
+  /* Aux audio input is played */
+  AUX_AUDIO_FLAG = 0x200,
+
+  /* system sound like UI feedback */
+  SYSTEM_SOUND_FLAG = 0x400,
+
+  /* Radio is played */
+  RADIO_FLAG = 0x800,
+
+  /* Ext source is played. This is for tagging generic ext sources. */
+  EXT_SOURCE_FLAG = 0x1000,
+};
+
+/*
+ * flags to represent capability of audio volume property.
+ * used in configArray[1] of VehiclePropConfig.
+ */
+enum VehicleAudioVolumeCapabilityFlag : int32_t {
+  /*
+   * External audio module or vehicle hal has persistent storage
+   * to keep the volume level. This must be set only when per context
+   * volume level is supported. When this is set, audio volume level per
+   * each context will be retrieved from the property when system starts up.
+   * And external audio module is also expected to adjust volume automatically
+   * whenever there is an audio context change.
+   * When this flag is not set, android side will assume that there is no
+   * persistent storage and stored value in android side will be used to
+   * initialize the volume level. And android side will set volume level
+   * of each physical streams whenever there is an audio context change.
+   */
+  PERSISTENT_STORAGE = 0x1,
+
+  /*
+   * When this flag is set, the H/W can support only single master volume for
+   * all streams.
+   * There is no way to set volume level differently per each stream or context.
+   */
+  MASTER_VOLUME_ONLY = 0x2,
+};
+
+/*
+ * enum to represent audio volume state.
+ */
+enum VehicleAudioVolumeState : int32_t {
+  STATE_OK = 0,
+
+  /*
+   * Audio volume has reached volume limit set in
+   * VehicleProperty#AUDIO_VOLUME_LIMIT and user's request to increase volume
+   * further is not allowed.
+   */
+  LIMIT_REACHED = 1,
+};
+
+/*
+ * Index in int32Values for VehicleProperty#AUDIO_VOLUME property.
+ */
+enum VehicleAudioVolumeIndex : int32_t {
+  INDEX_STREAM = 0,
+  INDEX_VOLUME = 1,
+  INDEX_STATE = 2,
+};
+
+/*
+ * Index in int32Values for VehicleProperty#AUDIO_VOLUME_LIMIT property.
+ */
+enum VehicleAudioVolumeLimitIndex : int32_t {
+  STREAM = 0,
+  MAX_VOLUME = 1,
+};
+
+/*
+ * Index in int32Values for VehicleProperty#AUDIO_ROUTING_POLICY property.
+ */
+enum VehicleAudioRoutingPolicyIndex : int32_t {
+  STREAM = 0,
+  CONTEXTS = 1,
+};
+
+/*
+ * Flag to be used in VehiclePropConfig#configFlags for
+ * VehicleProperty#AUDIO_HW_VARIANT.
+ */
+enum VehicleAudioHwVariantConfigFlag : int32_t {
+  /*
+   * Flag to tell that radio is internal to android and radio must
+   * be treated like other android stream like media.
+   * When this flag is not set or AUDIO_HW_VARIANT does not exist,
+   * radio is treated as external module. This brins some delta in audio focus
+   * handling as well.
+   */
+  INTERNAL_RADIO_FLAG = 0x1,
+};
+
+enum VehicleApPowerStateConfigFlag : int32_t /* NOTE: type is guessed */ {
+  /*
+   * AP can enter deep sleep state. If not set, AP will always shutdown from
+   * VehicleApPowerState#SHUTDOWN_PREPARE power state.
+   */
+  ENABLE_DEEP_SLEEP_FLAG = 0x1,
+
+  /*
+   * The power controller can power on AP from off state after timeout
+   * specified in VehicleApPowerSet VEHICLE_AP_POWER_SET_SHUTDOWN_READY message.
+   */
+  CONFIG_SUPPORT_TIMER_POWER_ON_FLAG = 0x2,
+};
+
+enum VehicleApPowerState : int32_t /* NOTE: type is guessed */ {
+  /* vehicle HAL will never publish this state to AP */
+  OFF = 0,
+
+  /* vehicle HAL will never publish this state to AP */
+  DEEP_SLEEP = 1,
+
+  /* AP is on but display must be off. */
+  ON_DISP_OFF = 2,
+
+  /* AP is on with display on. This state allows full user interaction. */
+  ON_FULL = 3,
+
+  /*
+   * The power controller has requested AP to shutdown. AP can either enter
+   * sleep state or start full shutdown. AP can also request postponing
+   * shutdown by sending VehicleApPowerSetState#SHUTDOWN_POSTPONE message. The
+   * power controller must change power state to this state to shutdown
+   * system.
+   *
+   * int32Values[1] : one of enum_vehicle_ap_power_state_shutdown_param_type
+   */
+  SHUTDOWN_PREPARE = 4,
+};
+
+enum VehicleApPowerStateShutdownParam : int32_t {
+  /* AP must shutdown immediately. Postponing is not allowed. */
+  SHUTDOWN_IMMEDIATELY = 1,
+
+  /* AP can enter deep sleep instead of shutting down completely. */
+  CAN_SLEEP = 2,
+
+  /* AP can only shutdown with postponing allowed. */
+  SHUTDOWN_ONLY = 3,
+};
+
+enum VehicleApPowerSetState : int32_t /* NOTE: type is guessed */ {
+  /*
+   * AP has finished boot up, and can start shutdown if requested by power
+   * controller.
+   */
+  BOOT_COMPLETE = 0x1,
+
+  /*
+   * AP is entering deep sleep state. How this state is implemented may vary
+   * depending on each H/W, but AP's power must be kept in this state.
+   */
+  DEEP_SLEEP_ENTRY = 0x2,
+
+  /*
+   * AP is exiting from deep sleep state, and is in
+   * VehicleApPowerState#SHUTDOWN_PREPARE state.
+   * The power controller may change state to other ON states based on the
+   * current state.
+   */
+  DEEP_SLEEP_EXIT = 0x3,
+
+  /*
+   * int32Values[1]: Time to postpone shutdown in ms. Maximum value can be
+   *                 5000 ms.
+   *                 If AP needs more time, it will send another POSTPONE
+   *                 message before the previous one expires.
+   */
+  SHUTDOWN_POSTPONE = 0x4,
+
+  /*
+   * AP is starting shutting down. When system completes shutdown, everything
+   * will stop in AP as kernel will stop all other contexts. It is
+   * responsibility of vehicle HAL or lower level to synchronize that state
+   * with external power controller. As an example, some kind of ping
+   * with timeout in power controller can be a solution.
+   *
+   * int32Values[1]: Time to turn on AP in secs. Power controller may turn on
+   *                 AP after specified time so that AP can run tasks like
+   *                 update. If it is set to 0, there is no wake up, and power
+   *                 controller may not necessarily support wake-up. If power
+   *                 controller turns on AP due to timer, it must start with
+   *                 VehicleApPowerState#ON_DISP_OFF state, and after
+   *                 receiving VehicleApPowerSetState#BOOT_COMPLETE, it shall
+   *                 do state transition to
+   *                 VehicleApPowerState#SHUTDOWN_PREPARE.
+   */
+  SHUTDOWN_START = 0x5,
+
+  /*
+   * User has requested to turn off headunit's display, which is detected in
+   * android side.
+   * The power controller may change the power state to
+   * VehicleApPowerState#ON_DISP_OFF.
+   */
+  DISPLAY_OFF = 0x6,
+
+  /*
+   * User has requested to turn on headunit's display, most probably from power
+   * key input which is attached to headunit. The power controller may change
+   * the power state to VehicleApPowerState#ON_FULL.
+   */
+  DISPLAY_ON = 0x7,
+};
+
+/*
+ * Index in int32Values for VehicleProperty#AP_POWER_STATE property.
+ */
+enum VehicleApPowerStateIndex : int32_t {
+  STATE = 0,
+  ADDITIONAL = 1,
+};
+
+/*
+ * Enum to represent bootup reason.
+ */
+enum VehicleApPowerBootupReason : int32_t {
+  /*
+   * Power on due to user's pressing of power key or rotating of ignition
+   * switch.
+   */
+  USER_POWER_ON = 0,
+
+  /*
+   * Automatic power on triggered by door unlock or any other kind of automatic
+   * user detection.
+   */
+  USER_UNLOCK = 1,
+
+  /*
+   * Automatic power on triggered by timer. This only happens when AP has asked
+   * wake-up after
+   * certain time through time specified in
+   * VehicleApPowerSetState#SHUTDOWN_START.
+   */
+  TIMER = 2,
+};
+
+enum VehicleHwKeyInputAction : int32_t {
+  /* Key down */
+  ACTION_DOWN = 0,
+
+  /* Key up */
+  ACTION_UP = 1,
+};
+
+enum VehicleDisplay : int32_t {
+  /* center console */
+  MAIN = 0,
+
+  INSTRUMENT_CLUSTER = 1,
+};
+
+/*
+ * Represents instrument cluster type available in system
+ */
+enum VehicleInstrumentClusterType : int32_t {
+  /* Android has no access to instument cluster */
+  NONE = 0,
+
+  /*
+   * Instrument cluster can communicate through vehicle hal with additional
+   * properties to exchange meta-data
+   */
+  HAL_INTERFACE = 1,
+
+  /*
+   * Instrument cluster is external display where android can render contents
+   */
+  EXTERNAL_DISPLAY = 2,
+};
+
+/*
+ * Units used for int or float type with no attached enum types.
+ */
+enum VehicleUnit : int32_t {
+    SHOULD_NOT_USE = 0x000,
+
+    METER_PER_SEC  = 0x01,
+    RPM            = 0x02,
+    HZ             = 0x03,
+    PERCENTILE     = 0x10,
+    MILLIMETER     = 0x20,
+    METER          = 0x21,
+    KILOMETER      = 0x23,
+    CELSIUS        = 0x30,
+    FAHRENHEIT     = 0x31,
+    KELVIN         = 0x32,
+    MILLILITER     = 0x40,
+    NANO_SECS      = 0x50,
+    SECS           = 0x53,
+    YEAR           = 0x59,
+};
+
+  /*
+   * This describes how value of property can change.
+   */
+enum VehiclePropertyChangeMode : int32_t {
+  /*
+   * Property of this type must never be changed. Subscription is not supported
+   * for these properties.
+   */
+  STATIC = 0x00,
+
+  /*
+   * Property of this type must be reported when there is a change.
+   * IVehicle#get call must return the current value.
+   * Set operation for this property is assumed to be asynchronous. When the
+   * property is read (using IVehicle#get) after IVehicle#set, it may still
+   * return old value until underlying H/W backing this property has actually
+   * changed the state. Once state is changed, the property must dispatch
+   * changed value as event.
+   */
+  ON_CHANGE = 0x01,
+
+  /*
+   * Property of this type change continuously and requires fixed rate of
+   * sampling to retrieve the data.
+   */
+  CONTINUOUS = 0x02,
+
+  /*
+   * Property of this type may be polled to get the current value.
+   */
+  POLL = 0x03,
+
+  /*
+   * This is for property where change event must be sent only when the
+   * value is set from external component. Normal value change must not trigger
+   * event. For example, clock property can send change event only when it is
+   * set, outside android, for case like user setting time or time getting
+   * update. There is no need to send it per every value change.
+   */
+  ON_SET = 0x04,
+};
+
+/*
+ * Property config defines the capabilities of it. User of the API
+ * must first get the property config to understand the output from get()
+ * commands and also to ensure that set() or events commands are in sync with
+ * the expected output.
+ */
+enum VehiclePropertyAccess : int32_t {
+  READ = 0x01,
+  WRITE = 0x02,
+  READ_WRITE = 0x03,
+};
+
+/*
+ * These permissions define how the OEMs want to distribute their information
+ * and security they want to apply. On top of these restrictions, android will
+ * have additional 'app-level' permissions that the apps will need to ask the
+ * user before the apps have the information.
+ * This information must be kept in VehiclePropConfig#permissionModel.
+ */
+enum VehiclePermissionModel : int32_t {
+  /*
+   * No special restriction, but each property can still require specific
+   * android app-level permission.
+   */
+  NO_RESTRICTION = 0,
+
+  /* Signature only. Only APKs signed with OEM keys are allowed. */
+  OEM_ONLY = 0x1,
+
+  /* System only. APKs built-in to system  can access the property. */
+  SYSTEM_APP_ONLY = 0x2,
+
+  /* Equivalent to “system|signature” */
+  OEM_OR_SYSTEM_APP = 0x3,
+};
+
+/*
+ * Car states.
+ *
+ * The driving states determine what features of the UI will be accessible.
+ */
+enum VehicleDrivingStatus : int32_t {
+  UNRESTRICTED = 0x00,
+  NO_VIDEO = 0x01,
+  NO_KEYBOARD_INPUT = 0x02,
+  NO_VOICE_INPUT = 0x04,
+  NO_CONFIG = 0x08,
+  LIMIT_MESSAGE_LEN = 0x10,
+};
+
+/*
+ * Various gears which can be selected by user and chosen in system.
+ */
+enum VehicleGear: int32_t {
+  GEAR_NEUTRAL = 0x0001,
+  GEAR_REVERSE = 0x0002,
+  GEAR_PARK = 0x0004,
+  GEAR_DRIVE = 0x0008,
+  GEAR_LOW = 0x0010,
+  GEAR_1 = 0x0010,
+  GEAR_2 = 0x0020,
+  GEAR_3 = 0x0040,
+  GEAR_4 = 0x0080,
+  GEAR_5 = 0x0100,
+  GEAR_6 = 0x0200,
+  GEAR_7 = 0x0400,
+  GEAR_8 = 0x0800,
+  GEAR_9 = 0x1000,
+};
+
+/*
+ * Various zones in the car.
+ *
+ * Zones are used for Air Conditioning purposes and divide the car into physical
+ * area zones.
+ */
+enum VehicleAreaZone : int32_t {
+  ROW_1_LEFT = 0x00000001,
+  ROW_1_CENTER = 0x00000002,
+  ROW_1_RIGHT = 0x00000004,
+  ROW_1 = 0x00000008,
+  ROW_2_LEFT = 0x00000010,
+  ROW_2_CENTER = 0x00000020,
+  ROW_2_RIGHT = 0x00000040,
+  ROW_2 = 0x00000080,
+  ROW_3_LEFT = 0x00000100,
+  ROW_3_CENTER = 0x00000200,
+  ROW_3_RIGHT = 0x00000400,
+  ROW_3 = 0x00000800,
+  ROW_4_LEFT = 0x00001000,
+  ROW_4_CENTER = 0x00002000,
+  ROW_4_RIGHT = 0x00004000,
+  ROW_4 = 0x00008000,
+  WHOLE_CABIN = 0x80000000,
+};
+
+/*
+ * Various Seats in the car.
+ */
+enum VehicleAreaSeat : int32_t {
+    ROW_1_LEFT   = 0x0001,
+    ROW_1_CENTER = 0x0002,
+    ROW_1_RIGHT  = 0x0004,
+    ROW_2_LEFT   = 0x0010,
+    ROW_2_CENTER = 0x0020,
+    ROW_2_RIGHT  = 0x0040,
+    ROW_3_LEFT   = 0x0100,
+    ROW_3_CENTER = 0x0200,
+    ROW_3_RIGHT  = 0x0400
+};
+
+/*
+ * Various windshields/windows in the car.
+ */
+enum VehicleAreaWindow : int32_t {
+    FRONT_WINDSHIELD = 0x0001,
+    REAR_WINDSHIELD = 0x0002,
+    ROOF_TOP = 0x0004,
+    ROW_1_LEFT = 0x0010,
+    ROW_1_RIGHT = 0x0020,
+    ROW_2_LEFT = 0x0100,
+    ROW_2_RIGHT = 0x0200,
+    ROW_3_LEFT = 0x1000,
+    ROW_3_RIGHT = 0x2000,
+};
+
+enum VehicleAreaDoor : int32_t {
+    ROW_1_LEFT = 0x00000001,
+    ROW_1_RIGHT = 0x00000004,
+    ROW_2_LEFT = 0x00000010,
+    ROW_2_RIGHT = 0x00000040,
+    ROW_3_LEFT = 0x00000100,
+    ROW_3_RIGHT = 0x00000400,
+    HOOD = 0x10000000,
+    REAR = 0x20000000,
+};
+
+enum VehicleAreaMirror : int32_t {
+    DRIVER_LEFT = 0x00000001,
+    DRIVER_RIGHT = 0x00000002,
+    DRIVER_CENTER = 0x00000004,
+};
+
+enum VehicleTurnSignal : int32_t {
+    NONE = 0x00,
+    RIGHT = 0x01,
+    LEFT = 0x02,
+    EMERGENCY = 0x04,
+};
+
+struct VehicleAreaConfig {
+    /*
+     * Area id is ignored for VehiclePropertyGroup:GLOBAL properties.
+     */
+    int32_t areaId;
+
+    int32_t minInt32Value;
+    int32_t maxInt32Value;
+
+    int64_t minInt64Value;
+    int64_t maxInt64Value;
+
+    float minFloatValue;
+    float maxFloatValue;
+};
+
+struct VehiclePropConfig {
+    VehicleProperty prop;
+
+    /*
+     * Defines if the property is read or write or both.
+     */
+    VehiclePropertyAccess access;
+
+    /*
+     * Defines the change mode of the property.
+     */
+    VehiclePropertyChangeMode changeMode;
+
+    /*
+     * Defines permission model to access the data.
+     */
+    VehiclePermissionModel permissionModel;
+
+    /*
+     * Some of the properties may have associated areas (for example, some hvac
+     * properties are associated with VehicleAreaZone), in these
+     * cases the config may contain an ORed value for the associated areas.
+     */
+    int32_t supportedAreas;
+
+    /*
+     * Contains per-area configuration.
+     */
+    vec<VehicleAreaConfig> areaConfigs;
+
+    /*
+     * Configuration flags for this property.
+     *
+     * For example, it may store the number of presets that are stored by the
+     * radio module.
+     */
+    int32_t configFlags;
+
+    /* Contains additional configuration parameters */
+    vec<int32_t> configArray;
+
+    /*
+     * Some properties may require additional information passed over this
+     * string. Most properties do not need to set this.
+     */
+    string configString;
+
+    /*
+     * Min sample rate in Hz.
+     * Must be defined for VehiclePropertyChangeMode::CONTINUOUS
+     */
+    float minSampleRate;
+
+    /*
+     * Must be defined for VehiclePropertyChangeMode::CONTINUOUS
+     * Max sample rate in Hz.
+     */
+    float maxSampleRate;
+};
+
+/*
+ * Encapsulates the property name and the associated value. It
+ * is used across various API calls to set values, get values or to register for
+ * events.
+ */
+struct VehiclePropValue {
+    /* Property identifier */
+    VehicleProperty prop;
+
+    /* Time is elapsed nanoseconds since boot */
+    int64_t timestamp;
+
+    /*
+     * Area type(s) for non-global property it must be one of the value from
+     * VehicleArea* enums or 0 for global properties.
+     */
+    int32_t areaId;
+
+    /*
+     * Contains value for a single property. Depending on property data type of
+     * this property (VehiclePropetyType) one field of this structure must be filled in.
+     */
+    struct RawValue {
+        /*
+         * This is used for properties of types VehiclePropertyType#INT
+         * and VehiclePropertyType#INT_VEC
+         */
+        vec<int32_t> int32Values;
+
+        /*
+         * This is used for properties of types VehiclePropertyType#FLOAT
+         * and VehiclePropertyType#FLOAT_VEC
+         */
+        vec<float> floatValues;
+
+        /* This is used for properties of type VehiclePropertyType#INT64 */
+        vec<int64_t> int64Values;
+
+        /* This is used for properties of type VehiclePropertyType#BYTES */
+        vec<uint8_t> bytes;
+
+        /* This is used for properties of type VehiclePropertyType#STRING */
+        string stringValue;
+    };
+
+    RawValue value;
+};
+
+
+/*
+ * Represent the operation where the current error has happened.
+ */
+enum VehiclePropertyOperation : int32_t {
+    /*
+     * Generic error to this property which is not tied to any operation.
+     */
+    GENERIC = 0,
+
+    /*
+     * Error happened while handling property set.
+     */
+    SET = 1,
+
+    /*
+     * Error happened while handling property get.
+     */
+    GET = 2,
+
+    /*
+     * Error happened while handling property subscription.
+     */
+    SUBSCRIBE = 3,
+};
+
+
+enum SubscribeFlags {
+  UNDEFINED = 0x0,
+
+  /*
+   * Subscribe to event that was originated in vehicle HAL
+   * (most likely this event came from the vehicle itself).
+   */
+  HAL_EVENT = 0x1,
+
+  /*
+   * Use this flag to subscribe on events when IVehicle#set(...) was called by
+   * vehicle HAL's client (e.g. Car Service).
+   */
+  SET_CALL = 0x2,
+
+  DEFAULT = HAL_EVENT,
+};
+
+/*
+ * Encapsulates information about subscription to vehicle property events.
+ */
+struct SubscribeOptions {
+  /* Property to subscribe */
+  VehicleProperty propId;
+
+  /*
+   * Area ids - this must be a bit mask of areas to subscribe or 0 to subscribe
+   * to all areas.
+   */
+  int32_t vehicleAreas;
+
+  /*
+   * Sample rate in Hz.
+   *
+   * Must be provided for properties with
+   * VehiclePropertyChangeMode::CONTINUOUS. The value must be within
+   * VehiclePropConfig#minSamplingRate .. VehiclePropConfig#maxSamplingRate
+   * for a given property.
+   * This value indicates how many updates per second client wants to receive.
+   */
+  float sampleRate;
+
+  /* Flags that indicate what kind of events listen to. */
+  SubscribeFlags flags;
+};
+
+/* Error codes used in vehicle HAL interface. */
+enum StatusCode {
+  OK = 0,
+
+  /* Try again. */
+  TRY_AGAIN = 1,
+
+  /* Invalid argument provided. */
+  INVALID_ARG = 2,
+
+  /*
+   * This code must be returned when device that associated with the vehicle
+   * property is not available. For example, when client tries to set HVAC
+   * temperature when the whole HVAC unit is turned OFF.
+   */
+  NOT_AVAILABLE = 3,
+
+  /* Access denied */
+  ACCESS_DENIED = 4,
+
+  /* Something unexpected has happened in Vehicle HAL */
+  INTERNAL_ERROR = 5,
+};
diff --git a/vehicle/Android.bp b/vehicle/Android.bp
new file mode 100644 (file)
index 0000000..c12cd4f
--- /dev/null
@@ -0,0 +1,4 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "2.0",
+]
diff --git a/vibrator/1.0/Android.bp b/vibrator/1.0/Android.bp
new file mode 100644 (file)
index 0000000..faf4341
--- /dev/null
@@ -0,0 +1,51 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.vibrator@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.vibrator@1.0",
+    srcs: [
+        "types.hal",
+        "IVibrator.hal",
+    ],
+    out: [
+        "android/hardware/vibrator/1.0/types.cpp",
+        "android/hardware/vibrator/1.0/VibratorAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.vibrator@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.vibrator@1.0",
+    srcs: [
+        "types.hal",
+        "IVibrator.hal",
+    ],
+    out: [
+        "android/hardware/vibrator/1.0/types.h",
+        "android/hardware/vibrator/1.0/IVibrator.h",
+        "android/hardware/vibrator/1.0/IHwVibrator.h",
+        "android/hardware/vibrator/1.0/BnVibrator.h",
+        "android/hardware/vibrator/1.0/BpVibrator.h",
+        "android/hardware/vibrator/1.0/BsVibrator.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.vibrator@1.0",
+    generated_sources: ["android.hardware.vibrator@1.0_genc++"],
+    generated_headers: ["android.hardware.vibrator@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.vibrator@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/vibrator/1.0/Android.mk b/vibrator/1.0/Android.mk
new file mode 100644 (file)
index 0000000..54ac2f6
--- /dev/null
@@ -0,0 +1,102 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.vibrator@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (Status)
+#
+GEN := $(intermediates)/android/hardware/vibrator/1.0/Status.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vibrator@1.0::types.Status
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IVibrator.hal
+#
+GEN := $(intermediates)/android/hardware/vibrator/1.0/IVibrator.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVibrator.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vibrator@1.0::IVibrator
+
+$(GEN): $(LOCAL_PATH)/IVibrator.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.vibrator@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build types.hal (Status)
+#
+GEN := $(intermediates)/android/hardware/vibrator/1.0/Status.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vibrator@1.0::types.Status
+
+$(GEN): $(LOCAL_PATH)/types.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+
+#
+# Build IVibrator.hal
+#
+GEN := $(intermediates)/android/hardware/vibrator/1.0/IVibrator.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVibrator.hal
+$(GEN): PRIVATE_DEPS += $(LOCAL_PATH)/types.hal
+$(GEN): $(LOCAL_PATH)/types.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vibrator@1.0::IVibrator
+
+$(GEN): $(LOCAL_PATH)/IVibrator.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/vibrator/1.0/IVibrator.hal b/vibrator/1.0/IVibrator.hal
new file mode 100644 (file)
index 0000000..0a4ffca
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * 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 android.hardware.vibrator@1.0;
+
+interface IVibrator {
+  /** Turn on vibrator
+   *
+   * This function must only be called after the previous timeout has expired or
+   * was canceled (through off()).
+   * @param timeout_ms number of milliseconds to vibrate.
+   * @return vibratorOnRet whether vibrator command was successful or not.
+   */
+  on(uint32_t timeoutMs) generates (Status vibratorOnRet);
+
+  /** Turn off vibrator
+   *
+   * Cancel a previously-started vibration, if any.
+   * @return vibratorOffRet whether vibrator command was successful or not.
+   */
+  off() generates (Status vibratorOffRet);
+};
diff --git a/vibrator/1.0/default/Android.bp b/vibrator/1.0/default/Android.bp
new file mode 100644 (file)
index 0000000..4dd00dd
--- /dev/null
@@ -0,0 +1,27 @@
+//
+// 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.
+cc_library_shared {
+    name: "android.hardware.vibrator@1.0-impl",
+    relative_install_path: "hw",
+    srcs: ["Vibrator.cpp"],
+    shared_libs: [
+        "libhidl",
+        "liblog",
+        "libhwbinder",
+        "libutils",
+        "libhardware",
+        "android.hardware.vibrator@1.0",
+    ],
+}
diff --git a/vibrator/1.0/default/Android.mk b/vibrator/1.0/default/Android.mk
new file mode 100644 (file)
index 0000000..2b168bb
--- /dev/null
@@ -0,0 +1,34 @@
+#
+# 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.
+
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.vibrator@1.0-service
+LOCAL_INIT_RC := android.hardware.vibrator@1.0-service.rc
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+  service.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+  libhidl \
+  liblog \
+  libhwbinder \
+  libutils \
+  libhardware \
+  android.hardware.vibrator@1.0
+
+include $(BUILD_EXECUTABLE)
diff --git a/vibrator/1.0/default/Vibrator.cpp b/vibrator/1.0/default/Vibrator.cpp
new file mode 100644 (file)
index 0000000..4cd3b30
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "VibratorService"
+
+#include <hardware/hardware.h>
+#include <hardware/vibrator.h>
+#include "Vibrator.h"
+
+namespace android {
+namespace hardware {
+namespace vibrator {
+namespace V1_0 {
+namespace implementation {
+
+Vibrator::Vibrator(vibrator_device_t *device) : mDevice(device) {}
+
+// Methods from ::android::hardware::vibrator::V1_0::IVibrator follow.
+Return<Status> Vibrator::on(uint32_t timeout_ms) {
+    int32_t ret = mDevice->vibrator_on(mDevice, timeout_ms);
+    if (ret != 0) {
+        ALOGE("on command failed : %s", strerror(-ret));
+        return Status::ERR;
+    }
+    return Status::OK;
+}
+
+Return<Status> Vibrator::off()  {
+    int32_t ret = mDevice->vibrator_off(mDevice);
+    if (ret != 0) {
+        ALOGE("off command failed : %s", strerror(-ret));
+        return Status::ERR;
+    }
+    return Status::OK;
+}
+
+IVibrator* HIDL_FETCH_IVibrator(const char *hal) {
+    vibrator_device_t *vib_device;
+    const hw_module_t *hw_module = nullptr;
+
+    int ret = hw_get_module(hal, &hw_module);
+    if (ret == 0) {
+        ret = vibrator_open(hw_module, &vib_device);
+        if (ret != 0) {
+            ALOGE("vibrator_open %s failed: %d", hal, ret);
+        }
+    } else {
+        ALOGE("hw_get_module %s failed: %d", hal, ret);
+    }
+
+    if (ret == 0) {
+        return new Vibrator(vib_device);
+    } else {
+        ALOGE("Passthrough failed to open legacy HAL.");
+        return nullptr;
+    }
+}
+
+} // namespace implementation
+}  // namespace V1_0
+}  // namespace vibrator
+}  // namespace hardware
+}  // namespace android
diff --git a/vibrator/1.0/default/Vibrator.h b/vibrator/1.0/default/Vibrator.h
new file mode 100644 (file)
index 0000000..36c4cc1
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+#ifndef HIDL_GENERATED_android_hardware_vibrator_V1_0_Vibrator_H_
+#define HIDL_GENERATED_android_hardware_vibrator_V1_0_Vibrator_H_
+
+#include <android/hardware/vibrator/1.0/IVibrator.h>
+#include <hidl/Status.h>
+
+#include <hidl/MQDescriptor.h>
+namespace android {
+namespace hardware {
+namespace vibrator {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::vibrator::V1_0::IVibrator;
+using ::android::hardware::vibrator::V1_0::Status;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+
+struct Vibrator : public IVibrator {
+  Vibrator(vibrator_device_t *device);
+
+  // Methods from ::android::hardware::vibrator::V1_0::IVibrator follow.
+  Return<Status> on(uint32_t timeoutMs)  override;
+  Return<Status> off()  override;
+
+  private:
+    vibrator_device_t    *mDevice;
+};
+
+extern "C" IVibrator* HIDL_FETCH_IVibrator(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace vibrator
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_vibrator_V1_0_Vibrator_H_
diff --git a/vibrator/1.0/default/android.hardware.vibrator@1.0-service.rc b/vibrator/1.0/default/android.hardware.vibrator@1.0-service.rc
new file mode 100644 (file)
index 0000000..a7836b3
--- /dev/null
@@ -0,0 +1,4 @@
+service vibrator-1-0 /system/bin/hw/android.hardware.vibrator@1.0-service
+    class hal
+    user system
+    group system readproc
diff --git a/vibrator/1.0/default/service.cpp b/vibrator/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..064e1e2
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * 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.
+ */
+#define LOG_TAG "android.hardware.vibrator@1.0-service"
+
+#include <android/hardware/vibrator/1.0/IVibrator.h>
+#include <hidl/LegacySupport.h>
+
+using android::hardware::vibrator::V1_0::IVibrator;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IVibrator>("vibrator");
+}
diff --git a/vibrator/1.0/types.hal b/vibrator/1.0/types.hal
new file mode 100644 (file)
index 0000000..8fc5683
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * 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 android.hardware.vibrator@1.0;
+
+enum Status: uint32_t {
+    OK             = 0,
+    ERR            = 1
+};
diff --git a/vibrator/1.0/vts/Android.mk b/vibrator/1.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..bdecb85
--- /dev/null
@@ -0,0 +1,86 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for Vibrator v1.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_vibrator@1.0
+
+LOCAL_SRC_FILES := \
+  Vibrator.vts \
+  types.vts \
+
+LOCAL_C_INCLUDES := \
+  android.hardware.vibrator@1.0 \
+  system/core/base/include \
+  system/core/include \
+
+LOCAL_SHARED_LIBRARIES += \
+  android.hardware.vibrator@1.0 \
+  libbase \
+  libutils \
+  libcutils \
+  liblog \
+  libhidl \
+  libhwbinder \
+  libprotobuf-cpp-full \
+  libvts_common \
+  libvts_datatype \
+  libvts_measurement \
+  libvts_multidevice_proto \
+
+LOCAL_CFLAGS += -DENABLE_TREBLE
+
+LOCAL_STATIC_LIBRARIES := \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for vibrator.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_vibrator@1.0
+
+LOCAL_SRC_FILES := \
+   Vibrator.vts \
+   types.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.vibrator@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/vibrator/1.0/vts/Vibrator.vts b/vibrator/1.0/vts/Vibrator.vts
new file mode 100644 (file)
index 0000000..e0de3fb
--- /dev/null
@@ -0,0 +1,30 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "IVibrator"
+
+package: "android.hardware.vibrator"
+
+import: "android.hardware.vibrator@1.0::types"
+
+interface: {
+    api: {
+        name: "on"
+        return_type_hidl: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::vibrator::V1_0::Status"
+        }
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "uint32_t"
+        }
+    }
+
+    api: {
+        name: "off"
+        return_type_hidl: {
+            type: TYPE_ENUM
+            predefined_type: "::android::hardware::vibrator::V1_0::Status"
+        }
+    }
+
+}
diff --git a/vibrator/1.0/vts/functional/Android.bp b/vibrator/1.0/vts/functional/Android.bp
new file mode 100644 (file)
index 0000000..22b7536
--- /dev/null
@@ -0,0 +1,32 @@
+//
+// 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.
+//
+
+cc_test {
+    name: "vibrator_hidl_hal_test",
+    gtest: true,
+    srcs: ["vibrator_hidl_hal_test.cpp"],
+    shared_libs: [
+        "liblog",
+        "libutils",
+        "android.hardware.vibrator@1.0",
+    ],
+    static_libs: ["libgtest"],
+    cflags: [
+        "-O0",
+        "-g",
+    ],
+}
+
diff --git a/vibrator/1.0/vts/functional/vibrator_hidl_hal_test.cpp b/vibrator/1.0/vts/functional/vibrator_hidl_hal_test.cpp
new file mode 100644 (file)
index 0000000..659508d
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "vibrator_hidl_hal_test"
+
+#include <android-base/logging.h>
+#include <android/hardware/vibrator/1.0/IVibrator.h>
+#include <android/hardware/vibrator/1.0/types.h>
+#include <gtest/gtest.h>
+#include <unistd.h>
+
+using ::android::hardware::vibrator::V1_0::IVibrator;
+using ::android::hardware::vibrator::V1_0::Status;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::sp;
+
+#define VIBRATOR_SERVICE_NAME "vibrator"
+
+// The main test class for VIBRATOR HIDL HAL.
+class VibratorHidlTest : public ::testing::Test {
+ public:
+  virtual void SetUp() override {
+    vibrator = IVibrator::getService(VIBRATOR_SERVICE_NAME, false);
+    ASSERT_NE(vibrator, nullptr);
+  }
+
+  virtual void TearDown() override {}
+
+  sp<IVibrator> vibrator;
+};
+
+// A class for test environment setup (kept since this file is a template).
+class VibratorHidlEnvironment : public ::testing::Environment {
+ public:
+  virtual void SetUp() {}
+  virtual void TearDown() {}
+
+ private:
+};
+
+TEST_F(VibratorHidlTest, OnThenOffBeforeTimeout) {
+  EXPECT_EQ(Status::OK, vibrator->on(2000));
+  sleep(1);
+  EXPECT_EQ(Status::OK, vibrator->off());
+}
+
+int main(int argc, char **argv) {
+  ::testing::AddGlobalTestEnvironment(new VibratorHidlEnvironment);
+  ::testing::InitGoogleTest(&argc, argv);
+  int status = RUN_ALL_TESTS();
+  ALOGI("Test result = %d", status);
+  return status;
+}
diff --git a/vibrator/1.0/vts/types.vts b/vibrator/1.0/vts/types.vts
new file mode 100644 (file)
index 0000000..d1bf1e1
--- /dev/null
@@ -0,0 +1,24 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "types"
+
+package: "android.hardware.vibrator"
+
+
+attribute: {
+    name: "::android::hardware::vibrator::V1_0::Status"
+    type: TYPE_ENUM
+    enum_value: {
+        scalar_type: "uint32_t"
+
+        enumerator: "OK"
+        scalar_value: {
+            uint32_t: 0
+        }
+        enumerator: "ERR"
+        scalar_value: {
+            uint32_t: 1
+        }
+    }
+}
+
diff --git a/vibrator/Android.bp b/vibrator/Android.bp
new file mode 100644 (file)
index 0000000..ed19a37
--- /dev/null
@@ -0,0 +1,6 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+    "1.0/default",
+    "1.0/vts/functional",
+]
diff --git a/vr/1.0/Android.bp b/vr/1.0/Android.bp
new file mode 100644 (file)
index 0000000..fc4619f
--- /dev/null
@@ -0,0 +1,47 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+
+genrule {
+    name: "android.hardware.vr@1.0_genc++",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.vr@1.0",
+    srcs: [
+        "IVr.hal",
+    ],
+    out: [
+        "android/hardware/vr/1.0/VrAll.cpp",
+    ],
+}
+
+genrule {
+    name: "android.hardware.vr@1.0_genc++_headers",
+    tools: ["hidl-gen"],
+    cmd: "$(location hidl-gen) -o $(genDir) -Lc++ -randroid.hardware:hardware/interfaces android.hardware.vr@1.0",
+    srcs: [
+        "IVr.hal",
+    ],
+    out: [
+        "android/hardware/vr/1.0/IVr.h",
+        "android/hardware/vr/1.0/IHwVr.h",
+        "android/hardware/vr/1.0/BnVr.h",
+        "android/hardware/vr/1.0/BpVr.h",
+        "android/hardware/vr/1.0/BsVr.h",
+    ],
+}
+
+cc_library_shared {
+    name: "android.hardware.vr@1.0",
+    generated_sources: ["android.hardware.vr@1.0_genc++"],
+    generated_headers: ["android.hardware.vr@1.0_genc++_headers"],
+    export_generated_headers: ["android.hardware.vr@1.0_genc++_headers"],
+    shared_libs: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+    ],
+    export_shared_lib_headers: [
+        "libhidl",
+        "libhwbinder",
+        "libutils",
+    ],
+}
diff --git a/vr/1.0/Android.mk b/vr/1.0/Android.mk
new file mode 100644 (file)
index 0000000..b35ca3d
--- /dev/null
@@ -0,0 +1,64 @@
+# This file is autogenerated by hidl-gen. Do not edit manually.
+
+LOCAL_PATH := $(call my-dir)
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.vr@1.0-java
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build IVr.hal
+#
+GEN := $(intermediates)/android/hardware/vr/1.0/IVr.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVr.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vr@1.0::IVr
+
+$(GEN): $(LOCAL_PATH)/IVr.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_JAVA_LIBRARY)
+
+
+################################################################################
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := android.hardware.vr@1.0-java-static
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+intermediates := $(local-generated-sources-dir)
+
+HIDL := $(HOST_OUT_EXECUTABLES)/hidl-gen$(HOST_EXECUTABLE_SUFFIX)
+
+#
+# Build IVr.hal
+#
+GEN := $(intermediates)/android/hardware/vr/1.0/IVr.java
+$(GEN): $(HIDL)
+$(GEN): PRIVATE_HIDL := $(HIDL)
+$(GEN): PRIVATE_DEPS := $(LOCAL_PATH)/IVr.hal
+$(GEN): PRIVATE_OUTPUT_DIR := $(intermediates)
+$(GEN): PRIVATE_CUSTOM_TOOL = \
+        $(PRIVATE_HIDL) -o $(PRIVATE_OUTPUT_DIR) \
+        -Ljava -randroid.hardware:hardware/interfaces \
+        android.hardware.vr@1.0::IVr
+
+$(GEN): $(LOCAL_PATH)/IVr.hal
+       $(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(GEN)
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/vr/1.0/IVr.hal b/vr/1.0/IVr.hal
new file mode 100644 (file)
index 0000000..1f996e9
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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 android.hardware.vr@1.0;
+
+interface IVr {
+  /**
+   * Convenience method to set up any state needed at runtime startup.  This is
+   * called once from the VrManagerService during its boot phase.
+   */
+  @callflow(next={"*"})
+  @entry
+  @exit
+  init();
+
+  /**
+   * Set the VR mode state.  Possible states of the enabled parameter are:
+   * false - VR mode is disabled, turn off all VR-specific settings.
+   * true - VR mode is enabled, turn on all VR-specific settings.
+   *
+   * This must be called whenever the the Android system enters or leaves VR
+   * mode. This will typically occur when the user switches to or from a VR
+   * application that is doing stereoscopic rendering.
+   */
+  @callflow(next={"*"})
+  @exit
+  setVrMode(bool enabled);
+};
diff --git a/vr/1.0/default/Android.bp b/vr/1.0/default/Android.bp
new file mode 100644 (file)
index 0000000..09b0002
--- /dev/null
@@ -0,0 +1,16 @@
+cc_library_shared {
+    name: "android.hardware.vr@1.0-impl",
+    relative_install_path: "hw",
+    srcs: ["Vr.cpp"],
+    shared_libs: [
+        "liblog",
+        "libcutils",
+        "libhardware",
+        "libhwbinder",
+        "libbase",
+        "libcutils",
+        "libutils",
+        "libhidl",
+        "android.hardware.vr@1.0",
+    ],
+}
diff --git a/vr/1.0/default/Vr.cpp b/vr/1.0/default/Vr.cpp
new file mode 100644 (file)
index 0000000..4b2c603
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "VrService"
+
+#include <hardware/hardware.h>
+#include <hardware/vr.h>
+#include "Vr.h"
+
+namespace android {
+namespace hardware {
+namespace vr {
+namespace V1_0 {
+namespace implementation {
+
+Vr::Vr(vr_module_t *device) : mDevice(device) {}
+
+// Methods from ::android::hardware::vr::V1_0::IVr follow.
+Return<void> Vr::init() {
+    mDevice->init(mDevice);
+    return Void();
+}
+
+Return<void> Vr::setVrMode(bool enabled)  {
+    mDevice->set_vr_mode(mDevice, enabled);
+    return Void();
+}
+
+IVr* HIDL_FETCH_IVr(const char *name) {
+    vr_module_t *vr_module;
+    const hw_module_t *hw_module = NULL;
+
+    int ret = hw_get_module(name, &hw_module);
+    if (ret == 0) {
+        return new Vr(reinterpret_cast<vr_module_t*>(
+                const_cast<hw_module_t*>(hw_module)));
+    } else {
+        ALOGE("hw_get_module %s failed: %d", name, ret);
+        return nullptr;
+    }
+}
+
+} // namespace implementation
+}  // namespace V1_0
+}  // namespace vr
+}  // namespace hardware
+}  // namespace android
diff --git a/vr/1.0/default/Vr.h b/vr/1.0/default/Vr.h
new file mode 100644 (file)
index 0000000..90694d9
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+#ifndef HIDL_GENERATED_android_hardware_vr_V1_0_Vr_H_
+#define HIDL_GENERATED_android_hardware_vr_V1_0_Vr_H_
+
+#include <android/hardware/vr/1.0/IVr.h>
+#include <hardware/vr.h>
+#include <hidl/MQDescriptor.h>
+
+namespace android {
+namespace hardware {
+namespace vr {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::vr::V1_0::IVr;
+using ::android::hardware::Return;
+
+struct Vr : public IVr {
+    Vr(vr_module_t *device);
+
+    // Methods from ::android::hardware::vr::V1_0::IVr follow.
+    Return<void> init()  override;
+    Return<void> setVrMode(bool enabled)  override;
+
+  private:
+    vr_module_t    *mDevice;
+};
+
+extern "C" IVr* HIDL_FETCH_IVr(const char* name);
+
+}  // namespace implementation
+}  // namespace V1_0
+}  // namespace vr
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HIDL_GENERATED_android_hardware_vr_V1_0_Vr_H_
diff --git a/vr/1.0/default/android.hardware.vr@1.0-service.rc b/vr/1.0/default/android.hardware.vr@1.0-service.rc
new file mode 100644 (file)
index 0000000..6177089
--- /dev/null
@@ -0,0 +1,4 @@
+service vr-1-0 /system/bin/hw/android.hardware.vr@1.0-service
+    class hal
+    user system
+    group system readproc
diff --git a/vr/1.0/default/service.cpp b/vr/1.0/default/service.cpp
new file mode 100644 (file)
index 0000000..c27ceaf
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+#define LOG_TAG "android.hardware.vr@1.0-service"
+
+#include <android/hardware/vr/1.0/IVr.h>
+#include <hidl/LegacySupport.h>
+
+// Generated HIDL files
+using android::hardware::vr::V1_0::IVr;
+using android::hardware::defaultPassthroughServiceImplementation;
+
+int main() {
+    return defaultPassthroughServiceImplementation<IVr>("vr");
+}
diff --git a/vr/1.0/vts/Android.mk b/vr/1.0/vts/Android.mk
new file mode 100644 (file)
index 0000000..3c45652
--- /dev/null
@@ -0,0 +1,85 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# build VTS driver for Vr v1.0.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_driver_hidl_vr@1.0
+
+LOCAL_SRC_FILES := \
+  Vr.vts \
+
+LOCAL_C_INCLUDES := \
+  android.hardware.vr@1.0 \
+  system/core/base/include \
+  system/core/include \
+
+LOCAL_SHARED_LIBRARIES += \
+  android.hardware.vr@1.0 \
+  libbase \
+  libutils \
+  libcutils \
+  liblog \
+  libhidl \
+  libhwbinder \
+  libprotobuf-cpp-full \
+  libvts_common \
+  libvts_datatype \
+  libvts_measurement \
+  libvts_multidevice_proto \
+
+LOCAL_CFLAGS += -DENABLE_TREBLE
+
+LOCAL_STATIC_LIBRARIES := \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# build profiler for Vr.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvts_profiler_hidl_vr@1.0
+
+LOCAL_SRC_FILES := \
+   Vr.vts \
+
+LOCAL_C_INCLUDES += \
+  test/vts/drivers/libprofiling \
+
+LOCAL_VTS_MODE := PROFILER
+
+LOCAL_SHARED_LIBRARIES := \
+   android.hardware.vr@1.0 \
+   libbase \
+   libcutils \
+   liblog \
+   libhidl \
+   libhwbinder \
+   libprotobuf-cpp-full \
+   libvts_common \
+   libvts_multidevice_proto \
+   libvts_profiling \
+   libutils \
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := full
+
+include $(BUILD_SHARED_LIBRARY)
+
diff --git a/vr/1.0/vts/Vr.vts b/vr/1.0/vts/Vr.vts
new file mode 100644 (file)
index 0000000..36ec11f
--- /dev/null
@@ -0,0 +1,36 @@
+component_class: HAL_HIDL
+component_type_version: 1.0
+component_name: "IVr"
+
+package: "android.hardware.vr"
+
+
+interface: {
+    api: {
+        name: "init"
+        callflow: {
+            next: "*"
+        }
+        callflow: {
+            entry: true
+        }
+        callflow: {
+            exit: true
+        }
+    }
+
+    api: {
+        name: "setVrMode"
+        arg: {
+            type: TYPE_SCALAR
+            scalar_type: "bool_t"
+        }
+        callflow: {
+            next: "*"
+        }
+        callflow: {
+            exit: true
+        }
+    }
+
+}
diff --git a/vr/Android.bp b/vr/Android.bp
new file mode 100644 (file)
index 0000000..ba90f2c
--- /dev/null
@@ -0,0 +1,5 @@
+// This is an autogenerated file, do not edit.
+subdirs = [
+    "1.0",
+    "1.0/default",
+]