Merge "PlaybackThread: Request real-time priority on ARC" into main
diff --git a/Android.bp b/Android.bp
index 7a2bb9b..72b8721 100644
--- a/Android.bp
+++ b/Android.bp
@@ -105,7 +105,6 @@
aidl_interface {
name: "av-audio-types-aidl",
- unstable: true,
host_supported: true,
vendor_available: true,
double_loadable: true,
@@ -125,4 +124,12 @@
sdk_version: "module_current",
},
},
+ versions_with_info: [
+ {
+ version: "1",
+ imports: ["android.hardware.audio.core-V2"],
+ },
+ ],
+ frozen: true,
+
}
diff --git a/aidl_api/av-audio-types-aidl/1/.hash b/aidl_api/av-audio-types-aidl/1/.hash
new file mode 100644
index 0000000..0002682
--- /dev/null
+++ b/aidl_api/av-audio-types-aidl/1/.hash
@@ -0,0 +1 @@
+ef1bc5ed9db445fbfc116cdec6e6ad081458ee40
diff --git a/aidl_api/av-audio-types-aidl/1/android/media/audio/IHalAdapterVendorExtension.aidl b/aidl_api/av-audio-types-aidl/1/android/media/audio/IHalAdapterVendorExtension.aidl
new file mode 100644
index 0000000..a9aa2c1
--- /dev/null
+++ b/aidl_api/av-audio-types-aidl/1/android/media/audio/IHalAdapterVendorExtension.aidl
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.media.audio;
+/* @hide */
+interface IHalAdapterVendorExtension {
+ @utf8InCpp String[] parseVendorParameterIds(android.media.audio.IHalAdapterVendorExtension.ParameterScope scope, in @utf8InCpp String rawKeys);
+ void parseVendorParameters(android.media.audio.IHalAdapterVendorExtension.ParameterScope scope, in @utf8InCpp String rawKeysAndValues, out android.hardware.audio.core.VendorParameter[] syncParameters, out android.hardware.audio.core.VendorParameter[] asyncParameters);
+ android.hardware.audio.core.VendorParameter[] parseBluetoothA2dpReconfigureOffload(in @utf8InCpp String rawValue);
+ android.hardware.audio.core.VendorParameter[] parseBluetoothLeReconfigureOffload(in @utf8InCpp String rawValue);
+ @utf8InCpp String processVendorParameters(android.media.audio.IHalAdapterVendorExtension.ParameterScope scope, in android.hardware.audio.core.VendorParameter[] parameters);
+ enum ParameterScope {
+ MODULE = 0,
+ STREAM = 1,
+ }
+}
diff --git a/aidl_api/av-audio-types-aidl/current/android/media/audio/IHalAdapterVendorExtension.aidl b/aidl_api/av-audio-types-aidl/current/android/media/audio/IHalAdapterVendorExtension.aidl
new file mode 100644
index 0000000..a9aa2c1
--- /dev/null
+++ b/aidl_api/av-audio-types-aidl/current/android/media/audio/IHalAdapterVendorExtension.aidl
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.media.audio;
+/* @hide */
+interface IHalAdapterVendorExtension {
+ @utf8InCpp String[] parseVendorParameterIds(android.media.audio.IHalAdapterVendorExtension.ParameterScope scope, in @utf8InCpp String rawKeys);
+ void parseVendorParameters(android.media.audio.IHalAdapterVendorExtension.ParameterScope scope, in @utf8InCpp String rawKeysAndValues, out android.hardware.audio.core.VendorParameter[] syncParameters, out android.hardware.audio.core.VendorParameter[] asyncParameters);
+ android.hardware.audio.core.VendorParameter[] parseBluetoothA2dpReconfigureOffload(in @utf8InCpp String rawValue);
+ android.hardware.audio.core.VendorParameter[] parseBluetoothLeReconfigureOffload(in @utf8InCpp String rawValue);
+ @utf8InCpp String processVendorParameters(android.media.audio.IHalAdapterVendorExtension.ParameterScope scope, in android.hardware.audio.core.VendorParameter[] parameters);
+ enum ParameterScope {
+ MODULE = 0,
+ STREAM = 1,
+ }
+}
diff --git a/camera/camera_platform.aconfig b/camera/camera_platform.aconfig
index 63a514d..bfbc457 100644
--- a/camera/camera_platform.aconfig
+++ b/camera/camera_platform.aconfig
@@ -86,7 +86,21 @@
flag {
namespace: "camera_platform"
+ name: "camera_extensions_characteristics_get"
+ description: "Enable get extension specific camera characteristics API"
+ bug: "280649914"
+}
+
+flag {
+ namespace: "camera_platform"
name: "delay_lazy_hal_instantiation"
description: "Only trigger lazy HAL instantiation when the HAL is needed for an operation."
bug: "319735068"
}
+
+flag {
+ namespace: "camera_platform"
+ name: "return_buffers_outside_locks"
+ description: "Enable returning graphics buffers to buffer queues without holding the in-flight mutex"
+ bug: "315526878"
+}
diff --git a/media/aconfig/Android.bp b/media/aconfig/Android.bp
index ee25c03..e0d1fa9 100644
--- a/media/aconfig/Android.bp
+++ b/media/aconfig/Android.bp
@@ -2,6 +2,7 @@
aconfig_declarations {
name: "aconfig_mediacodec_flags",
package: "com.android.media.codec.flags",
+ container: "system",
srcs: ["mediacodec_flags.aconfig"],
}
@@ -28,6 +29,7 @@
aconfig_declarations {
name: "aconfig_codec_fwk_flags",
package: "android.media.codec",
+ container: "system",
srcs: ["codec_fwk.aconfig"],
}
diff --git a/media/aconfig/codec_fwk.aconfig b/media/aconfig/codec_fwk.aconfig
index 06aceeb..1475e15 100644
--- a/media/aconfig/codec_fwk.aconfig
+++ b/media/aconfig/codec_fwk.aconfig
@@ -3,6 +3,7 @@
# !!! Please add flags in alphabetical order. !!!
package: "android.media.codec"
+container: "system"
flag {
name: "aidl_hal_input_surface"
diff --git a/media/aconfig/mediacodec_flags.aconfig b/media/aconfig/mediacodec_flags.aconfig
index be0fc5c..4d1e5ca 100644
--- a/media/aconfig/mediacodec_flags.aconfig
+++ b/media/aconfig/mediacodec_flags.aconfig
@@ -1,4 +1,5 @@
package: "com.android.media.codec.flags"
+container: "system"
# ******************************************************************
# !!! DO NOT ADD FURTHER FLAGS TO THIS FILE !!!
diff --git a/media/audio/aconfig/audio_framework.aconfig b/media/audio/aconfig/audio_framework.aconfig
index c5663cd..a30b108 100644
--- a/media/audio/aconfig/audio_framework.aconfig
+++ b/media/audio/aconfig/audio_framework.aconfig
@@ -30,6 +30,15 @@
bug: "316414750"
}
+flag {
+ name: "foreground_audio_control"
+ namespace: "media_audio"
+ description:
+ "Audio focus gain requires FGS or delegation to "
+ "take effect"
+ bug: "296232417"
+}
+
# TODO remove
flag {
name: "focus_freeze_test_api"
@@ -51,6 +60,7 @@
Enable the API for providing loudness metadata and CTA-2075 \
support."
bug: "298463873"
+ is_exported: true
}
flag {
@@ -62,3 +72,9 @@
bug: "265057196"
}
+flag {
+ name: "supported_device_types_api"
+ namespace: "media_audio"
+ description: "Surface new API method AudioManager.getSupportedDeviceTypes()"
+ bug: "307537538"
+}
diff --git a/media/codec2/components/aac/C2SoftAacDec.cpp b/media/codec2/components/aac/C2SoftAacDec.cpp
index d1b08bd..c770d0c 100644
--- a/media/codec2/components/aac/C2SoftAacDec.cpp
+++ b/media/codec2/components/aac/C2SoftAacDec.cpp
@@ -35,14 +35,14 @@
#define FILEREAD_MAX_LAYERS 2
-#define DRC_DEFAULT_MOBILE_REF_LEVEL -16.0 /* 64*-0.25dB = -16 dB below full scale for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_CUT 1.0 /* maximum compression of dynamic range for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_BOOST 1.0 /* maximum compression of dynamic range for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_HEAVY C2Config::DRC_COMPRESSION_HEAVY /* switch for heavy compression for mobile conf */
+#define DRC_DEFAULT_MOBILE_REF_LEVEL 64 /* 64*-0.25dB = -16 dB below full scale for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_CUT 127 /* maximum compression of dynamic range for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_BOOST 127 /* maximum compression of dynamic range for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1 /* switch for heavy compression for mobile conf */
#define DRC_DEFAULT_MOBILE_DRC_EFFECT 3 /* MPEG-D DRC effect type; 3 => Limited playback range */
#define DRC_DEFAULT_MOBILE_DRC_ALBUM 0 /* MPEG-D DRC album mode; 0 => album mode is disabled, 1 => album mode is enabled */
#define DRC_DEFAULT_MOBILE_OUTPUT_LOUDNESS (0.25) /* decoder output loudness; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
-#define DRC_DEFAULT_MOBILE_ENC_LEVEL (0.25) /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
+#define DRC_DEFAULT_MOBILE_ENC_LEVEL (-1) /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
#define MAX_CHANNEL_COUNT 8 /* maximum number of audio channels that can be decoded */
// names of properties that can be used to override the default DRC settings
#define PROP_DRC_OVERRIDE_REF_LEVEL "aac_drc_reference_level"
@@ -145,9 +145,13 @@
.withSetter(ProfileLevelSetter)
.build());
+ C2Config::drc_compression_mode_t defaultCompressionMode =
+ property_get_int32(PROP_DRC_OVERRIDE_HEAVY, DRC_DEFAULT_MOBILE_DRC_HEAVY) == 1
+ ? C2Config::DRC_COMPRESSION_HEAVY
+ : C2Config::DRC_COMPRESSION_LIGHT;
addParameter(
DefineParam(mDrcCompressMode, C2_PARAMKEY_DRC_COMPRESSION_MODE)
- .withDefault(new C2StreamDrcCompressionModeTuning::input(0u, C2Config::DRC_COMPRESSION_HEAVY))
+ .withDefault(new C2StreamDrcCompressionModeTuning::input(0u, defaultCompressionMode))
.withFields({
C2F(mDrcCompressMode, value).oneOf({
C2Config::DRC_COMPRESSION_ODM_DEFAULT,
@@ -158,37 +162,48 @@
.withSetter(Setter<decltype(*mDrcCompressMode)>::StrictValueWithNoDeps)
.build());
+
+ float defaultRefLevel = -0.25 * property_get_int32(PROP_DRC_OVERRIDE_REF_LEVEL,
+ DRC_DEFAULT_MOBILE_REF_LEVEL);
addParameter(
DefineParam(mDrcTargetRefLevel, C2_PARAMKEY_DRC_TARGET_REFERENCE_LEVEL)
- .withDefault(new C2StreamDrcTargetReferenceLevelTuning::input(0u, DRC_DEFAULT_MOBILE_REF_LEVEL))
+ .withDefault(new C2StreamDrcTargetReferenceLevelTuning::input(0u, defaultRefLevel))
.withFields({C2F(mDrcTargetRefLevel, value).inRange(-31.75, 0.25)})
.withSetter(Setter<decltype(*mDrcTargetRefLevel)>::StrictValueWithNoDeps)
.build());
+ float defaultEncLevel = -0.25 * property_get_int32(PROP_DRC_OVERRIDE_ENC_LEVEL,
+ DRC_DEFAULT_MOBILE_ENC_LEVEL);
addParameter(
DefineParam(mDrcEncTargetLevel, C2_PARAMKEY_DRC_ENCODED_TARGET_LEVEL)
- .withDefault(new C2StreamDrcEncodedTargetLevelTuning::input(0u, DRC_DEFAULT_MOBILE_ENC_LEVEL))
+ .withDefault(new C2StreamDrcEncodedTargetLevelTuning::input(0u, defaultEncLevel))
.withFields({C2F(mDrcEncTargetLevel, value).inRange(-31.75, 0.25)})
.withSetter(Setter<decltype(*mDrcEncTargetLevel)>::StrictValueWithNoDeps)
.build());
+ float defaultDrcBoost =
+ property_get_int32(PROP_DRC_OVERRIDE_BOOST, DRC_DEFAULT_MOBILE_DRC_BOOST) / 127.;
addParameter(
DefineParam(mDrcBoostFactor, C2_PARAMKEY_DRC_BOOST_FACTOR)
- .withDefault(new C2StreamDrcBoostFactorTuning::input(0u, DRC_DEFAULT_MOBILE_DRC_BOOST))
+ .withDefault(new C2StreamDrcBoostFactorTuning::input(0u, defaultDrcBoost))
.withFields({C2F(mDrcBoostFactor, value).inRange(0, 1.)})
.withSetter(Setter<decltype(*mDrcBoostFactor)>::StrictValueWithNoDeps)
.build());
+ float defaultDrcCut =
+ property_get_int32(PROP_DRC_OVERRIDE_CUT, DRC_DEFAULT_MOBILE_DRC_CUT) / 127.;
addParameter(
DefineParam(mDrcAttenuationFactor, C2_PARAMKEY_DRC_ATTENUATION_FACTOR)
- .withDefault(new C2StreamDrcAttenuationFactorTuning::input(0u, DRC_DEFAULT_MOBILE_DRC_CUT))
+ .withDefault(new C2StreamDrcAttenuationFactorTuning::input(0u, defaultDrcCut))
.withFields({C2F(mDrcAttenuationFactor, value).inRange(0, 1.)})
.withSetter(Setter<decltype(*mDrcAttenuationFactor)>::StrictValueWithNoDeps)
.build());
+ C2Config::drc_effect_type_t defaultDrcEffectType = (C2Config::drc_effect_type_t)
+ property_get_int32(PROP_DRC_OVERRIDE_EFFECT, DRC_DEFAULT_MOBILE_DRC_EFFECT);
addParameter(
DefineParam(mDrcEffectType, C2_PARAMKEY_DRC_EFFECT_TYPE)
- .withDefault(new C2StreamDrcEffectTypeTuning::input(0u, C2Config::DRC_EFFECT_LIMITED_PLAYBACK_RANGE))
+ .withDefault(new C2StreamDrcEffectTypeTuning::input(0u, defaultDrcEffectType))
.withFields({
C2F(mDrcEffectType, value).oneOf({
C2Config::DRC_EFFECT_ODM_DEFAULT,
diff --git a/media/codec2/components/avc/C2SoftAvcDec.cpp b/media/codec2/components/avc/C2SoftAvcDec.cpp
index 96a4c4a..3385b95 100644
--- a/media/codec2/components/avc/C2SoftAvcDec.cpp
+++ b/media/codec2/components/avc/C2SoftAvcDec.cpp
@@ -416,6 +416,7 @@
ivdext_create_op_t s_create_op = {};
s_create_ip.s_ivd_create_ip_t.u4_size = sizeof(ivdext_create_ip_t);
+ s_create_ip.u4_keep_threads_active = 1;
s_create_ip.s_ivd_create_ip_t.e_cmd = IVD_CMD_CREATE;
s_create_ip.s_ivd_create_ip_t.u4_share_disp_buf = 0;
s_create_ip.s_ivd_create_ip_t.e_output_format = mIvColorFormat;
diff --git a/media/codec2/components/avc/C2SoftAvcEnc.cpp b/media/codec2/components/avc/C2SoftAvcEnc.cpp
index e424860..80a5e67 100644
--- a/media/codec2/components/avc/C2SoftAvcEnc.cpp
+++ b/media/codec2/components/avc/C2SoftAvcEnc.cpp
@@ -152,6 +152,17 @@
.build());
addParameter(
+ DefineParam(mBitrateMode, C2_PARAMKEY_BITRATE_MODE)
+ .withDefault(new C2StreamBitrateModeTuning::output(0u, C2Config::BITRATE_VARIABLE))
+ .withFields({C2F(mBitrateMode, value).oneOf({
+ C2Config::BITRATE_CONST,
+ C2Config::BITRATE_VARIABLE,
+ C2Config::BITRATE_IGNORE})
+ })
+ .withSetter(Setter<decltype(*mBitrateMode)>::StrictValueWithNoDeps)
+ .build());
+
+ addParameter(
DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
.withDefault(new C2StreamBitrateInfo::output(0u, 64000))
.withFields({C2F(mBitrate, value).inRange(4096, 12000000)})
@@ -536,6 +547,9 @@
std::shared_ptr<C2StreamPictureSizeInfo::input> getSize_l() const { return mSize; }
std::shared_ptr<C2StreamIntraRefreshTuning::output> getIntraRefresh_l() const { return mIntraRefresh; }
std::shared_ptr<C2StreamFrameRateInfo::output> getFrameRate_l() const { return mFrameRate; }
+ std::shared_ptr<C2StreamBitrateModeTuning::output> getBitrateMode_l() const {
+ return mBitrateMode;
+ }
std::shared_ptr<C2StreamBitrateInfo::output> getBitrate_l() const { return mBitrate; }
std::shared_ptr<C2StreamRequestSyncFrameTuning::output> getRequestSync_l() const { return mRequestSync; }
std::shared_ptr<C2StreamGopTuning::output> getGop_l() const { return mGop; }
@@ -552,6 +566,7 @@
std::shared_ptr<C2StreamRequestSyncFrameTuning::output> mRequestSync;
std::shared_ptr<C2StreamIntraRefreshTuning::output> mIntraRefresh;
std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
+ std::shared_ptr<C2StreamBitrateModeTuning::output> mBitrateMode;
std::shared_ptr<C2StreamProfileLevelInfo::output> mProfileLevel;
std::shared_ptr<C2StreamSyncFrameIntervalTuning::output> mSyncFramePeriod;
std::shared_ptr<C2StreamGopTuning::output> mGop;
@@ -1154,6 +1169,7 @@
{
IntfImpl::Lock lock = mIntf->lock();
mSize = mIntf->getSize_l();
+ mBitrateMode = mIntf->getBitrateMode_l();
mBitrate = mIntf->getBitrate_l();
mFrameRate = mIntf->getFrameRate_l();
mIntraRefresh = mIntf->getIntraRefresh_l();
@@ -1326,8 +1342,23 @@
} else {
ps_init_ip->u4_enable_recon = 0;
}
+
+ switch (mBitrateMode->value) {
+ case C2Config::BITRATE_IGNORE:
+ ps_init_ip->e_rc_mode = IVE_RC_NONE;
+ break;
+ case C2Config::BITRATE_CONST:
+ ps_init_ip->e_rc_mode = IVE_RC_CBR_NON_LOW_DELAY;
+ break;
+ case C2Config::BITRATE_VARIABLE:
+ ps_init_ip->e_rc_mode = IVE_RC_STORAGE;
+ break;
+ default:
+ ps_init_ip->e_rc_mode = DEFAULT_RC_MODE;
+ break;
+ break;
+ }
ps_init_ip->e_recon_color_fmt = DEFAULT_RECON_COLOR_FORMAT;
- ps_init_ip->e_rc_mode = DEFAULT_RC_MODE;
ps_init_ip->u4_max_framerate = DEFAULT_MAX_FRAMERATE;
ps_init_ip->u4_max_bitrate = DEFAULT_MAX_BITRATE;
ps_init_ip->u4_num_bframes = mBframes;
diff --git a/media/codec2/components/avc/C2SoftAvcEnc.h b/media/codec2/components/avc/C2SoftAvcEnc.h
index cde6604..33d166f 100644
--- a/media/codec2/components/avc/C2SoftAvcEnc.h
+++ b/media/codec2/components/avc/C2SoftAvcEnc.h
@@ -191,6 +191,7 @@
std::shared_ptr<C2StreamIntraRefreshTuning::output> mIntraRefresh;
std::shared_ptr<C2StreamFrameRateInfo::output> mFrameRate;
std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
+ std::shared_ptr<C2StreamBitrateModeTuning::output> mBitrateMode;
std::shared_ptr<C2StreamRequestSyncFrameTuning::output> mRequestSync;
std::shared_ptr<C2StreamColorAspectsInfo::output> mColorAspects;
diff --git a/media/codec2/components/hevc/C2SoftHevcDec.cpp b/media/codec2/components/hevc/C2SoftHevcDec.cpp
index 15d6dcd..81db2a1 100644
--- a/media/codec2/components/hevc/C2SoftHevcDec.cpp
+++ b/media/codec2/components/hevc/C2SoftHevcDec.cpp
@@ -407,6 +407,7 @@
ivdext_create_op_t s_create_op = {};
s_create_ip.s_ivd_create_ip_t.u4_size = sizeof(ivdext_create_ip_t);
+ s_create_ip.u4_keep_threads_active = 1;
s_create_ip.s_ivd_create_ip_t.e_cmd = IVD_CMD_CREATE;
s_create_ip.s_ivd_create_ip_t.u4_share_disp_buf = 0;
s_create_ip.s_ivd_create_ip_t.e_output_format = mIvColorformat;
diff --git a/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp b/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
index 439323c..491098d 100644
--- a/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
+++ b/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
@@ -433,6 +433,7 @@
s_fill_mem_ip.s_ivd_fill_mem_rec_ip_t.u4_size = sizeof(ivdext_fill_mem_rec_ip_t);
s_fill_mem_ip.u4_share_disp_buf = 0;
+ s_fill_mem_ip.u4_keep_threads_active = 1;
s_fill_mem_ip.e_output_format = mIvColorformat;
s_fill_mem_ip.u4_deinterlace = 1;
s_fill_mem_ip.s_ivd_fill_mem_rec_ip_t.e_cmd = IV_CMD_FILL_NUM_MEM_REC;
@@ -474,6 +475,7 @@
s_init_ip.s_ivd_init_ip_t.u4_frm_max_ht = mHeight;
s_init_ip.u4_share_disp_buf = 0;
s_init_ip.u4_deinterlace = 1;
+ s_init_ip.u4_keep_threads_active = 1;
s_init_ip.s_ivd_init_ip_t.u4_num_mem_rec = mNumMemRecords;
s_init_ip.s_ivd_init_ip_t.e_output_format = mIvColorformat;
s_init_op.s_ivd_init_op_t.u4_size = sizeof(ivdext_init_op_t);
diff --git a/media/codec2/components/vpx/C2SoftVpxEnc.cpp b/media/codec2/components/vpx/C2SoftVpxEnc.cpp
index 76e74ec..0384e2e 100644
--- a/media/codec2/components/vpx/C2SoftVpxEnc.cpp
+++ b/media/codec2/components/vpx/C2SoftVpxEnc.cpp
@@ -29,6 +29,12 @@
#define INT32_MAX 2147483647
#endif
+/* Quantization param values defined by the spec */
+#define VPX_QP_MIN 0
+#define VPX_QP_MAX 63
+#define VPX_QP_DEFAULT_MIN VPX_QP_MIN
+#define VPX_QP_DEFAULT_MAX VPX_QP_MAX
+
namespace android {
C2SoftVpxEnc::IntfImpl::IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
@@ -197,6 +203,20 @@
})
.withSetter(CodedColorAspectsSetter, mColorAspects)
.build());
+
+ addParameter(
+ DefineParam(mPictureQuantization, C2_PARAMKEY_PICTURE_QUANTIZATION)
+ .withDefault(C2StreamPictureQuantizationTuning::output::AllocShared(
+ 0 /* flexCount */, 0u /* stream */))
+ .withFields({C2F(mPictureQuantization, m.values[0].type_).oneOf(
+ {C2Config::I_FRAME, C2Config::P_FRAME}),
+ C2F(mPictureQuantization, m.values[0].min).inRange(
+ VPX_QP_DEFAULT_MIN, VPX_QP_DEFAULT_MAX),
+ C2F(mPictureQuantization, m.values[0].max).inRange(
+ VPX_QP_DEFAULT_MIN, VPX_QP_DEFAULT_MAX)})
+ .withSetter(PictureQuantizationSetter)
+ .build());
+
}
C2R C2SoftVpxEnc::IntfImpl::BitrateSetter(bool mayBlock, C2P<C2StreamBitrateInfo::output> &me) {
@@ -330,6 +350,58 @@
double period = mSyncFramePeriod->value / 1e6 * mFrameRate->value;
return (uint32_t)c2_max(c2_min(period + 0.5, double(UINT32_MAX)), 1.);
}
+
+C2R C2SoftVpxEnc::IntfImpl::PictureQuantizationSetter(bool mayBlock,
+ C2P<C2StreamPictureQuantizationTuning::output>
+ &me) {
+ (void)mayBlock;
+ // these are the ones we're going to set, so want them to default
+ // to the DEFAULT values for the codec
+ int32_t iMin = VPX_QP_DEFAULT_MIN, pMin = VPX_QP_DEFAULT_MIN;
+ int32_t iMax = VPX_QP_DEFAULT_MAX, pMax = VPX_QP_DEFAULT_MAX;
+ for (size_t i = 0; i < me.v.flexCount(); ++i) {
+ const C2PictureQuantizationStruct &layer = me.v.m.values[i];
+ // layerMin is clamped to [VPX_QP_MIN, layerMax] to avoid error
+ // cases where layer.min > layer.max
+ int32_t layerMax = std::clamp(layer.max, VPX_QP_MIN, VPX_QP_MAX);
+ int32_t layerMin = std::clamp(layer.min, VPX_QP_MIN, layerMax);
+ if (layer.type_ == C2Config::picture_type_t(I_FRAME)) {
+ iMax = layerMax;
+ iMin = layerMin;
+ ALOGV("iMin %d iMax %d", iMin, iMax);
+ } else if (layer.type_ == C2Config::picture_type_t(P_FRAME)) {
+ pMax = layerMax;
+ pMin = layerMin;
+ ALOGV("pMin %d pMax %d", pMin, pMax);
+ }
+ }
+ ALOGV("PictureQuantizationSetter(entry): i %d-%d p %d-%d",
+ iMin, iMax, pMin, pMax);
+
+ // vpx library takes same range for I/P picture type
+ int32_t maxFrameQP = std::min({iMax, pMax});
+ int32_t minFrameQP = std::max({iMin, pMin});
+ if (minFrameQP > maxFrameQP) {
+ minFrameQP = maxFrameQP;
+ }
+ // put them back into the structure
+ for (size_t i = 0; i < me.v.flexCount(); ++i) {
+ const C2PictureQuantizationStruct &layer = me.v.m.values[i];
+
+ if (layer.type_ == C2Config::picture_type_t(I_FRAME)) {
+ me.set().m.values[i].max = maxFrameQP;
+ me.set().m.values[i].min = minFrameQP;
+ }
+ else if (layer.type_ == C2Config::picture_type_t(P_FRAME)) {
+ me.set().m.values[i].max = maxFrameQP;
+ me.set().m.values[i].min = minFrameQP;
+ }
+ }
+ ALOGV("PictureQuantizationSetter(exit): minFrameQP = %d maxFrameQP = %d",
+ minFrameQP, maxFrameQP);
+ return C2R::Ok();
+}
+
C2R C2SoftVpxEnc::IntfImpl::ColorAspectsSetter(bool mayBlock,
C2P<C2StreamColorAspectsInfo::input>& me) {
(void)mayBlock;
@@ -453,6 +525,7 @@
mRequestSync = mIntf->getRequestSync_l();
mLayering = mIntf->getTemporalLayers_l();
mTemporalLayers = mLayering->m.layerCount;
+ mQpBounds = mIntf->getPictureQuantization_l();
}
switch (mBitrateMode->value) {
@@ -466,6 +539,18 @@
break;
}
+ if (mQpBounds->flexCount() > 0) {
+ // read min max qp for sequence
+ for (size_t i = 0; i < mQpBounds->flexCount(); ++i) {
+ const C2PictureQuantizationStruct &layer = mQpBounds->m.values[i];
+ if (layer.type_ == C2Config::picture_type_t(I_FRAME)) {
+ mMaxQuantizer = layer.max;
+ mMinQuantizer = layer.min;
+ break;
+ }
+ }
+ }
+
setCodecSpecificInterface();
if (!mCodecInterface) goto CleanUp;
diff --git a/media/codec2/components/vpx/C2SoftVpxEnc.h b/media/codec2/components/vpx/C2SoftVpxEnc.h
index bfb4444..980de04 100644
--- a/media/codec2/components/vpx/C2SoftVpxEnc.h
+++ b/media/codec2/components/vpx/C2SoftVpxEnc.h
@@ -219,6 +219,7 @@
std::shared_ptr<C2StreamBitrateModeTuning::output> mBitrateMode;
std::shared_ptr<C2StreamRequestSyncFrameTuning::output> mRequestSync;
std::shared_ptr<C2StreamTemporalLayeringTuning::output> mLayering;
+ std::shared_ptr<C2StreamPictureQuantizationTuning::output> mQpBounds;
C2_DO_NOT_COPY(C2SoftVpxEnc);
};
@@ -250,6 +251,9 @@
static C2R LayeringSetter(bool mayBlock, C2P<C2StreamTemporalLayeringTuning::output>& me);
+ static C2R PictureQuantizationSetter(bool mayBlock,
+ C2P<C2StreamPictureQuantizationTuning::output> &me);
+
// unsafe getters
std::shared_ptr<C2StreamPictureSizeInfo::input> getSize_l() const { return mSize; }
std::shared_ptr<C2StreamIntraRefreshTuning::output> getIntraRefresh_l() const {
@@ -269,6 +273,9 @@
std::shared_ptr<C2StreamColorAspectsInfo::output> getCodedColorAspects_l() const {
return mCodedColorAspects;
}
+ std::shared_ptr<C2StreamPictureQuantizationTuning::output> getPictureQuantization_l() const {
+ return mPictureQuantization;
+ }
uint32_t getSyncFramePeriod() const;
static C2R ColorAspectsSetter(bool mayBlock, C2P<C2StreamColorAspectsInfo::input> &me);
static C2R CodedColorAspectsSetter(bool mayBlock, C2P<C2StreamColorAspectsInfo::output> &me,
@@ -287,6 +294,7 @@
std::shared_ptr<C2StreamProfileLevelInfo::output> mProfileLevel;
std::shared_ptr<C2StreamColorAspectsInfo::input> mColorAspects;
std::shared_ptr<C2StreamColorAspectsInfo::output> mCodedColorAspects;
+ std::shared_ptr<C2StreamPictureQuantizationTuning::output> mPictureQuantization;
};
} // namespace android
diff --git a/media/codec2/hal/aidl/Component.cpp b/media/codec2/hal/aidl/Component.cpp
index 8da9861..ba5f8d4 100644
--- a/media/codec2/hal/aidl/Component.cpp
+++ b/media/codec2/hal/aidl/Component.cpp
@@ -46,6 +46,8 @@
using ::aidl::android::hardware::common::NativeHandle;
using ::aidl::android::hardware::media::bufferpool2::IClientManager;
using ::ndk::ScopedAStatus;
+using ::android::MultiAccessUnitInterface;
+using ::android::MultiAccessUnitHelper;
// ComponentListener wrapper
struct Component::Listener : public C2Component::Listener {
@@ -139,6 +141,52 @@
std::weak_ptr<IComponentListener> mListener;
};
+// Component listener for handle multiple access-units
+struct MultiAccessUnitListener : public Component::Listener {
+ MultiAccessUnitListener(const std::shared_ptr<Component>& component,
+ const std::shared_ptr<MultiAccessUnitHelper> &helper):
+ Listener(component), mHelper(helper) {
+ }
+
+ virtual void onError_nb(
+ std::weak_ptr<C2Component> c2component,
+ uint32_t errorCode) override {
+ if (mHelper) {
+ std::list<std::unique_ptr<C2Work>> worklist;
+ mHelper->error(&worklist);
+ if (!worklist.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(worklist));
+ }
+ }
+ Listener::onError_nb(c2component, errorCode);
+ }
+
+ virtual void onTripped_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::vector<std::shared_ptr<C2SettingResult>> c2settingResult
+ ) override {
+ Listener::onTripped_nb(c2component,
+ c2settingResult);
+ }
+
+ virtual void onWorkDone_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::list<std::unique_ptr<C2Work>> c2workItems) override {
+ if (mHelper) {
+ std::list<std::unique_ptr<C2Work>> processedWork;
+ mHelper->gather(c2workItems, &processedWork);
+ if (!processedWork.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(processedWork));
+ }
+ } else {
+ Listener::onWorkDone_nb(c2component, std::move(c2workItems));
+ }
+ }
+
+ protected:
+ std::shared_ptr<MultiAccessUnitHelper> mHelper;
+};
+
// Component::DeathContext
struct Component::DeathContext {
std::weak_ptr<Component> mWeakComp;
@@ -151,14 +199,38 @@
const std::shared_ptr<ComponentStore>& store,
const std::shared_ptr<IClientManager>& clientPoolManager)
: mComponent{component},
- mInterface{SharedRefBase::make<ComponentInterface>(
- component->intf(), store->getParameterCache())},
mListener{listener},
mStore{store},
mBufferPoolSender{clientPoolManager},
mDeathContext(nullptr) {
// Retrieve supported parameters from store
// TODO: We could cache this per component/interface type
+ if (MultiAccessUnitHelper::isEnabledOnPlatform()) {
+ c2_status_t err = C2_OK;
+ C2ComponentDomainSetting domain;
+ std::vector<std::unique_ptr<C2Param>> heapParams;
+ err = component->intf()->query_vb({&domain}, {}, C2_MAY_BLOCK, &heapParams);
+ if (err == C2_OK && (domain.value == C2Component::DOMAIN_AUDIO)) {
+ std::vector<std::shared_ptr<C2ParamDescriptor>> params;
+ bool isComponentSupportsLargeAudioFrame = false;
+ component->intf()->querySupportedParams_nb(¶ms);
+ for (const auto ¶mDesc : params) {
+ if (paramDesc->name().compare(C2_PARAMKEY_OUTPUT_LARGE_FRAME) == 0) {
+ isComponentSupportsLargeAudioFrame = true;
+ LOG(VERBOSE) << "Underlying component supports large frame audio";
+ break;
+ }
+ }
+ if (!isComponentSupportsLargeAudioFrame) {
+ mMultiAccessUnitIntf = std::make_shared<MultiAccessUnitInterface>(
+ component->intf(),
+ std::static_pointer_cast<C2ReflectorHelper>(
+ ::android::GetCodec2PlatformComponentStore()->getParamReflector()));
+ }
+ }
+ }
+ mInterface = SharedRefBase::make<ComponentInterface>(
+ component->intf(), mMultiAccessUnitIntf, store->getParameterCache());
mInit = mInterface->status();
}
@@ -181,8 +253,21 @@
registerFrameData(mListener, work->input);
}
}
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitHelper) {
+ std::list<std::list<std::unique_ptr<C2Work>>> c2worklists;
+ mMultiAccessUnitHelper->scatter(c2works, &c2worklists);
+ for (auto &c2worklist : c2worklists) {
+ err = mComponent->queue_nb(&c2worklist);
+ if (err != C2_OK) {
+ LOG(ERROR) << "Error Queuing to component.";
+ return ScopedAStatus::fromServiceSpecificError(err);
+ }
+ }
+ return ScopedAStatus::ok();
+ }
- c2_status_t err = mComponent->queue_nb(&c2works);
+ err = mComponent->queue_nb(&c2works);
if (err == C2_OK) {
return ScopedAStatus::ok();
}
@@ -194,7 +279,9 @@
c2_status_t c2res = mComponent->flush_sm(
C2Component::FLUSH_COMPONENT,
&c2flushedWorks);
-
+ if (mMultiAccessUnitHelper) {
+ c2res = mMultiAccessUnitHelper->flush(&c2flushedWorks);
+ }
// Unregister input buffers.
for (const std::unique_ptr<C2Work>& work : c2flushedWorks) {
if (work) {
@@ -364,6 +451,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
if (status == C2_OK) {
return ScopedAStatus::ok();
@@ -377,6 +467,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
if (status == C2_OK) {
return ScopedAStatus::ok();
@@ -415,7 +508,12 @@
void Component::initListener(const std::shared_ptr<Component>& self) {
if (__builtin_available(android __ANDROID_API_T__, *)) {
- std::shared_ptr<C2Component::Listener> c2listener =
+ std::shared_ptr<C2Component::Listener> c2listener;
+ if (mMultiAccessUnitIntf) {
+ mMultiAccessUnitHelper = std::make_shared<MultiAccessUnitHelper>(mMultiAccessUnitIntf);
+ }
+ c2listener = mMultiAccessUnitHelper ?
+ std::make_shared<MultiAccessUnitListener>(self, mMultiAccessUnitHelper) :
std::make_shared<Listener>(self);
c2_status_t res = mComponent->setListener_vb(c2listener, C2_DONT_BLOCK);
if (res != C2_OK) {
diff --git a/media/codec2/hal/aidl/ComponentInterface.cpp b/media/codec2/hal/aidl/ComponentInterface.cpp
index 2d812c9..1f0534d 100644
--- a/media/codec2/hal/aidl/ComponentInterface.cpp
+++ b/media/codec2/hal/aidl/ComponentInterface.cpp
@@ -24,6 +24,8 @@
#include <utils/Timers.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2Debug.h>
#include <C2PlatformSupport.h>
@@ -43,9 +45,10 @@
// Implementation of ConfigurableC2Intf based on C2ComponentInterface
struct CompIntf : public ConfigurableC2Intf {
- CompIntf(const std::shared_ptr<C2ComponentInterface>& intf) :
+ CompIntf(const std::shared_ptr<C2ComponentInterface>& intf,
+ const std::shared_ptr<MultiAccessUnitInterface>& multiAccessUnitIntf):
ConfigurableC2Intf{intf->getName(), intf->getId()},
- mIntf{intf} {
+ mIntf{intf}, mMultiAccessUnitIntf{multiAccessUnitIntf} {
}
virtual c2_status_t config(
@@ -53,7 +56,34 @@
c2_blocking_t mayBlock,
std::vector<std::unique_ptr<C2SettingResult>>* const failures
) override {
- return mIntf->config_vb(params, mayBlock, failures);
+ std::vector<C2Param*> paramsToIntf;
+ std::vector<C2Param*> paramsToLargeFrameIntf;
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitIntf == nullptr) {
+ err = mIntf->config_vb(params, mayBlock, failures);
+ return err;
+ }
+ for (auto &p : params) {
+ if (mMultiAccessUnitIntf->isParamSupported(p->index())) {
+ paramsToLargeFrameIntf.push_back(p);
+ } else {
+ paramsToIntf.push_back(p);
+ }
+ }
+ c2_status_t err1 = C2_OK;
+ if (paramsToIntf.size() > 0) {
+ err1 = mIntf->config_vb(paramsToIntf, mayBlock, failures);
+ }
+ if (err1 != C2_OK) {
+ LOG(ERROR) << "We have a failed config";
+ }
+ c2_status_t err2 = C2_OK;
+ if (paramsToLargeFrameIntf.size() > 0) {
+ err2 = mMultiAccessUnitIntf->config(
+ paramsToLargeFrameIntf, mayBlock, failures);
+ }
+ // TODO: correct failure vector
+ return err1 != C2_OK ? err1 : err2;
}
virtual c2_status_t query(
@@ -61,23 +91,56 @@
c2_blocking_t mayBlock,
std::vector<std::unique_ptr<C2Param>>* const params
) const override {
- return mIntf->query_vb({}, indices, mayBlock, params);
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitIntf == nullptr) {
+ err = mIntf->query_vb({}, indices, mayBlock, params);
+ return err;
+ }
+ std::vector<C2Param::Index> paramsToIntf;
+ std::vector<C2Param::Index> paramsToLargeFrameIntf;
+ for (auto &i : indices) {
+ if (mMultiAccessUnitIntf->isParamSupported(i)) {
+ paramsToLargeFrameIntf.push_back(i);
+ } else {
+ paramsToIntf.push_back(i);
+ }
+ }
+ c2_status_t err1 = C2_OK;
+ if (paramsToIntf.size() > 0) {
+ err1 = mIntf->query_vb({}, paramsToIntf, mayBlock, params);
+ }
+ c2_status_t err2 = C2_OK;
+ if (paramsToLargeFrameIntf.size() > 0) {
+ err2 = mMultiAccessUnitIntf->query(
+ {}, paramsToLargeFrameIntf, mayBlock, params);
+ }
+ // TODO: correct failure vector
+ return err1 != C2_OK ? err1 : err2;
}
virtual c2_status_t querySupportedParams(
std::vector<std::shared_ptr<C2ParamDescriptor>>* const params
) const override {
- return mIntf->querySupportedParams_nb(params);
+ c2_status_t err = mIntf->querySupportedParams_nb(params);
+ if (mMultiAccessUnitIntf != nullptr) {
+ err = mMultiAccessUnitIntf->querySupportedParams(params);
+ }
+ return err;
}
virtual c2_status_t querySupportedValues(
std::vector<C2FieldSupportedValuesQuery>& fields,
c2_blocking_t mayBlock) const override {
- return mIntf->querySupportedValues_vb(fields, mayBlock);
+ c2_status_t err = mIntf->querySupportedValues_vb(fields, mayBlock);
+ if (mMultiAccessUnitIntf != nullptr) {
+ err = mMultiAccessUnitIntf->querySupportedValues(fields, mayBlock);
+ }
+ return err;
}
protected:
std::shared_ptr<C2ComponentInterface> mIntf;
+ std::shared_ptr<MultiAccessUnitInterface> mMultiAccessUnitIntf;
};
} // unnamed namespace
@@ -85,10 +148,16 @@
// ComponentInterface
ComponentInterface::ComponentInterface(
const std::shared_ptr<C2ComponentInterface>& intf,
+ const std::shared_ptr<ParameterCache>& cache):ComponentInterface(intf, nullptr, cache) {
+}
+
+ComponentInterface::ComponentInterface(
+ const std::shared_ptr<C2ComponentInterface>& intf,
+ const std::shared_ptr<MultiAccessUnitInterface>& multiAccessUnitIntf,
const std::shared_ptr<ParameterCache>& cache)
: mInterface{intf},
mConfigurable{SharedRefBase::make<CachedConfigurable>(
- std::make_unique<CompIntf>(intf))} {
+ std::make_unique<CompIntf>(intf, multiAccessUnitIntf))} {
mInit = mConfigurable->init(cache);
}
diff --git a/media/codec2/hal/aidl/ComponentStore.cpp b/media/codec2/hal/aidl/ComponentStore.cpp
index 3f687b5..ef49308 100644
--- a/media/codec2/hal/aidl/ComponentStore.cpp
+++ b/media/codec2/hal/aidl/ComponentStore.cpp
@@ -206,12 +206,19 @@
const std::shared_ptr<IClientManager>& pool,
std::shared_ptr<IComponent> *component) {
+ if (!listener) {
+ ALOGE("createComponent(): listener is null");
+ return ScopedAStatus::fromServiceSpecificError(Status::BAD_VALUE);
+ }
+ if (!pool) {
+ ALOGE("createComponent(): pool is null");
+ return ScopedAStatus::fromServiceSpecificError(Status::BAD_VALUE);
+ }
+
std::shared_ptr<C2Component> c2component;
c2_status_t status =
mStore->createComponent(name, &c2component);
- ALOGD("createComponent(): listener(%d)", bool(listener));
-
if (status == C2_OK) {
#ifndef __ANDROID_APEX__
c2component = GetFilterWrapper()->maybeWrapComponent(c2component);
diff --git a/media/codec2/hal/aidl/include/codec2/aidl/Component.h b/media/codec2/hal/aidl/include/codec2/aidl/Component.h
index 94b760f..9725bcf 100644
--- a/media/codec2/hal/aidl/include/codec2/aidl/Component.h
+++ b/media/codec2/hal/aidl/include/codec2/aidl/Component.h
@@ -31,6 +31,8 @@
#include <aidl/android/hardware/media/c2/IInputSurface.h>
#include <aidl/android/hardware/media/c2/IInputSurfaceConnection.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2Component.h>
#include <C2Buffer.h>
#include <C2.h>
@@ -46,6 +48,8 @@
namespace c2 {
namespace utils {
+using ::android::MultiAccessUnitInterface;
+using ::android::MultiAccessUnitHelper;
struct ComponentStore;
@@ -85,6 +89,8 @@
std::shared_ptr<C2Component> mComponent;
std::shared_ptr<ComponentInterface> mInterface;
std::shared_ptr<IComponentListener> mListener;
+ std::shared_ptr<MultiAccessUnitInterface> mMultiAccessUnitIntf;
+ std::shared_ptr<MultiAccessUnitHelper> mMultiAccessUnitHelper;
std::shared_ptr<ComponentStore> mStore;
DefaultBufferPoolSender mBufferPoolSender;
@@ -102,6 +108,8 @@
struct Listener;
+ friend struct MultiAccessUnitListener;
+
::ndk::ScopedAIBinder_DeathRecipient mDeathRecipient;
static void OnBinderDied(void *cookie);
static void OnBinderUnlinked(void *cookie);
diff --git a/media/codec2/hal/aidl/include/codec2/aidl/ComponentInterface.h b/media/codec2/hal/aidl/include/codec2/aidl/ComponentInterface.h
index 7723bee..bd19cd6 100644
--- a/media/codec2/hal/aidl/include/codec2/aidl/ComponentInterface.h
+++ b/media/codec2/hal/aidl/include/codec2/aidl/ComponentInterface.h
@@ -22,11 +22,14 @@
#include <aidl/android/hardware/media/c2/BnComponentInterface.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2Component.h>
#include <C2Buffer.h>
#include <C2.h>
#include <memory>
+#include <set>
namespace aidl {
namespace android {
@@ -35,12 +38,16 @@
namespace c2 {
namespace utils {
-struct ComponentStore;
+using ::android::MultiAccessUnitInterface;
struct ComponentInterface : public BnComponentInterface {
ComponentInterface(
const std::shared_ptr<C2ComponentInterface>& interface,
const std::shared_ptr<ParameterCache>& cache);
+ ComponentInterface(
+ const std::shared_ptr<C2ComponentInterface>& interface,
+ const std::shared_ptr<MultiAccessUnitInterface>& largeBufferIntf,
+ const std::shared_ptr<ParameterCache>& cache);
c2_status_t status() const;
::ndk::ScopedAStatus getConfigurable(
std::shared_ptr<IConfigurable> *intf) override;
@@ -51,7 +58,6 @@
c2_status_t mInit;
};
-
} // namespace utils
} // namespace c2
} // namespace media
diff --git a/media/codec2/hal/common/Android.bp b/media/codec2/hal/common/Android.bp
index 2aedd8b..7d7b285 100644
--- a/media/codec2/hal/common/Android.bp
+++ b/media/codec2/hal/common/Android.bp
@@ -11,6 +11,7 @@
srcs: [
"BufferTypes.cpp",
+ "MultiAccessUnitHelper.cpp",
],
export_include_dirs: ["include/"],
@@ -26,7 +27,10 @@
"libcodec2_vndk",
"liblog",
"libstagefright_foundation",
+ "server_configurable_flags",
],
+
+ static_libs: ["aconfig_mediacodec_flags_c_lib"],
}
cc_library_static {
diff --git a/media/codec2/hal/common/HalSelection.cpp b/media/codec2/hal/common/HalSelection.cpp
index 761a409..d3ea181 100644
--- a/media/codec2/hal/common/HalSelection.cpp
+++ b/media/codec2/hal/common/HalSelection.cpp
@@ -28,7 +28,12 @@
namespace android {
bool IsCodec2AidlHalSelected() {
- if (!com::android::media::codec::flags::provider_->aidl_hal()) {
+ // For new devices with vendor software targeting 202404, we always want to
+ // use AIDL if it exists
+ constexpr int kAndroidApi202404 = 202404;
+ int vendorVersion = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
+ if (!com::android::media::codec::flags::provider_->aidl_hal() &&
+ vendorVersion < kAndroidApi202404) {
// Cannot select AIDL if not enabled
return false;
}
diff --git a/media/codec2/hal/common/MultiAccessUnitHelper.cpp b/media/codec2/hal/common/MultiAccessUnitHelper.cpp
new file mode 100644
index 0000000..cd9fd9f
--- /dev/null
+++ b/media/codec2/hal/common/MultiAccessUnitHelper.cpp
@@ -0,0 +1,742 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "Codec2-MultiAccessUnitHelper"
+#include <android-base/logging.h>
+
+#include <com_android_media_codec_flags.h>
+
+#include <codec2/common/MultiAccessUnitHelper.h>
+#include <android-base/properties.h>
+
+#include <C2BufferPriv.h>
+#include <C2Debug.h>
+#include <C2PlatformSupport.h>
+
+namespace android {
+
+static C2R MultiAccessUnitParamsSetter(
+ bool mayBlock, C2InterfaceHelper::C2P<C2LargeFrame::output> &me) {
+ (void)mayBlock;
+ C2R res = C2R::Ok();
+ if (!me.F(me.v.maxSize).supportsAtAll(me.v.maxSize)) {
+ res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.maxSize)));
+ } else if (!me.F(me.v.thresholdSize).supportsAtAll(me.v.thresholdSize)) {
+ res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.thresholdSize)));
+ } else if (me.v.maxSize < me.v.thresholdSize) {
+ me.set().maxSize = me.v.thresholdSize;
+ } else if (me.v.thresholdSize == 0 && me.v.maxSize > 0) {
+ me.set().thresholdSize = me.v.maxSize;
+ }
+ std::vector<std::unique_ptr<C2SettingResult>> failures;
+ res.retrieveFailures(&failures);
+ if (!failures.empty()) {
+ me.set().maxSize = 0;
+ me.set().thresholdSize = 0;
+ }
+ return res;
+}
+
+MultiAccessUnitInterface::MultiAccessUnitInterface(
+ const std::shared_ptr<C2ComponentInterface>& interface,
+ std::shared_ptr<C2ReflectorHelper> helper)
+ : C2InterfaceHelper(helper), mC2ComponentIntf(interface) {
+ setDerivedInstance(this);
+ addParameter(
+ DefineParam(mLargeFrameParams, C2_PARAMKEY_OUTPUT_LARGE_FRAME)
+ .withDefault(new C2LargeFrame::output(0u, 0, 0))
+ .withFields({
+ C2F(mLargeFrameParams, maxSize).inRange(
+ 0, c2_min(UINT_MAX, 10 * 512000 * 8 * 2u)),
+ C2F(mLargeFrameParams, thresholdSize).inRange(
+ 0, c2_min(UINT_MAX, 10 * 512000 * 8 * 2u))
+ })
+ .withSetter(MultiAccessUnitParamsSetter)
+ .build());
+ std::vector<std::shared_ptr<C2ParamDescriptor>> supportedParams;
+ querySupportedParams(&supportedParams);
+ // Adding to set to do intf seperation in query/config
+ for (std::shared_ptr<C2ParamDescriptor> &desc : supportedParams) {
+ mSupportedParamIndexSet.insert(desc->index());
+ }
+
+ if (mC2ComponentIntf) {
+ c2_status_t err = mC2ComponentIntf->query_vb({&mKind}, {}, C2_MAY_BLOCK, nullptr);
+ }
+}
+
+bool MultiAccessUnitInterface::isParamSupported(C2Param::Index index) {
+ return (mSupportedParamIndexSet.count(index) != 0);
+}
+
+C2LargeFrame::output MultiAccessUnitInterface::getLargeFrameParam() const {
+ return *mLargeFrameParams;
+}
+
+C2Component::kind_t MultiAccessUnitInterface::kind() const {
+ return (C2Component::kind_t)(mKind.value);
+}
+
+void MultiAccessUnitInterface::getDecoderSampleRateAndChannelCount(
+ uint32_t &sampleRate_, uint32_t &channelCount_) const {
+ if (mC2ComponentIntf) {
+ C2StreamSampleRateInfo::output sampleRate;
+ C2StreamChannelCountInfo::output channelCount;
+ c2_status_t res = mC2ComponentIntf->query_vb(
+ {&sampleRate, &channelCount}, {}, C2_MAY_BLOCK, nullptr);
+ if (res == C2_OK) {
+ sampleRate_ = sampleRate.value;
+ channelCount_ = channelCount.value;
+ }
+ }
+}
+
+//C2MultiAccessUnitBuffer
+class C2MultiAccessUnitBuffer : public C2Buffer {
+ public:
+ explicit C2MultiAccessUnitBuffer(
+ const std::vector<C2ConstLinearBlock> &blocks):
+ C2Buffer(blocks) {
+ }
+};
+
+//MultiAccessUnitHelper
+MultiAccessUnitHelper::MultiAccessUnitHelper(
+ const std::shared_ptr<MultiAccessUnitInterface>& intf):
+ mInit(false),
+ mInterface(intf) {
+ std::shared_ptr<C2AllocatorStore> store = GetCodec2PlatformAllocatorStore();
+ if(store->fetchAllocator(C2AllocatorStore::DEFAULT_LINEAR, &mLinearAllocator) == C2_OK) {
+ mLinearPool = std::make_shared<C2PooledBlockPool>(mLinearAllocator, ++mBlockPoolId);
+ mInit = true;
+ }
+}
+
+MultiAccessUnitHelper::~MultiAccessUnitHelper() {
+ std::unique_lock<std::mutex> l(mLock);
+ mFrameHolder.clear();
+}
+
+bool MultiAccessUnitHelper::isEnabledOnPlatform() {
+ bool result = com::android::media::codec::flags::provider_->large_audio_frame();
+ if (!result) {
+ return false;
+ }
+ //TODO: remove this before launch
+ result = ::android::base::GetBoolProperty("debug.media.c2.large.audio.frame", true);
+ LOG(DEBUG) << "MultiAccessUnitHelper " << (result ? "enabled" : "disabled");
+ return result;
+}
+
+std::shared_ptr<MultiAccessUnitInterface> MultiAccessUnitHelper::getInterface() {
+ return mInterface;
+}
+
+bool MultiAccessUnitHelper::getStatus() {
+ return mInit;
+}
+
+void MultiAccessUnitHelper::reset() {
+ std::lock_guard<std::mutex> l(mLock);
+ mFrameHolder.clear();
+}
+
+c2_status_t MultiAccessUnitHelper::error(
+ std::list<std::unique_ptr<C2Work>> * const worklist) {
+ if (worklist == nullptr) {
+ LOG(ERROR) << "Provided null worklist for error()";
+ return C2_OK;
+ }
+ std::unique_lock<std::mutex> l(mLock);
+ for (auto frame = mFrameHolder.begin(); frame != mFrameHolder.end(); frame++) {
+ if (frame->mLargeWork) {
+ finalizeWork(*frame, 0, true);
+ worklist->push_back(std::move(frame->mLargeWork));
+ frame->reset();
+ }
+ }
+ mFrameHolder.clear();
+ return C2_OK;
+}
+
+c2_status_t MultiAccessUnitHelper::flush(
+ std::list<std::unique_ptr<C2Work>>* const c2flushedWorks) {
+ c2_status_t c2res = C2_OK;
+ std::lock_guard<std::mutex> l(mLock);
+ for (std::unique_ptr<C2Work>& w : *c2flushedWorks) {
+ bool foundFlushedFrame = false;
+ std::list<MultiAccessUnitInfo>::iterator frame =
+ mFrameHolder.begin();
+ while (frame != mFrameHolder.end() && !foundFlushedFrame) {
+ auto it = frame->mComponentFrameIds.find(
+ w->input.ordinal.frameIndex.peekull());
+ if (it != frame->mComponentFrameIds.end()) {
+ LOG(DEBUG) << "Multi access-unit flush"
+ << w->input.ordinal.frameIndex.peekull()
+ << " with " << frame->inOrdinal.frameIndex.peekull();
+ w->input.ordinal.frameIndex = frame->inOrdinal.frameIndex;
+ bool removeEntry = w->worklets.empty()
+ || !w->worklets.front()
+ || (w->worklets.front()->output.flags
+ & C2FrameData::FLAG_INCOMPLETE) == 0;
+ if (removeEntry) {
+ frame->mComponentFrameIds.erase(it);
+ }
+ foundFlushedFrame = true;
+ }
+ if (frame->mComponentFrameIds.empty()) {
+ frame = mFrameHolder.erase(frame);
+ } else {
+ ++frame;
+ }
+ }
+ }
+ return c2res;
+}
+
+c2_status_t MultiAccessUnitHelper::scatter(
+ std::list<std::unique_ptr<C2Work>> &largeWork,
+ std::list<std::list<std::unique_ptr<C2Work>>>* const processedWork) {
+ LOG(DEBUG) << "Multiple access-unit: scatter";
+ if (processedWork == nullptr) {
+ LOG(ERROR) << "MultiAccessUnitHelper provided with no work list";
+ return C2_CORRUPTED;
+ }
+ for (std::unique_ptr<C2Work>& w : largeWork) {
+ std::list<std::unique_ptr<C2Work>> sliceWork;
+ C2WorkOrdinalStruct inputOrdinal = w->input.ordinal;
+ // To hold correspondence and processing bits b/w input and output
+ MultiAccessUnitInfo frameInfo(inputOrdinal);
+ std::set<uint64_t>& frameSet = frameInfo.mComponentFrameIds;
+ uint64_t newFrameIdx = mFrameIndex++;
+ // TODO: Do not split buffers if component inherantly supports MultipleFrames.
+ // if thats case, only replace frameindex.
+ auto cloneInputWork = [&newFrameIdx](std::unique_ptr<C2Work>& inWork, uint32_t flags) {
+ std::unique_ptr<C2Work> newWork(new C2Work);
+ newWork->input.flags = (C2FrameData::flags_t)flags;
+ newWork->input.ordinal = inWork->input.ordinal;
+ newWork->input.ordinal.frameIndex = newFrameIdx;
+ if (!inWork->input.configUpdate.empty()) {
+ for (std::unique_ptr<C2Param>& param : inWork->input.configUpdate) {
+ newWork->input.configUpdate.push_back(
+ std::move(C2Param::Copy(*(param.get()))));
+ }
+ }
+ newWork->input.infoBuffers = (inWork->input.infoBuffers);
+ if (!inWork->worklets.empty() && inWork->worklets.front() != nullptr) {
+ newWork->worklets.emplace_back(new C2Worklet);
+ newWork->worklets.front()->component = inWork->worklets.front()->component;
+ std::vector<std::unique_ptr<C2Tuning>> tunings;
+ for (std::unique_ptr<C2Tuning>& tuning : inWork->worklets.front()->tunings) {
+ tunings.push_back(std::move(
+ std::unique_ptr<C2Tuning>(
+ static_cast<C2Tuning*>(
+ C2Param::Copy(*(tuning.get())).release()))));
+ }
+ newWork->worklets.front()->tunings = std::move(tunings);
+ }
+ return newWork;
+ };
+ if (w->input.buffers.empty()
+ || (w->input.buffers.front() == nullptr)
+ || (!w->input.buffers.front()->hasInfo(
+ C2AccessUnitInfos::input::PARAM_TYPE))) {
+ LOG(DEBUG) << "Empty or MultiAU info buffer scatter frames with frameIndex "
+ << inputOrdinal.frameIndex.peekull()
+ << ") -> newFrameIndex " << newFrameIdx
+ <<" : input ts " << inputOrdinal.timestamp.peekull();
+ sliceWork.push_back(std::move(cloneInputWork(w, w->input.flags)));
+ if (!w->input.buffers.empty() && w->input.buffers.front() != nullptr) {
+ sliceWork.back()->input.buffers = std::move(w->input.buffers);
+ }
+ frameSet.insert(newFrameIdx);
+ processedWork->push_back(std::move(sliceWork));
+ } else {
+ const std::vector<std::shared_ptr<C2Buffer>>& inBuffers = w->input.buffers;
+ if (inBuffers.front()->data().linearBlocks().size() == 0) {
+ LOG(ERROR) << "ERROR: Work has Large frame info but has no linear blocks.";
+ return C2_CORRUPTED;
+ }
+ const std::vector<C2ConstLinearBlock>& multiAU =
+ inBuffers.front()->data().linearBlocks();
+ std::shared_ptr<const C2AccessUnitInfos::input> auInfo =
+ std::static_pointer_cast<const C2AccessUnitInfos::input>(
+ w->input.buffers.front()->getInfo(C2AccessUnitInfos::input::PARAM_TYPE));
+ uint32_t offset = 0; uint32_t multiAUSize = multiAU.front().size();
+ bool sendEos = false;
+ for (int idx = 0; idx < auInfo->flexCount(); ++idx) {
+ std::vector<C2ConstLinearBlock> au;
+ const C2AccessUnitInfosStruct &info = auInfo->m.values[idx];
+ sendEos |= (info.flags & C2FrameData::FLAG_END_OF_STREAM);
+ std::unique_ptr<C2Work> newWork = cloneInputWork(w, info.flags);
+ frameSet.insert(newFrameIdx);
+ newFrameIdx = mFrameIndex++;
+ newWork->input.ordinal.timestamp = info.timestamp;
+ au.push_back(multiAU.front().subBlock(offset, info.size));
+ if ((offset + info.size) > multiAUSize) {
+ LOG(ERROR) << "ERROR: access-unit offset > buffer size"
+ << " current offset " << (offset + info.size)
+ << " buffer size " << multiAUSize;
+ return C2_CORRUPTED;
+ }
+ newWork->input.buffers.push_back(
+ std::shared_ptr<C2Buffer>(new C2MultiAccessUnitBuffer(au)));
+ LOG(DEBUG) << "Frame scatter queuing frames WITH info in ordinal "
+ << inputOrdinal.frameIndex.peekull()
+ << " total offset " << offset << " info.size " << info.size
+ << " : TS " << newWork->input.ordinal.timestamp.peekull();
+ // add to worklist
+ sliceWork.push_back(std::move(newWork));
+ processedWork->push_back(std::move(sliceWork));
+ offset += info.size;
+ }
+ if (!sendEos && (w->input.flags & C2FrameData::FLAG_END_OF_STREAM)) {
+ if (!processedWork->empty()) {
+ std::list<std::unique_ptr<C2Work>> &sliceWork = processedWork->back();
+ if (!sliceWork.empty()) {
+ std::unique_ptr<C2Work> &work = sliceWork.back();
+ if (work) {
+ work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
+ }
+ }
+ }
+ }
+ }
+ if (!processedWork->empty()) {
+ {
+ C2LargeFrame::output multiAccessParams = mInterface->getLargeFrameParam();
+ if (mInterface->kind() == C2Component::KIND_DECODER) {
+ uint32_t sampleRate = 0;
+ uint32_t channelCount = 0;
+ uint32_t frameSize = 0;
+ mInterface->getDecoderSampleRateAndChannelCount(
+ sampleRate, channelCount);
+ if (sampleRate > 0 && channelCount > 0) {
+ frameSize = channelCount * 2;
+ multiAccessParams.maxSize =
+ (multiAccessParams.maxSize / frameSize) * frameSize;
+ multiAccessParams.thresholdSize =
+ (multiAccessParams.thresholdSize / frameSize) * frameSize;
+ }
+ }
+ frameInfo.mLargeFrameTuning = multiAccessParams;
+ std::lock_guard<std::mutex> l(mLock);
+ mFrameHolder.push_back(std::move(frameInfo));
+ }
+ }
+ }
+ return C2_OK;
+}
+
+c2_status_t MultiAccessUnitHelper::gather(
+ std::list<std::unique_ptr<C2Work>> &c2workItems,
+ std::list<std::unique_ptr<C2Work>>* const processedWork) {
+ LOG(DEBUG) << "Multi access-unit gather process";
+ if (processedWork == nullptr) {
+ LOG(ERROR) << "Nothing provided for processed work";
+ return C2_CORRUPTED;
+ }
+ auto addOutWork = [&processedWork](std::unique_ptr<C2Work>& work) {
+ processedWork->push_back(std::move(work));
+ };
+ {
+ std::lock_guard<std::mutex> l(mLock);
+ for (auto& work : c2workItems) {
+ LOG(DEBUG) << "FrameHolder Size: " << mFrameHolder.size();
+ uint64_t thisFrameIndex = work->input.ordinal.frameIndex.peekull();
+ bool removeEntry = work->worklets.empty()
+ || !work->worklets.front()
+ || (work->worklets.front()->output.flags
+ & C2FrameData::FLAG_INCOMPLETE) == 0;
+ bool foundFrame = false;
+ std::list<MultiAccessUnitInfo>::iterator frame =
+ mFrameHolder.begin();
+ while (!foundFrame && frame != mFrameHolder.end()) {
+ auto it = frame->mComponentFrameIds.find(thisFrameIndex);
+ if (it != frame->mComponentFrameIds.end()) {
+ foundFrame = true;
+ LOG(DEBUG) << "onWorkDone (frameIndex " << thisFrameIndex
+ << " worklstsSze " << work->worklets.size()
+ << ") -> frameIndex " << frame->inOrdinal.frameIndex.peekull();
+ if (work->result != C2_OK
+ || work->worklets.empty()
+ || !work->worklets.front()
+ || (frame->mLargeFrameTuning.thresholdSize == 0
+ || frame->mLargeFrameTuning.maxSize == 0)) {
+ if (removeEntry) {
+ frame->mComponentFrameIds.erase(it);
+ removeEntry = false;
+ }
+ if (frame->mLargeWork) {
+ finalizeWork(*frame);
+ addOutWork(frame->mLargeWork);
+ frame->reset();
+ }
+ c2_status_t workResult = work->result;
+ frame->mLargeWork = std::move(work);
+ frame->mLargeWork->input.ordinal.frameIndex =
+ frame->inOrdinal.frameIndex;
+ finalizeWork(*frame);
+ addOutWork(frame->mLargeWork);
+ frame->reset();
+ if (workResult != C2_OK) {
+ frame->mAccessUnitInfos.clear();
+ }
+ } else if (C2_OK != processWorklets(*frame, work, addOutWork)) {
+ LOG(DEBUG) << "Error while processing work";
+ }
+ if (removeEntry) {
+ LOG(DEBUG) << "Removing entry: " << thisFrameIndex
+ << " -> " << frame->inOrdinal.frameIndex.peekull();
+ frame->mComponentFrameIds.erase(it);
+ }
+ // This is to take care of the last bytes and to decide to send with
+ // FLAG_INCOMPLETE or not.
+ if ((frame->mWview
+ && (frame->mWview->offset() > frame->mLargeFrameTuning.thresholdSize))
+ || frame->mComponentFrameIds.empty()) {
+ if (frame->mLargeWork) {
+ finalizeWork(*frame);
+ addOutWork(frame->mLargeWork);
+ frame->reset();
+ }
+ }
+ if (frame->mComponentFrameIds.empty()) {
+ LOG(DEBUG) << "This frame is finished ID " << thisFrameIndex;
+ frame = mFrameHolder.erase(frame);
+ continue;
+ }
+ } else {
+ LOG(DEBUG) << "Received an out-of-order output " << thisFrameIndex
+ << " expected: " <<mFrameHolder.front().inOrdinal.frameIndex.peekull();
+ }
+ frame++;
+ }
+ if (!foundFrame) {
+ LOG(ERROR) <<" Error: Frame Holder reports no frame " << thisFrameIndex;
+ }
+ }
+ }
+ return C2_OK;
+}
+
+c2_status_t MultiAccessUnitHelper::createLinearBlock(MultiAccessUnitInfo &frame) {
+ if (!mInit) {
+ LOG(ERROR) << "Large buffer allocator failed";
+ return C2_NO_MEMORY;
+ }
+ C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
+ uint32_t maxOutSize = frame.mLargeFrameTuning.maxSize;
+ c2_status_t err = mLinearPool->fetchLinearBlock(maxOutSize, usage, &frame.mBlock);
+ LOG(DEBUG) << "Allocated block with offset : " << frame.mBlock->offset()
+ << " size " << frame.mBlock->size() << " Capacity " << frame.mBlock->capacity();
+ if (err != C2_OK) {
+ LOG(ERROR) << "Error allocating Multi access-unit Buffer";
+ return err;
+ }
+ frame.mWview = std::make_shared<C2WriteView>(frame.mBlock->map().get());
+ LOG(DEBUG) << "Allocated buffer : requested size : " <<
+ frame.mLargeFrameTuning.maxSize
+ << " alloc size " << frame.mWview->size();
+ return C2_OK;
+}
+
+/*
+ * For every work from the component, we try to do aggregation of work here.
+*/
+c2_status_t MultiAccessUnitHelper::processWorklets(MultiAccessUnitInfo &frame,
+ std::unique_ptr<C2Work>& work,
+ const std::function <void(std::unique_ptr<C2Work>&)>& addWork) {
+ // This will allocate work, worklet, c2Block
+ auto allocateWork = [&](MultiAccessUnitInfo &frame,
+ bool allocateWorket = false,
+ bool allocateBuffer = false) {
+ c2_status_t ret = C2_OK;
+ if (frame.mLargeWork == nullptr) {
+ frame.mLargeWork.reset(new C2Work);
+ frame.mLargeWork->input.ordinal = frame.inOrdinal;
+ frame.mLargeWork->input.ordinal.frameIndex = frame.inOrdinal.frameIndex;
+ }
+ if (allocateWorket) {
+ if (frame.mLargeWork->worklets.size() == 0) {
+ frame.mLargeWork->worklets.emplace_back(new C2Worklet);
+ }
+ }
+ if (allocateBuffer) {
+ if (frame.mWview == nullptr) {
+ ret = createLinearBlock(frame);
+ }
+ }
+ return ret;
+ };
+ // we will only have one worklet.
+ bool foundEndOfStream = false;
+ for (auto worklet = work->worklets.begin();
+ worklet != work->worklets.end() && (*worklet) != nullptr; ++worklet) {
+ uint32_t flagsForNoCopy = C2FrameData::FLAG_DROP_FRAME
+ | C2FrameData::FLAG_DISCARD_FRAME
+ | C2FrameData::FLAG_CORRUPT;
+ if ((*worklet)->output.flags & flagsForNoCopy) {
+ if (frame.mLargeWork) {
+ finalizeWork(frame);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ }
+ frame.mLargeWork = std::move(work);
+ frame.mLargeWork->input.ordinal.frameIndex = frame.inOrdinal.frameIndex;
+ finalizeWork(frame);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ return C2_OK;
+ }
+ c2_status_t c2ret = allocateWork(frame, true);
+ if (c2ret != C2_OK) {
+ return c2ret;
+ }
+ C2FrameData& outputFramedata = frame.mLargeWork->worklets.front()->output;
+ if (!(*worklet)->output.configUpdate.empty()) {
+ for (auto& configUpdate : (*worklet)->output.configUpdate) {
+ outputFramedata.configUpdate.push_back(std::move(configUpdate));
+ }
+ (*worklet)->output.configUpdate.clear();
+ }
+ outputFramedata.infoBuffers.insert(outputFramedata.infoBuffers.begin(),
+ (*worklet)->output.infoBuffers.begin(),
+ (*worklet)->output.infoBuffers.end());
+ int64_t sampleTimeUs = 0;
+ uint32_t frameSize = 0;
+ uint32_t sampleRate = 0;
+ uint32_t channelCount = 0;
+ mInterface->getDecoderSampleRateAndChannelCount(sampleRate, channelCount);
+ if (sampleRate > 0 && channelCount > 0) {
+ sampleTimeUs = (1000000u) / (sampleRate * channelCount * 2);
+ frameSize = channelCount * 2;
+ }
+ LOG(DEBUG) << "maxOutSize " << frame.mLargeFrameTuning.maxSize
+ << " threshold " << frame.mLargeFrameTuning.thresholdSize;
+ if ((*worklet)->output.buffers.size() > 0) {
+ allocateWork(frame, true, true);
+ }
+ LOG(DEBUG) << "This worklet has " << (*worklet)->output.buffers.size() << " buffers"
+ << " ts: " << (*worklet)->output.ordinal.timestamp.peekull();
+ int64_t workletTimestamp = (*worklet)->output.ordinal.timestamp.peekull();
+ int64_t timestamp = workletTimestamp;
+ uint32_t flagsForCopy = ((*worklet)->output.flags) & C2FrameData::FLAG_CODEC_CONFIG;
+ for (int bufIdx = 0; bufIdx < (*worklet)->output.buffers.size(); ++bufIdx) {
+ std::shared_ptr<C2Buffer>& buffer = (*worklet)->output.buffers[bufIdx];
+ if (!buffer || buffer->data().linearBlocks().empty()) {
+ continue;
+ }
+ const std::vector<C2ConstLinearBlock>& blocks = buffer->data().linearBlocks();
+ if (blocks.size() > 0) {
+ uint32_t inputOffset = 0;
+ uint32_t inputSize = blocks.front().size();
+ frame.mInfos.insert(frame.mInfos.end(),
+ buffer->info().begin(), buffer->info().end());
+ if (frameSize != 0 && (mInterface->kind() == C2Component::KIND_DECODER)) {
+ // For decoders we only split multiples of 16bChannelCount*2
+ inputSize -= (inputSize % frameSize);
+ }
+ while (inputOffset < inputSize) {
+ if (frame.mWview->offset() >= frame.mLargeFrameTuning.thresholdSize) {
+ frame.mLargeWork->result = C2_OK;
+ finalizeWork(frame, flagsForCopy);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ allocateWork(frame, true, true);
+ }
+ if (mInterface->kind() == C2Component::KIND_ENCODER) {
+ if (inputSize > frame.mLargeFrameTuning.maxSize) {
+ LOG(ERROR) << "Enc: Output buffer too small for AU, configured with "
+ << frame.mLargeFrameTuning.maxSize
+ << " block size: " << blocks.front().size()
+ << "alloc size " << frame.mWview->size();
+ if (frame.mLargeWork
+ && frame.mWview && frame.mWview->offset() > 0) {
+ finalizeWork(frame, flagsForCopy);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ allocateWork(frame, true, false);
+ }
+ frame.mLargeWork->result = C2_NO_MEMORY;
+ finalizeWork(frame, 0, true);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ return C2_NO_MEMORY;
+ } else if (inputSize > frame.mWview->size()) {
+ LOG(DEBUG) << "Enc: Large frame hitting bufer limit, current size "
+ << frame.mWview->offset();
+ if (frame.mLargeWork
+ && frame.mWview && frame.mWview->offset() > 0) {
+ finalizeWork(frame, flagsForCopy);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ allocateWork(frame, true, true);
+ }
+ }
+ }
+ C2ReadView rView = blocks.front().map().get();
+ if (rView.error()) {
+ LOG(ERROR) << "Buffer read view error";
+ frame.mLargeWork->result = rView.error();
+ frame.mLargeWork->worklets.clear();
+ finalizeWork(frame, 0, true);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ return C2_NO_MEMORY;
+ }
+ uint32_t toCopy = 0;
+ if (mInterface->kind() == C2Component::KIND_ENCODER) {
+ toCopy = inputSize;
+ } else {
+ toCopy = c2_min(frame.mWview->size(), (inputSize - inputOffset));
+ timestamp = workletTimestamp + inputOffset * sampleTimeUs;
+ LOG(DEBUG) << "ts " << timestamp
+ << " copiedOutput " << inputOffset
+ << " sampleTimeUs " << sampleTimeUs;
+ }
+ LOG(DEBUG) << " Copy size " << toCopy
+ << " ts " << timestamp;
+ memcpy(frame.mWview->data(), rView.data() + inputOffset, toCopy);
+ frame.mWview->setOffset(frame.mWview->offset() + toCopy);
+ inputOffset += toCopy;
+ mergeAccessUnitInfo(frame, flagsForCopy, toCopy, timestamp);
+ }
+ } else {
+ frame.mLargeWork->worklets.front()->output.buffers.push_back(std::move(buffer));
+ LOG(DEBUG) << "Copying worklets without linear buffer";
+ }
+ }
+ uint32_t flagsForCsdOrEnd = (*worklet)->output.flags
+ & (C2FrameData::FLAG_END_OF_STREAM | C2FrameData::FLAG_CODEC_CONFIG);
+ if (flagsForCsdOrEnd) {
+ LOG(DEBUG) << "Output worklet has CSD/EOS data";
+ frame.mLargeWork->result = C2_OK;
+ // we can assign timestamp as this will be evaluated in finalizeWork
+ frame.mLargeWork->worklets.front()->output.ordinal.timestamp = timestamp;
+ finalizeWork(frame, flagsForCsdOrEnd, true);
+ addWork(frame.mLargeWork);
+ frame.reset();
+ }
+ }
+ return C2_OK;
+}
+
+c2_status_t MultiAccessUnitHelper::finalizeWork(
+ MultiAccessUnitInfo& frame, uint32_t inFlags, bool forceComplete) {
+ if (frame.mLargeWork == nullptr) {
+ return C2_OK;
+ }
+ //prepare input ordinal
+ frame.mLargeWork->input.ordinal = frame.inOrdinal;
+ // remove this
+ int64_t timeStampUs = frame.inOrdinal.timestamp.peekull();
+ if (!frame.mAccessUnitInfos.empty()) {
+ timeStampUs = frame.mAccessUnitInfos.front().timestamp;
+ } else if (!frame.mLargeWork->worklets.empty()) {
+ std::unique_ptr<C2Worklet> &worklet = frame.mLargeWork->worklets.front();
+ if (worklet) {
+ timeStampUs = worklet->output.ordinal.timestamp.peekull();
+ }
+ }
+ LOG(DEBUG) << "Finalizing work with input Idx "
+ << frame.mLargeWork->input.ordinal.frameIndex.peekull()
+ << " timestamp " << timeStampUs;
+ uint32_t finalFlags = 0;
+ if ((!forceComplete)
+ && (frame.mLargeWork->result == C2_OK)
+ && (!frame.mComponentFrameIds.empty())) {
+ finalFlags |= C2FrameData::FLAG_INCOMPLETE;
+ }
+ if (frame.mLargeWork->result == C2_OK) {
+ finalFlags |= inFlags;
+ }
+ // update worklet if present
+ if (!frame.mLargeWork->worklets.empty() &&
+ frame.mLargeWork->worklets.front() != nullptr) {
+ frame.mLargeWork->workletsProcessed = 1;
+ C2FrameData& outFrameData = frame.mLargeWork->worklets.front()->output;
+ outFrameData.ordinal.frameIndex = frame.inOrdinal.frameIndex.peekull();
+ outFrameData.ordinal.timestamp = timeStampUs;
+ finalFlags |= frame.mLargeWork->worklets.front()->output.flags;
+ outFrameData.flags = (C2FrameData::flags_t)finalFlags;
+ // update buffers
+ if (frame.mBlock && (frame.mWview->offset() > 0)) {
+ size_t size = frame.mWview->offset();
+ LOG(DEBUG) << "Finalize : Block: Large frame size set as " << size
+ << " timestamp as " << timeStampUs
+ << "frameIndex " << outFrameData.ordinal.frameIndex.peekull();
+ frame.mWview->setOffset(0);
+ std::shared_ptr<C2Buffer> c2Buffer = C2Buffer::CreateLinearBuffer(
+ frame.mBlock->share(0, size, ::C2Fence()));
+ if (frame.mAccessUnitInfos.size() > 0) {
+ if (finalFlags & C2FrameData::FLAG_END_OF_STREAM) {
+ frame.mAccessUnitInfos.back().flags |=
+ C2FrameData::FLAG_END_OF_STREAM;
+ }
+ std::shared_ptr<C2AccessUnitInfos::output> largeFrame =
+ C2AccessUnitInfos::output::AllocShared(
+ frame.mAccessUnitInfos.size(), 0u, frame.mAccessUnitInfos);
+ frame.mInfos.push_back(largeFrame);
+ frame.mAccessUnitInfos.clear();
+ }
+ for (auto &info : frame.mInfos) {
+ c2Buffer->setInfo(std::const_pointer_cast<C2Info>(info));
+ }
+ frame.mLargeWork->worklets.front()->output.buffers.push_back(std::move(c2Buffer));
+ frame.mInfos.clear();
+ frame.mBlock.reset();
+ frame.mWview.reset();
+ }
+ }
+ LOG(DEBUG) << "Multi access-unitflag setting as " << finalFlags;
+ return C2_OK;
+}
+
+void MultiAccessUnitHelper::mergeAccessUnitInfo(
+ MultiAccessUnitInfo &frame,
+ uint32_t flags_,
+ uint32_t size,
+ int64_t timestamp) {
+ // Remove flags that are not part of Access unit info
+ uint32_t flags = flags_ & ~(C2FrameData::FLAG_INCOMPLETE
+ | C2FrameData::FLAG_DISCARD_FRAME
+ | C2FrameData::FLAG_CORRUPT
+ | C2FrameData::FLAG_CORRECTED);
+ if (frame.mAccessUnitInfos.empty()) {
+ frame.mAccessUnitInfos.emplace_back(flags, size, timestamp);
+ return;
+ }
+ if ((mInterface->kind() == C2Component::KIND_DECODER) &&
+ (frame.mAccessUnitInfos.back().flags == flags)) {
+ // merge access units here
+ C2AccessUnitInfosStruct &s = frame.mAccessUnitInfos.back();
+ s.size += size; // don't have to update timestamp
+ } else {
+ frame.mAccessUnitInfos.emplace_back(flags, size, timestamp);
+ }
+}
+
+void MultiAccessUnitHelper::MultiAccessUnitInfo::reset() {
+ mBlock.reset();
+ mWview.reset();
+ mInfos.clear();
+ mAccessUnitInfos.clear();
+ mLargeWork.reset();
+}
+
+} // namespace android
\ No newline at end of file
diff --git a/media/codec2/hal/common/include/codec2/common/MultiAccessUnitHelper.h b/media/codec2/hal/common/include/codec2/common/MultiAccessUnitHelper.h
new file mode 100644
index 0000000..ef5cff9
--- /dev/null
+++ b/media/codec2/hal/common/include/codec2/common/MultiAccessUnitHelper.h
@@ -0,0 +1,211 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 CODEC2_COMMON_MULTI_ACCESSUNIT_HELPER_H
+#define CODEC2_COMMON_MULTI_ACCESSUNIT_HELPER_H
+
+#include <hidl/Status.h>
+#include <hwbinder/IBinder.h>
+
+#include <C2Config.h>
+#include <util/C2InterfaceHelper.h>
+#include <C2Buffer.h>
+#include <C2.h>
+
+#include <set>
+#include <memory>
+#include <mutex>
+
+namespace android {
+
+struct MultiAccessUnitHelper;
+
+struct MultiAccessUnitInterface : public C2InterfaceHelper {
+ explicit MultiAccessUnitInterface(
+ const std::shared_ptr<C2ComponentInterface>& interface,
+ std::shared_ptr<C2ReflectorHelper> helper);
+
+ bool isParamSupported(C2Param::Index index);
+ C2LargeFrame::output getLargeFrameParam() const;
+ C2Component::kind_t kind() const;
+
+protected:
+ void getDecoderSampleRateAndChannelCount(
+ uint32_t &sampleRate_, uint32_t &channelCount_) const;
+ const std::shared_ptr<C2ComponentInterface> mC2ComponentIntf;
+ std::shared_ptr<C2LargeFrame::output> mLargeFrameParams;
+ C2ComponentKindSetting mKind;
+ std::set<C2Param::Index> mSupportedParamIndexSet;
+
+ friend struct MultiAccessUnitHelper;
+};
+
+struct MultiAccessUnitHelper {
+public:
+ MultiAccessUnitHelper(
+ const std::shared_ptr<MultiAccessUnitInterface>& intf);
+
+ virtual ~MultiAccessUnitHelper();
+
+ static bool isEnabledOnPlatform();
+
+ /*
+ * Scatters the incoming linear buffer into access-unit sized buffers
+ * based on the access-unit info.
+ */
+ c2_status_t scatter(
+ std::list<std::unique_ptr<C2Work>> &c2workItems,
+ std::list<std::list<std::unique_ptr<C2Work>>> * const processedWork);
+
+ /*
+ * Gathers different access-units into a single buffer based on the scatter list
+ * and the configured max and threshold sizes. This also generates the associated
+ * access-unit information and attach it with the final result.
+ */
+ c2_status_t gather(
+ std::list<std::unique_ptr<C2Work>> &c2workItems,
+ std::list<std::unique_ptr<C2Work>> * const processedWork);
+
+ /*
+ * Flushes the codec and generated the list of flushed buffers.
+ */
+ c2_status_t flush(
+ std::list<std::unique_ptr<C2Work>> * const c2flushedWorks);
+
+ /*
+ * Gets all the pending buffers under generation in c2workItems.
+ */
+ c2_status_t error(std::list<std::unique_ptr<C2Work>> * const c2workItems);
+
+ /*
+ * Get the interface object of this handler.
+ */
+ std::shared_ptr<MultiAccessUnitInterface> getInterface();
+
+ /*
+ * Gets the status of the object. This really is to make sure that
+ * all the allocators are configured properly within the handler.
+ */
+ bool getStatus();
+
+ /*
+ * Resets the structures inside the handler.
+ */
+ void reset();
+
+protected:
+
+ struct MultiAccessUnitInfo {
+ /*
+ * From the input
+ * Ordinal of the input frame
+ */
+ C2WorkOrdinalStruct inOrdinal;
+
+ /*
+ * Frame indexes of the scattered buffers
+ */
+ std::set<uint64_t> mComponentFrameIds;
+
+ /*
+ * For the output
+ * Current output block.
+ */
+ std::shared_ptr<C2LinearBlock> mBlock;
+
+ /*
+ * Write view of current block
+ */
+ std::shared_ptr<C2WriteView> mWview;
+
+ /*
+ * C2Info related to the current mBlock
+ */
+ std::vector<std::shared_ptr<const C2Info>> mInfos;
+
+ /*
+ * C2AccessUnitInfos for the current buffer
+ */
+ std::vector<C2AccessUnitInfosStruct> mAccessUnitInfos;
+
+ /*
+ * Current tuning used to process this input work
+ */
+ C2LargeFrame::output mLargeFrameTuning;
+
+ /*
+ * Current output C2Work being processed
+ */
+ std::unique_ptr<C2Work> mLargeWork;
+
+ MultiAccessUnitInfo(C2WorkOrdinalStruct ordinal):inOrdinal(ordinal) {
+
+ }
+
+ /*
+ * Resets this frame
+ */
+ void reset();
+ };
+
+ /*
+ * Creates a linear block to be used with work
+ */
+ c2_status_t createLinearBlock(MultiAccessUnitInfo &frame);
+
+ /*
+ * Processes worklets from the component
+ */
+ c2_status_t processWorklets(MultiAccessUnitInfo &frame,
+ std::unique_ptr<C2Work> &work,
+ const std::function <void(std::unique_ptr<C2Work>&)> &addWork);
+
+ /*
+ * Finalizes the work to be send out.
+ */
+ c2_status_t finalizeWork(MultiAccessUnitInfo &frame,
+ uint32_t flags = 0, bool forceComplete = false);
+
+ /*
+ * Merges different access unit infos if possible
+ */
+ void mergeAccessUnitInfo(MultiAccessUnitInfo &frame,
+ uint32_t flags,
+ uint32_t size,
+ int64_t timestamp);
+
+ bool mInit;
+
+ // Interface of this module
+ std::shared_ptr<MultiAccessUnitInterface> mInterface;
+ // Local pool id used for output buffer allocation
+ C2BlockPool::local_id_t mBlockPoolId;
+ // C2Blockpool for output buffer allocation
+ std::shared_ptr<C2BlockPool> mLinearPool;
+ // Allocator for output buffer allocation
+ std::shared_ptr<C2Allocator> mLinearAllocator;
+ // FrameIndex for the current outgoing work
+ std::atomic_uint64_t mFrameIndex;
+ // Mutex to protect mFrameHolder
+ std::mutex mLock;
+ // List of Infos that contains the input and
+ // output work and buffer objects
+ std::list<MultiAccessUnitInfo> mFrameHolder;
+};
+
+} // namespace android
+
+#endif // CODEC2_COMMON_MULTI_ACCESSUNIT_HELPER_H
diff --git a/media/codec2/hal/hidl/1.0/utils/Android.bp b/media/codec2/hal/hidl/1.0/utils/Android.bp
index 2f2ecd1..9646a0b 100644
--- a/media/codec2/hal/hidl/1.0/utils/Android.bp
+++ b/media/codec2/hal/hidl/1.0/utils/Android.bp
@@ -52,7 +52,6 @@
],
}
-
// DO NOT DEPEND ON THIS DIRECTLY
// use libcodec2-hidl-defaults instead
cc_library {
diff --git a/media/codec2/hal/hidl/1.0/utils/Component.cpp b/media/codec2/hal/hidl/1.0/utils/Component.cpp
index 0aeed08..ebbaafc 100644
--- a/media/codec2/hal/hidl/1.0/utils/Component.cpp
+++ b/media/codec2/hal/hidl/1.0/utils/Component.cpp
@@ -135,6 +135,52 @@
wp<IComponentListener> mListener;
};
+// Component listener for handle multiple access-units
+struct MultiAccessUnitListener : public Component::Listener {
+ MultiAccessUnitListener(const sp<Component> &component,
+ const std::shared_ptr<MultiAccessUnitHelper> &handler):
+ Listener(component), mHandler(handler) {
+ }
+
+ virtual void onError_nb(
+ std::weak_ptr<C2Component> c2component,
+ uint32_t errorCode) override {
+ if (mHandler) {
+ std::list<std::unique_ptr<C2Work>> worklist;
+ mHandler->error(&worklist);
+ if (!worklist.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(worklist));
+ }
+ }
+ Listener::onError_nb(c2component, errorCode);
+ }
+
+ virtual void onTripped_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::vector<std::shared_ptr<C2SettingResult>> c2settingResult
+ ) override {
+ Listener::onTripped_nb(c2component,
+ c2settingResult);
+ }
+
+ virtual void onWorkDone_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::list<std::unique_ptr<C2Work>> c2workItems) override {
+ if (mHandler) {
+ std::list<std::unique_ptr<C2Work>> processedWork;
+ mHandler->gather(c2workItems, &processedWork);
+ if (!processedWork.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(processedWork));
+ }
+ } else {
+ Listener::onWorkDone_nb(c2component, std::move(c2workItems));
+ }
+ }
+
+ protected:
+ std::shared_ptr<MultiAccessUnitHelper> mHandler;
+};
+
// Component::Sink
struct Component::Sink : public IInputSink {
std::shared_ptr<Component> mComponent;
@@ -208,13 +254,37 @@
const sp<::android::hardware::media::bufferpool::V2_0::
IClientManager>& clientPoolManager)
: mComponent{component},
- mInterface{new ComponentInterface(component->intf(),
- store->getParameterCache())},
mListener{listener},
mStore{store},
mBufferPoolSender{clientPoolManager} {
// Retrieve supported parameters from store
// TODO: We could cache this per component/interface type
+ if (MultiAccessUnitHelper::isEnabledOnPlatform()) {
+ c2_status_t err = C2_OK;
+ C2ComponentDomainSetting domain;
+ std::vector<std::unique_ptr<C2Param>> heapParams;
+ err = component->intf()->query_vb({&domain}, {}, C2_MAY_BLOCK, &heapParams);
+ if (err == C2_OK && (domain.value == C2Component::DOMAIN_AUDIO)) {
+ std::vector<std::shared_ptr<C2ParamDescriptor>> params;
+ bool isComponentSupportsLargeAudioFrame = false;
+ component->intf()->querySupportedParams_nb(¶ms);
+ for (const auto ¶mDesc : params) {
+ if (paramDesc->name().compare(C2_PARAMKEY_OUTPUT_LARGE_FRAME) == 0) {
+ isComponentSupportsLargeAudioFrame = true;
+ LOG(VERBOSE) << "Underlying component supports large frame audio";
+ break;
+ }
+ }
+ if (!isComponentSupportsLargeAudioFrame) {
+ mMultiAccessUnitIntf = std::make_shared<MultiAccessUnitInterface>(
+ component->intf(),
+ std::static_pointer_cast<C2ReflectorHelper>(
+ GetCodec2PlatformComponentStore()->getParamReflector()));
+ }
+ }
+ }
+ mInterface = new ComponentInterface(
+ component->intf(), mMultiAccessUnitIntf, store->getParameterCache());
mInit = mInterface->status();
}
@@ -240,7 +310,6 @@
// Methods from ::android::hardware::media::c2::V1_0::IComponent
Return<Status> Component::queue(const WorkBundle& workBundle) {
std::list<std::unique_ptr<C2Work>> c2works;
-
if (!objcpy(&c2works, workBundle)) {
return Status::CORRUPTED;
}
@@ -252,7 +321,19 @@
registerFrameData(mListener, work->input);
}
}
-
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitHelper) {
+ std::list<std::list<std::unique_ptr<C2Work>>> c2worklists;
+ mMultiAccessUnitHelper->scatter(c2works, &c2worklists);
+ for (auto &c2worklist : c2worklists) {
+ err = mComponent->queue_nb(&c2worklist);
+ if (err != C2_OK) {
+ LOG(ERROR) << "Error Queuing to component.";
+ break;
+ }
+ }
+ return static_cast<Status>(err);
+ }
return static_cast<Status>(mComponent->queue_nb(&c2works));
}
@@ -261,6 +342,9 @@
c2_status_t c2res = mComponent->flush_sm(
C2Component::FLUSH_COMPONENT,
&c2flushedWorks);
+ if (mMultiAccessUnitHelper) {
+ c2res = mMultiAccessUnitHelper->flush(&c2flushedWorks);
+ }
// Unregister input buffers.
for (const std::unique_ptr<C2Work>& work : c2flushedWorks) {
@@ -469,6 +553,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
return status;
}
@@ -479,6 +566,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
return status;
}
@@ -501,8 +591,14 @@
}
void Component::initListener(const sp<Component>& self) {
- std::shared_ptr<C2Component::Listener> c2listener =
+ std::shared_ptr<C2Component::Listener> c2listener;
+ if (mMultiAccessUnitIntf) {
+ mMultiAccessUnitHelper = std::make_shared<MultiAccessUnitHelper>(mMultiAccessUnitIntf);
+ }
+ c2listener = mMultiAccessUnitHelper ?
+ std::make_shared<MultiAccessUnitListener>(self, mMultiAccessUnitHelper) :
std::make_shared<Listener>(self);
+
c2_status_t res = mComponent->setListener_vb(c2listener, C2_DONT_BLOCK);
if (res != C2_OK) {
mInit = res;
diff --git a/media/codec2/hal/hidl/1.0/utils/ComponentInterface.cpp b/media/codec2/hal/hidl/1.0/utils/ComponentInterface.cpp
index 12078e0..5a5e780 100644
--- a/media/codec2/hal/hidl/1.0/utils/ComponentInterface.cpp
+++ b/media/codec2/hal/hidl/1.0/utils/ComponentInterface.cpp
@@ -25,7 +25,6 @@
#include <hidl/HidlBinderSupport.h>
#include <utils/Timers.h>
-#include <C2BqBufferPriv.h>
#include <C2Debug.h>
#include <C2PlatformSupport.h>
@@ -45,9 +44,10 @@
// Implementation of ConfigurableC2Intf based on C2ComponentInterface
struct CompIntf : public ConfigurableC2Intf {
- CompIntf(const std::shared_ptr<C2ComponentInterface>& intf) :
+ CompIntf(const std::shared_ptr<C2ComponentInterface>& intf,
+ const std::shared_ptr<MultiAccessUnitInterface>& multiAccessUnitIntf):
ConfigurableC2Intf{intf->getName(), intf->getId()},
- mIntf{intf} {
+ mIntf{intf}, mMultiAccessUnitIntf{multiAccessUnitIntf} {
}
virtual c2_status_t config(
@@ -55,7 +55,34 @@
c2_blocking_t mayBlock,
std::vector<std::unique_ptr<C2SettingResult>>* const failures
) override {
- return mIntf->config_vb(params, mayBlock, failures);
+ std::vector<C2Param*> paramsToIntf;
+ std::vector<C2Param*> paramsToLargeFrameIntf;
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitIntf == nullptr) {
+ err = mIntf->config_vb(params, mayBlock, failures);
+ return err;
+ }
+ for (auto &p : params) {
+ if (mMultiAccessUnitIntf->isParamSupported(p->index())) {
+ paramsToLargeFrameIntf.push_back(p);
+ } else {
+ paramsToIntf.push_back(p);
+ }
+ }
+ c2_status_t err1 = C2_OK;
+ if (paramsToIntf.size() > 0) {
+ err1 = mIntf->config_vb(paramsToIntf, mayBlock, failures);
+ }
+ if (err1 != C2_OK) {
+ LOG(ERROR) << "We have a failed config";
+ }
+ c2_status_t err2 = C2_OK;
+ if (paramsToLargeFrameIntf.size() > 0) {
+ err2 = mMultiAccessUnitIntf->config(
+ paramsToLargeFrameIntf, mayBlock, failures);
+ }
+ // TODO: correct failure vector
+ return err1 != C2_OK ? err1 : err2;
}
virtual c2_status_t query(
@@ -63,33 +90,74 @@
c2_blocking_t mayBlock,
std::vector<std::unique_ptr<C2Param>>* const params
) const override {
- return mIntf->query_vb({}, indices, mayBlock, params);
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitIntf == nullptr) {
+ err = mIntf->query_vb({}, indices, mayBlock, params);
+ return err;
+ }
+ std::vector<C2Param::Index> paramsToIntf;
+ std::vector<C2Param::Index> paramsToLargeFrameIntf;
+ for (auto &i : indices) {
+ if (mMultiAccessUnitIntf->isParamSupported(i)) {
+ paramsToLargeFrameIntf.push_back(i);
+ } else {
+ paramsToIntf.push_back(i);
+ }
+ }
+ c2_status_t err1 = C2_OK;
+ if (paramsToIntf.size() > 0) {
+ err1 = mIntf->query_vb({}, paramsToIntf, mayBlock, params);
+ }
+ c2_status_t err2 = C2_OK;
+ if (paramsToLargeFrameIntf.size() > 0) {
+ err2 = mMultiAccessUnitIntf->query(
+ {}, paramsToLargeFrameIntf, mayBlock, params);
+ }
+ // TODO: correct failure vector
+ return err1 != C2_OK ? err1 : err2;
}
virtual c2_status_t querySupportedParams(
std::vector<std::shared_ptr<C2ParamDescriptor>>* const params
) const override {
- return mIntf->querySupportedParams_nb(params);
+ c2_status_t err = mIntf->querySupportedParams_nb(params);
+ if (mMultiAccessUnitIntf != nullptr) {
+ err = mMultiAccessUnitIntf->querySupportedParams(params);
+ }
+ return err;
}
virtual c2_status_t querySupportedValues(
std::vector<C2FieldSupportedValuesQuery>& fields,
c2_blocking_t mayBlock) const override {
- return mIntf->querySupportedValues_vb(fields, mayBlock);
+ c2_status_t err = mIntf->querySupportedValues_vb(fields, mayBlock);
+ if (mMultiAccessUnitIntf != nullptr) {
+ err = mMultiAccessUnitIntf->querySupportedValues(fields, mayBlock);
+ }
+ return err;
}
protected:
std::shared_ptr<C2ComponentInterface> mIntf;
+ std::shared_ptr<MultiAccessUnitInterface> mMultiAccessUnitIntf;
};
} // unnamed namespace
+
// ComponentInterface
ComponentInterface::ComponentInterface(
const std::shared_ptr<C2ComponentInterface>& intf,
+ const std::shared_ptr<ParameterCache>& cache):ComponentInterface(intf, nullptr, cache) {
+}
+
+ComponentInterface::ComponentInterface(
+ const std::shared_ptr<C2ComponentInterface>& intf,
+ const std::shared_ptr<MultiAccessUnitInterface>& multiAccessUnitIntf,
const std::shared_ptr<ParameterCache>& cache)
: mInterface{intf},
- mConfigurable{new CachedConfigurable(std::make_unique<CompIntf>(intf))} {
+ mConfigurable{new CachedConfigurable(
+ std::make_unique<CompIntf>(intf, multiAccessUnitIntf))} {
mInit = mConfigurable->init(cache);
}
diff --git a/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/Component.h b/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/Component.h
index 3f55618..aed94ec 100644
--- a/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/Component.h
+++ b/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/Component.h
@@ -30,6 +30,8 @@
#include <hidl/Status.h>
#include <hwbinder/IBinder.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2Component.h>
#include <C2Buffer.h>
#include <C2.h>
@@ -54,6 +56,8 @@
using ::android::hardware::IBinder;
using ::android::sp;
using ::android::wp;
+using ::android::MultiAccessUnitInterface;
+using ::android::MultiAccessUnitHelper;
struct ComponentStore;
@@ -113,6 +117,8 @@
std::shared_ptr<C2Component> mComponent;
sp<ComponentInterface> mInterface;
sp<IComponentListener> mListener;
+ std::shared_ptr<MultiAccessUnitInterface> mMultiAccessUnitIntf;
+ std::shared_ptr<MultiAccessUnitHelper> mMultiAccessUnitHelper;
sp<ComponentStore> mStore;
::android::hardware::media::c2::V1_0::utils::DefaultBufferPoolSender
mBufferPoolSender;
@@ -135,6 +141,8 @@
struct Listener;
+ friend struct MultiAccessUnitListener;
+
using HwDeathRecipient = ::android::hardware::hidl_death_recipient;
sp<HwDeathRecipient> mDeathRecipient;
bool mClientDied{false};
diff --git a/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentInterface.h b/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentInterface.h
index 9102f92..2995faf 100644
--- a/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentInterface.h
+++ b/media/codec2/hal/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentInterface.h
@@ -23,10 +23,15 @@
#include <android/hardware/media/c2/1.0/IComponentInterface.h>
#include <hidl/Status.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2Component.h>
#include <C2Buffer.h>
+#include <C2Config.h>
+#include <util/C2InterfaceHelper.h>
#include <C2.h>
+#include <set>
#include <memory>
namespace android {
@@ -39,6 +44,7 @@
using ::android::hardware::Return;
using ::android::hardware::Void;
using ::android::sp;
+using ::android::MultiAccessUnitInterface;
struct ComponentStore;
@@ -46,6 +52,11 @@
ComponentInterface(
const std::shared_ptr<C2ComponentInterface>& interface,
const std::shared_ptr<ParameterCache>& cache);
+
+ ComponentInterface(
+ const std::shared_ptr<C2ComponentInterface>& interface,
+ const std::shared_ptr<MultiAccessUnitInterface>& largeBufferIntf,
+ const std::shared_ptr<ParameterCache>& cache);
c2_status_t status() const;
virtual Return<sp<IConfigurable>> getConfigurable() override;
diff --git a/media/codec2/hal/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.cpp b/media/codec2/hal/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.cpp
index 92b0bf5..2da6501 100644
--- a/media/codec2/hal/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.cpp
+++ b/media/codec2/hal/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.cpp
@@ -17,7 +17,7 @@
//#define LOG_NDEBUG 0
#define LOG_TAG "media_c2_hidl_test_common"
#include <stdio.h>
-
+#include <numeric>
#include "media_c2_hidl_test_common.h"
#include <android/hardware/media/c2/1.0/IComponentStore.h>
@@ -221,6 +221,32 @@
return parameters;
}
+constexpr static std::initializer_list<std::pair<uint32_t, uint32_t>> flagList{
+ {(1 << VTS_BIT_FLAG_SYNC_FRAME), 0},
+ {(1 << VTS_BIT_FLAG_CSD_FRAME), C2FrameData::FLAG_CODEC_CONFIG},
+};
+
+/*
+ * This is a conversion function that can be used to convert
+ * VTS flags to C2 flags and vice-versa based on the initializer list.
+ * @param flags can be a C2 flag or a VTS flag
+ * @param toC2 if true, converts flags to a C2 flag
+ * if false, converts flags to a VTS flag
+ */
+static uint32_t convertFlags(uint32_t flags, bool toC2) {
+ return std::transform_reduce(
+ flagList.begin(), flagList.end(),
+ 0u,
+ std::bit_or{},
+ [flags, toC2](const std::pair<uint32_t, uint32_t> &entry) {
+ if (toC2) {
+ return (flags & entry.first) ? entry.second : 0;
+ } else {
+ return (flags & entry.second) ? entry.first : 0;
+ }
+ });
+}
+
// Populate Info vector and return number of CSDs
int32_t populateInfoVector(std::string info, android::Vector<FrameInfo>* frameInfo,
bool timestampDevTest, std::list<uint64_t>* timestampUslist) {
@@ -258,9 +284,9 @@
eleInfo >> bytesCount;
eleInfo >> flags;
eleInfo >> timestamp;
- vtsFlags = mapInfoFlagstoVtsFlags(flags);
+ uint32_t c2Flags = convertFlags(flags, true);
frameInfo->editItemAt(frameInfo->size() - 1).largeFrameInfo.push_back(
- {vtsFlags, static_cast<uint32_t>(bytesCount), timestamp});
+ {c2Flags, static_cast<uint32_t>(bytesCount), timestamp});
}
}
}
@@ -298,5 +324,8 @@
else if (infoFlags == 0x10) return (1 << VTS_BIT_FLAG_NO_SHOW_FRAME);
else if (infoFlags == 0x20) return (1 << VTS_BIT_FLAG_CSD_FRAME);
else if (infoFlags == 0x40) return (1 << VTS_BIT_FLAG_LARGE_AUDIO_FRAME);
+ else if (infoFlags == 0x80) {
+ return (1 << VTS_BIT_FLAG_LARGE_AUDIO_FRAME) | (1 << VTS_BIT_FLAG_SYNC_FRAME);
+ }
return 0xFF;
}
diff --git a/media/codec2/hal/hidl/1.0/vts/functional/res/bbb_raw_1ch_8khz_s32le_largeframe.info b/media/codec2/hal/hidl/1.0/vts/functional/res/bbb_raw_1ch_8khz_s32le_largeframe.info
index 291e323..ee59a8e 100644
--- a/media/codec2/hal/hidl/1.0/vts/functional/res/bbb_raw_1ch_8khz_s32le_largeframe.info
+++ b/media/codec2/hal/hidl/1.0/vts/functional/res/bbb_raw_1ch_8khz_s32le_largeframe.info
@@ -1,5 +1,5 @@
-16384 64 0 1 16384 1 0
-49152 64 1024000 3 16384 1 1024000 16384 1 2048000 16384 1 3072000
-32768 64 4096000 2 16384 1 4096000 16384 1 5120000
-49152 64 6144000 3 16384 1 6144000 16384 1 7168000 16384 1 8192000
-10924 64 9216000 1 10924 1 9216000
+16384 128 0 1 16384 1 0
+49152 128 1024000 3 16384 1 1024000 16384 1 2048000 16384 1 3072000
+32768 128 4096000 2 16384 1 4096000 16384 1 5120000
+49152 128 6144000 3 16384 1 6144000 16384 1 7168000 16384 1 8192000
+10924 128 9216000 1 10924 1 9216000
diff --git a/media/codec2/hal/hidl/1.1/utils/Android.bp b/media/codec2/hal/hidl/1.1/utils/Android.bp
index 4f86511..d8b5db5 100644
--- a/media/codec2/hal/hidl/1.1/utils/Android.bp
+++ b/media/codec2/hal/hidl/1.1/utils/Android.bp
@@ -54,7 +54,6 @@
],
}
-
// DO NOT DEPEND ON THIS DIRECTLY
// use libcodec2-hidl-defaults instead
cc_library {
@@ -66,7 +65,6 @@
"com.android.media.swcodec",
],
-
defaults: ["hidl_defaults"],
srcs: [
@@ -97,6 +95,7 @@
"android.hardware.media.omx@1.0",
"libbase",
"libcodec2",
+ "libcodec2_hal_common",
"libcodec2_hidl@1.0",
"libcodec2_hidl_plugin_stub",
"libcodec2_vndk",
@@ -173,4 +172,3 @@
"libhidlbase",
],
}
-
diff --git a/media/codec2/hal/hidl/1.1/utils/Component.cpp b/media/codec2/hal/hidl/1.1/utils/Component.cpp
index d0f4f19..5073983 100644
--- a/media/codec2/hal/hidl/1.1/utils/Component.cpp
+++ b/media/codec2/hal/hidl/1.1/utils/Component.cpp
@@ -29,6 +29,8 @@
#include <hidl/HidlBinderSupport.h>
#include <utils/Timers.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2BqBufferPriv.h>
#include <C2Debug.h>
#include <C2PlatformSupport.h>
@@ -44,6 +46,8 @@
namespace utils {
using namespace ::android;
+using ::android::MultiAccessUnitInterface;
+using ::android::MultiAccessUnitHelper;
// ComponentListener wrapper
struct Component::Listener : public C2Component::Listener {
@@ -135,6 +139,52 @@
wp<IComponentListener> mListener;
};
+// Component listener for handle multiple access-units
+struct MultiAccessUnitListener : public Component::Listener {
+ MultiAccessUnitListener(const sp<Component> &component,
+ const std::shared_ptr<MultiAccessUnitHelper> &helper):
+ Listener(component), mHelper(helper) {
+ }
+
+ virtual void onError_nb(
+ std::weak_ptr<C2Component> c2component,
+ uint32_t errorCode) override {
+ if (mHelper) {
+ std::list<std::unique_ptr<C2Work>> worklist;
+ mHelper->error(&worklist);
+ if (!worklist.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(worklist));
+ }
+ }
+ Listener::onError_nb(c2component, errorCode);
+ }
+
+ virtual void onTripped_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::vector<std::shared_ptr<C2SettingResult>> c2settingResult
+ ) override {
+ Listener::onTripped_nb(c2component,
+ c2settingResult);
+ }
+
+ virtual void onWorkDone_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::list<std::unique_ptr<C2Work>> c2workItems) override {
+ if (mHelper) {
+ std::list<std::unique_ptr<C2Work>> processedWork;
+ mHelper->gather(c2workItems, &processedWork);
+ if (!processedWork.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(processedWork));
+ }
+ } else {
+ Listener::onWorkDone_nb(c2component, std::move(c2workItems));
+ }
+ }
+
+ protected:
+ std::shared_ptr<MultiAccessUnitHelper> mHelper;
+};
+
// Component::Sink
struct Component::Sink : public IInputSink {
std::shared_ptr<Component> mComponent;
@@ -208,13 +258,37 @@
const sp<::android::hardware::media::bufferpool::V2_0::
IClientManager>& clientPoolManager)
: mComponent{component},
- mInterface{new ComponentInterface(component->intf(),
- store->getParameterCache())},
mListener{listener},
mStore{store},
mBufferPoolSender{clientPoolManager} {
// Retrieve supported parameters from store
// TODO: We could cache this per component/interface type
+ if (MultiAccessUnitHelper::isEnabledOnPlatform()) {
+ c2_status_t err = C2_OK;
+ C2ComponentDomainSetting domain;
+ std::vector<std::unique_ptr<C2Param>> heapParams;
+ err = component->intf()->query_vb({&domain}, {}, C2_MAY_BLOCK, &heapParams);
+ if (err == C2_OK && (domain.value == C2Component::DOMAIN_AUDIO)) {
+ std::vector<std::shared_ptr<C2ParamDescriptor>> params;
+ bool isComponentSupportsLargeAudioFrame = false;
+ component->intf()->querySupportedParams_nb(¶ms);
+ for (const auto ¶mDesc : params) {
+ if (paramDesc->name().compare(C2_PARAMKEY_OUTPUT_LARGE_FRAME) == 0) {
+ isComponentSupportsLargeAudioFrame = true;
+ LOG(VERBOSE) << "Underlying component supports large frame audio";
+ break;
+ }
+ }
+ if (!isComponentSupportsLargeAudioFrame) {
+ mMultiAccessUnitIntf = std::make_shared<MultiAccessUnitInterface>(
+ component->intf(),
+ std::static_pointer_cast<C2ReflectorHelper>(
+ GetCodec2PlatformComponentStore()->getParamReflector()));
+ }
+ }
+ }
+ mInterface = new ComponentInterface(
+ component->intf(), mMultiAccessUnitIntf, store->getParameterCache());
mInit = mInterface->status();
}
@@ -252,6 +326,19 @@
registerFrameData(mListener, work->input);
}
}
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitHelper) {
+ std::list<std::list<std::unique_ptr<C2Work>>> c2worklists;
+ mMultiAccessUnitHelper->scatter(c2works, &c2worklists);
+ for (auto &c2worklist : c2worklists) {
+ err = mComponent->queue_nb(&c2worklist);
+ if (err != C2_OK) {
+ LOG(ERROR) << "Error Queuing to component.";
+ break;
+ }
+ }
+ return static_cast<Status>(err);
+ }
return static_cast<Status>(mComponent->queue_nb(&c2works));
}
@@ -261,6 +348,9 @@
c2_status_t c2res = mComponent->flush_sm(
C2Component::FLUSH_COMPONENT,
&c2flushedWorks);
+ if (mMultiAccessUnitHelper) {
+ c2res = mMultiAccessUnitHelper->flush(&c2flushedWorks);
+ }
// Unregister input buffers.
for (const std::unique_ptr<C2Work>& work : c2flushedWorks) {
@@ -469,6 +559,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
return status;
}
@@ -479,6 +572,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
return status;
}
@@ -508,7 +604,12 @@
}
void Component::initListener(const sp<Component>& self) {
- std::shared_ptr<C2Component::Listener> c2listener =
+ std::shared_ptr<C2Component::Listener> c2listener;
+ if (mMultiAccessUnitIntf) {
+ mMultiAccessUnitHelper = std::make_shared<MultiAccessUnitHelper>(mMultiAccessUnitIntf);
+ }
+ c2listener = mMultiAccessUnitHelper ?
+ std::make_shared<MultiAccessUnitListener>(self, mMultiAccessUnitHelper) :
std::make_shared<Listener>(self);
c2_status_t res = mComponent->setListener_vb(c2listener, C2_DONT_BLOCK);
if (res != C2_OK) {
diff --git a/media/codec2/hal/hidl/1.1/utils/include/codec2/hidl/1.1/Component.h b/media/codec2/hal/hidl/1.1/utils/include/codec2/hidl/1.1/Component.h
index f16de24..8f0478f 100644
--- a/media/codec2/hal/hidl/1.1/utils/include/codec2/hidl/1.1/Component.h
+++ b/media/codec2/hal/hidl/1.1/utils/include/codec2/hidl/1.1/Component.h
@@ -29,6 +29,8 @@
#include <hidl/Status.h>
#include <hwbinder/IBinder.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2Component.h>
#include <C2Buffer.h>
#include <C2.h>
@@ -57,6 +59,8 @@
using ::android::hardware::IBinder;
using ::android::sp;
using ::android::wp;
+using ::android::MultiAccessUnitInterface;
+using ::android::MultiAccessUnitHelper;
struct ComponentStore;
@@ -118,6 +122,8 @@
std::shared_ptr<C2Component> mComponent;
sp<ComponentInterface> mInterface;
sp<IComponentListener> mListener;
+ std::shared_ptr<MultiAccessUnitInterface> mMultiAccessUnitIntf;
+ std::shared_ptr<MultiAccessUnitHelper> mMultiAccessUnitHelper;
sp<ComponentStore> mStore;
::android::hardware::media::c2::V1_1::utils::DefaultBufferPoolSender
mBufferPoolSender;
@@ -140,6 +146,8 @@
struct Listener;
+ friend struct MultiAccessUnitListener;
+
using HwDeathRecipient = ::android::hardware::hidl_death_recipient;
sp<HwDeathRecipient> mDeathRecipient;
bool mClientDied{false};
diff --git a/media/codec2/hal/hidl/1.2/utils/Android.bp b/media/codec2/hal/hidl/1.2/utils/Android.bp
index b92dc07..a339946 100644
--- a/media/codec2/hal/hidl/1.2/utils/Android.bp
+++ b/media/codec2/hal/hidl/1.2/utils/Android.bp
@@ -58,7 +58,6 @@
],
}
-
// DO NOT DEPEND ON THIS DIRECTLY
// use libcodec2-hidl-defaults instead
cc_library {
@@ -102,6 +101,7 @@
"android.hardware.media.omx@1.0",
"libbase",
"libcodec2",
+ "libcodec2_hal_common",
"libcodec2_hidl@1.0",
"libcodec2_hidl@1.1",
"libcodec2_hidl_plugin_stub",
@@ -197,4 +197,3 @@
name: "libcodec2-hidl-client-defaults",
defaults: ["libcodec2-hidl-client-defaults@1.2"],
}
-
diff --git a/media/codec2/hal/hidl/1.2/utils/Component.cpp b/media/codec2/hal/hidl/1.2/utils/Component.cpp
index 036c900..bbdbef5 100644
--- a/media/codec2/hal/hidl/1.2/utils/Component.cpp
+++ b/media/codec2/hal/hidl/1.2/utils/Component.cpp
@@ -44,6 +44,8 @@
namespace utils {
using namespace ::android;
+using ::android::MultiAccessUnitInterface;
+using ::android::MultiAccessUnitHelper;
// ComponentListener wrapper
struct Component::Listener : public C2Component::Listener {
@@ -135,6 +137,52 @@
wp<IComponentListener> mListener;
};
+// Component listener for handle multiple access-units
+struct MultiAccessUnitListener : public Component::Listener {
+ MultiAccessUnitListener(const sp<Component> &component,
+ const std::shared_ptr<MultiAccessUnitHelper> &helper):
+ Listener(component), mHelper(helper) {
+ }
+
+ virtual void onError_nb(
+ std::weak_ptr<C2Component> c2component,
+ uint32_t errorCode) override {
+ if (mHelper) {
+ std::list<std::unique_ptr<C2Work>> worklist;
+ mHelper->error(&worklist);
+ if (!worklist.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(worklist));
+ }
+ }
+ Listener::onError_nb(c2component, errorCode);
+ }
+
+ virtual void onTripped_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::vector<std::shared_ptr<C2SettingResult>> c2settingResult
+ ) override {
+ Listener::onTripped_nb(c2component,
+ c2settingResult);
+ }
+
+ virtual void onWorkDone_nb(
+ std::weak_ptr<C2Component> c2component,
+ std::list<std::unique_ptr<C2Work>> c2workItems) override {
+ if (mHelper) {
+ std::list<std::unique_ptr<C2Work>> processedWork;
+ mHelper->gather(c2workItems, &processedWork);
+ if (!processedWork.empty()) {
+ Listener::onWorkDone_nb(c2component, std::move(processedWork));
+ }
+ } else {
+ Listener::onWorkDone_nb(c2component, std::move(c2workItems));
+ }
+ }
+
+ protected:
+ std::shared_ptr<MultiAccessUnitHelper> mHelper;
+};
+
// Component::Sink
struct Component::Sink : public IInputSink {
std::shared_ptr<Component> mComponent;
@@ -208,13 +256,37 @@
const sp<::android::hardware::media::bufferpool::V2_0::
IClientManager>& clientPoolManager)
: mComponent{component},
- mInterface{new ComponentInterface(component->intf(),
- store->getParameterCache())},
mListener{listener},
mStore{store},
mBufferPoolSender{clientPoolManager} {
// Retrieve supported parameters from store
// TODO: We could cache this per component/interface type
+ if (MultiAccessUnitHelper::isEnabledOnPlatform()) {
+ c2_status_t err = C2_OK;
+ C2ComponentDomainSetting domain;
+ std::vector<std::unique_ptr<C2Param>> heapParams;
+ err = component->intf()->query_vb({&domain}, {}, C2_MAY_BLOCK, &heapParams);
+ if (err == C2_OK && (domain.value == C2Component::DOMAIN_AUDIO)) {
+ std::vector<std::shared_ptr<C2ParamDescriptor>> params;
+ bool isComponentSupportsLargeAudioFrame = false;
+ component->intf()->querySupportedParams_nb(¶ms);
+ for (const auto ¶mDesc : params) {
+ if (paramDesc->name().compare(C2_PARAMKEY_OUTPUT_LARGE_FRAME) == 0) {
+ isComponentSupportsLargeAudioFrame = true;
+ LOG(VERBOSE) << "Underlying component supports large frame audio";
+ break;
+ }
+ }
+ if (!isComponentSupportsLargeAudioFrame) {
+ mMultiAccessUnitIntf = std::make_shared<MultiAccessUnitInterface>(
+ component->intf(),
+ std::static_pointer_cast<C2ReflectorHelper>(
+ GetCodec2PlatformComponentStore()->getParamReflector()));
+ }
+ }
+ }
+ mInterface = new ComponentInterface(
+ component->intf(), mMultiAccessUnitIntf, store->getParameterCache());
mInit = mInterface->status();
}
@@ -252,7 +324,19 @@
registerFrameData(mListener, work->input);
}
}
-
+ c2_status_t err = C2_OK;
+ if (mMultiAccessUnitHelper) {
+ std::list<std::list<std::unique_ptr<C2Work>>> c2worklists;
+ mMultiAccessUnitHelper->scatter(c2works, &c2worklists);
+ for (auto &c2worklist : c2worklists) {
+ err = mComponent->queue_nb(&c2worklist);
+ if (err != C2_OK) {
+ LOG(ERROR) << "Error Queuing to component.";
+ break;
+ }
+ }
+ return static_cast<Status>(err);
+ }
return static_cast<Status>(mComponent->queue_nb(&c2works));
}
@@ -261,7 +345,9 @@
c2_status_t c2res = mComponent->flush_sm(
C2Component::FLUSH_COMPONENT,
&c2flushedWorks);
-
+ if (mMultiAccessUnitHelper) {
+ c2res = mMultiAccessUnitHelper->flush(&c2flushedWorks);
+ }
// Unregister input buffers.
for (const std::unique_ptr<C2Work>& work : c2flushedWorks) {
if (work) {
@@ -469,6 +555,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
return status;
}
@@ -479,6 +568,9 @@
std::lock_guard<std::mutex> lock(mBlockPoolsMutex);
mBlockPools.clear();
}
+ if (mMultiAccessUnitHelper) {
+ mMultiAccessUnitHelper->reset();
+ }
InputBufferManager::unregisterFrameData(mListener);
return status;
}
@@ -539,7 +631,12 @@
}
void Component::initListener(const sp<Component>& self) {
- std::shared_ptr<C2Component::Listener> c2listener =
+ std::shared_ptr<C2Component::Listener> c2listener;
+ if (mMultiAccessUnitIntf) {
+ mMultiAccessUnitHelper = std::make_shared<MultiAccessUnitHelper>(mMultiAccessUnitIntf);
+ }
+ c2listener = mMultiAccessUnitHelper ?
+ std::make_shared<MultiAccessUnitListener>(self, mMultiAccessUnitHelper) :
std::make_shared<Listener>(self);
c2_status_t res = mComponent->setListener_vb(c2listener, C2_DONT_BLOCK);
if (res != C2_OK) {
diff --git a/media/codec2/hal/hidl/1.2/utils/include/codec2/hidl/1.2/Component.h b/media/codec2/hal/hidl/1.2/utils/include/codec2/hidl/1.2/Component.h
index 6a73392..f2b77bc 100644
--- a/media/codec2/hal/hidl/1.2/utils/include/codec2/hidl/1.2/Component.h
+++ b/media/codec2/hal/hidl/1.2/utils/include/codec2/hidl/1.2/Component.h
@@ -29,6 +29,8 @@
#include <hidl/Status.h>
#include <hwbinder/IBinder.h>
+#include <codec2/common/MultiAccessUnitHelper.h>
+
#include <C2Component.h>
#include <C2Buffer.h>
#include <C2.h>
@@ -57,6 +59,8 @@
using ::android::hardware::IBinder;
using ::android::sp;
using ::android::wp;
+using ::android::MultiAccessUnitInterface;
+using ::android::MultiAccessUnitHelper;
struct ComponentStore;
@@ -123,6 +127,8 @@
std::shared_ptr<C2Component> mComponent;
sp<ComponentInterface> mInterface;
sp<IComponentListener> mListener;
+ std::shared_ptr<MultiAccessUnitInterface> mMultiAccessUnitIntf;
+ std::shared_ptr<MultiAccessUnitHelper> mMultiAccessUnitHelper;
sp<ComponentStore> mStore;
::android::hardware::media::c2::V1_2::utils::DefaultBufferPoolSender
mBufferPoolSender;
@@ -145,6 +151,8 @@
struct Listener;
+ friend struct MultiAccessUnitListener;
+
using HwDeathRecipient = ::android::hardware::hidl_death_recipient;
sp<HwDeathRecipient> mDeathRecipient;
bool mClientDied{false};
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.cpp b/media/codec2/sfplugin/CCodecBufferChannel.cpp
index 6e6d3f7..7b1721e 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.cpp
+++ b/media/codec2/sfplugin/CCodecBufferChannel.cpp
@@ -90,6 +90,28 @@
return v == "true";
}
+// Flags can come with individual BufferInfos
+// when used with large frame audio
+constexpr static std::initializer_list<std::pair<uint32_t, uint32_t>> flagList = {
+ {BUFFER_FLAG_CODEC_CONFIG, C2FrameData::FLAG_CODEC_CONFIG},
+ {BUFFER_FLAG_END_OF_STREAM, C2FrameData::FLAG_END_OF_STREAM},
+ {BUFFER_FLAG_DECODE_ONLY, C2FrameData::FLAG_DROP_FRAME}
+};
+
+static uint32_t convertFlags(uint32_t flags, bool toC2) {
+ return std::transform_reduce(
+ flagList.begin(), flagList.end(),
+ 0u,
+ std::bit_or{},
+ [flags, toC2](const std::pair<uint32_t, uint32_t> &entry) {
+ if (toC2) {
+ return (flags & entry.first) ? entry.second : 0;
+ } else {
+ return (flags & entry.second) ? entry.first : 0;
+ }
+ });
+}
+
} // namespace
CCodecBufferChannel::QueueGuard::QueueGuard(
@@ -245,7 +267,8 @@
if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
flags |= C2FrameData::FLAG_DROP_FRAME;
}
- ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
+ ALOGV("[%s] queueInputBuffer: buffer->size() = %zu time: %lld",
+ mName, buffer->size(), (long long)timeUs);
std::list<std::unique_ptr<C2Work>> items;
std::unique_ptr<C2Work> work(new C2Work);
work->input.ordinal.timestamp = timeUs;
@@ -296,6 +319,34 @@
uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
output->rotation[frameIndex] = rotation;
}
+ sp<RefBase> obj;
+ if (buffer->meta()->findObject("accessUnitInfo", &obj)) {
+ ALOGV("Filling C2Info from multiple access units");
+ sp<WrapperObject<std::vector<AccessUnitInfo>>> infos{
+ (decltype(infos.get()))obj.get()};
+ std::vector<AccessUnitInfo> &accessUnitInfoVec = infos->value;
+ std::vector<C2AccessUnitInfosStruct> multipleAccessUnitInfos;
+ uint32_t outFlags = 0;
+ for (int i = 0; i < accessUnitInfoVec.size(); i++) {
+ outFlags = 0;
+ outFlags = convertFlags(accessUnitInfoVec[i].mFlags, true);
+ if (eos && (outFlags & C2FrameData::FLAG_END_OF_STREAM)) {
+ outFlags &= (~C2FrameData::FLAG_END_OF_STREAM);
+ }
+ multipleAccessUnitInfos.emplace_back(
+ outFlags,
+ accessUnitInfoVec[i].mSize,
+ accessUnitInfoVec[i].mTimestamp);
+ ALOGV("%d) flags: %d, size: %d, time: %llu",
+ i, outFlags, accessUnitInfoVec[i].mSize,
+ (long long)accessUnitInfoVec[i].mTimestamp);
+
+ }
+ const std::shared_ptr<C2AccessUnitInfos::input> c2AccessUnitInfos =
+ C2AccessUnitInfos::input::AllocShared(
+ multipleAccessUnitInfos.size(), 0u, multipleAccessUnitInfos);
+ c2buffer->setInfo(c2AccessUnitInfos);
+ }
work->input.buffers.push_back(c2buffer);
if (encryptedBlock) {
work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
@@ -2265,12 +2316,34 @@
case OutputBuffers::DISCARD:
break;
case OutputBuffers::NOTIFY_CLIENT:
+ {
// TRICKY: we want popped buffers reported in order, so sending
// the callback while holding the lock here. This assumes that
// onOutputBufferAvailable() does not block. onOutputBufferAvailable()
// callbacks are always sent with the Output lock held.
+ if (c2Buffer) {
+ std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
+ std::static_pointer_cast<const C2AccessUnitInfos::output>(
+ c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
+ if (bufferMetadata && bufferMetadata->flexCount() > 0) {
+ uint32_t flag = 0;
+ std::vector<AccessUnitInfo> accessUnitInfos;
+ for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
+ const C2AccessUnitInfosStruct &bufferMetadataStruct =
+ bufferMetadata->m.values[nMeta];
+ flag = convertFlags(bufferMetadataStruct.flags, false);
+ accessUnitInfos.emplace_back(flag,
+ static_cast<size_t>(bufferMetadataStruct.size),
+ static_cast<size_t>(bufferMetadataStruct.timestamp));
+ }
+ sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
+ new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
+ outBuffer->meta()->setObject("accessUnitInfo", obj);
+ }
+ }
mCallback->onOutputBufferAvailable(index, outBuffer);
break;
+ }
case OutputBuffers::REALLOCATE:
if (++reallocTryNum > kMaxReallocTry) {
output.unlock();
diff --git a/media/codec2/sfplugin/CCodecBuffers.cpp b/media/codec2/sfplugin/CCodecBuffers.cpp
index 670923b..8a48777 100644
--- a/media/codec2/sfplugin/CCodecBuffers.cpp
+++ b/media/codec2/sfplugin/CCodecBuffers.cpp
@@ -18,11 +18,14 @@
#define LOG_TAG "CCodecBuffers"
#include <utils/Log.h>
+#include <numeric>
+
#include <C2AllocatorGralloc.h>
#include <C2PlatformSupport.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/MediaDefs.h>
+#include <media/stagefright/CodecBase.h>
#include <media/stagefright/MediaCodecConstants.h>
#include <media/stagefright/SkipCutBuffer.h>
#include <mediadrm/ICrypto.h>
@@ -147,6 +150,165 @@
return copy;
}
+// MultiAccessUnitSkipCutBuffer for buffer and bufferInfos
+
+class MultiAccessUnitSkipCutBuffer : public SkipCutBuffer {
+
+public:
+ explicit MultiAccessUnitSkipCutBuffer(
+ int32_t skip, int32_t cut, size_t num16BitChannels):
+ SkipCutBuffer(skip, cut, num16BitChannels),
+ mFrontPaddingDelay(0), mSize(0) {
+ }
+
+ virtual ~MultiAccessUnitSkipCutBuffer() {
+
+ }
+
+ void submitMultiAccessUnits(
+ const sp<MediaCodecBuffer>& buffer,
+ int32_t sampleRate, size_t num16BitChannels,
+ std::shared_ptr<const C2AccessUnitInfos::output> &infos) {
+ if (infos == nullptr) {
+ // there is nothing to do more.
+ SkipCutBuffer::submit(buffer);
+ return;
+ }
+ typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
+ CHECK_EQ(mSize, SkipCutBuffer::size());
+ sp<BufferInfosWrapper> bufferInfos{new BufferInfosWrapper(decltype(bufferInfos->value)())};
+ uint32_t availableSize = buffer->size() + SkipCutBuffer::size();
+ uint32_t frontPadding = mFrontPadding;
+ int32_t lastEmptyAccessUnitIndex = -1;
+ int64_t byteInUs = 0;
+ if (sampleRate > 0 && num16BitChannels > 0) {
+ byteInUs = (1000000u / (sampleRate * num16BitChannels * 2));
+ }
+ if (frontPadding > 0) {
+ mInfos.clear();
+ mSize = 0;
+ }
+ for (int i = 0 ; i < infos->flexCount() && frontPadding > 0; i++) {
+ uint32_t flagsInPadding = 0;
+ int64_t timeInPadding = 0;
+ if (infos->m.values[i].size <= frontPadding) {
+ // we have more front padding so this buffer is not going to be used.
+ int32_t consumed = infos->m.values[i].size;
+ frontPadding -= consumed;
+ mFrontPaddingDelay += byteInUs * (consumed);
+ availableSize -= consumed;
+ flagsInPadding |= toMediaCodecFlags(infos->m.values[i].flags);
+ timeInPadding = infos->m.values[i].timestamp;
+ } else {
+ C2AccessUnitInfosStruct info = infos->m.values[i];
+ mFrontPaddingDelay += byteInUs * (frontPadding);
+ info.size -= frontPadding;
+ info.timestamp -= mFrontPaddingDelay;
+ availableSize -= frontPadding;
+ flagsInPadding |= toMediaCodecFlags(infos->m.values[i].flags);
+ timeInPadding = infos->m.values[i].timestamp;
+ frontPadding = 0;
+ mInfos.push_back(info);
+ mSize += info.size;
+ }
+ if (flagsInPadding != 0) {
+ bufferInfos->value.emplace_back(
+ flagsInPadding, 0, timeInPadding);
+ }
+ lastEmptyAccessUnitIndex = i;
+ }
+ if (frontPadding <= 0) {
+ // process what's already in the buffer first
+ auto it = mInfos.begin();
+ while (it != mInfos.end() && availableSize > mBackPadding) {
+ // we have samples to send out.
+ if ((availableSize - it->size) >= mBackPadding) {
+ // this is totally used here.
+ int32_t consumed = it->size;
+ bufferInfos->value.emplace_back(
+ toMediaCodecFlags(it->flags), consumed, it->timestamp);
+ availableSize -= consumed;
+ mSize -= consumed;
+ it = mInfos.erase(it);
+ } else {
+ int32_t consumed = availableSize - mBackPadding;
+ bufferInfos->value.emplace_back(
+ toMediaCodecFlags(it->flags),
+ consumed,
+ it->timestamp);
+ it->size -= consumed;
+ it->timestamp += consumed * byteInUs;
+ availableSize -= consumed;
+ mSize -= consumed;
+ it++;
+ }
+ }
+ // if buffer has more process all of it and keep the remaining info.
+ for (int i = (lastEmptyAccessUnitIndex + 1) ; i < infos->flexCount() ; i++) {
+ // upddate updatedInfo and mInfos
+ if (availableSize > mBackPadding) {
+ // we have to take data from the new buffer.
+ if (availableSize - infos->m.values[i].size >= mBackPadding) {
+ // we are using this info
+ int32_t consumed = infos->m.values[i].size;
+ bufferInfos->value.emplace_back(
+ toMediaCodecFlags(infos->m.values[i].flags),
+ consumed,
+ infos->m.values[i].timestamp - mFrontPaddingDelay);
+ availableSize -= consumed;
+ } else {
+ // if we need to update the size
+ C2AccessUnitInfosStruct info = infos->m.values[i];
+ int32_t consumed = availableSize - mBackPadding;
+ bufferInfos->value.emplace_back(
+ toMediaCodecFlags(infos->m.values[i].flags),
+ consumed,
+ infos->m.values[i].timestamp - mFrontPaddingDelay);
+ info.size -= consumed;
+ info.timestamp = info.timestamp - mFrontPaddingDelay +
+ consumed * byteInUs;
+ mInfos.push_back(info);
+ availableSize -= consumed;
+ mSize += info.size;
+ }
+ } else {
+ // we have to maintain infos
+ C2AccessUnitInfosStruct info = infos->m.values[i];
+ info.timestamp -= mFrontPaddingDelay;
+ mInfos.push_back(info);
+ mSize += info.size;
+ }
+ }
+ }
+ SkipCutBuffer::submit(buffer);
+ infos = nullptr;
+ if (!bufferInfos->value.empty()) {
+ buffer->meta()->setObject("accessUnitInfo", bufferInfos);
+ }
+ }
+protected:
+ // Flags can come with individual BufferInfos
+ // when used with large frame audio
+ constexpr static std::initializer_list<std::pair<uint32_t, uint32_t>> flagList = {
+ {BUFFER_FLAG_CODEC_CONFIG, C2FrameData::FLAG_CODEC_CONFIG},
+ {BUFFER_FLAG_END_OF_STREAM, C2FrameData::FLAG_END_OF_STREAM},
+ {BUFFER_FLAG_DECODE_ONLY, C2FrameData::FLAG_DROP_FRAME}
+ };
+
+ static uint32_t toMediaCodecFlags(uint32_t flags) {
+ return std::transform_reduce(
+ flagList.begin(), flagList.end(),
+ 0u,
+ std::bit_or{},
+ [flags](const std::pair<uint32_t, uint32_t> &entry) {
+ return (flags & entry.second) ? entry.first : 0;
+ });
+ }
+ std::list<C2AccessUnitInfosStruct> mInfos;
+ int64_t mFrontPaddingDelay;
+ size_t mSize;
+};
+
// OutputBuffers
OutputBuffers::OutputBuffers(const char *componentName, const char *name)
@@ -201,6 +363,15 @@
}
}
+bool OutputBuffers::submit(const sp<MediaCodecBuffer> &buffer, int32_t sampleRate,
+ int32_t channelCount, std::shared_ptr<const C2AccessUnitInfos::output> &infos) {
+ if (mSkipCutBuffer == nullptr) {
+ return false;
+ }
+ mSkipCutBuffer->submitMultiAccessUnits(buffer, sampleRate, channelCount, infos);
+ return true;
+}
+
void OutputBuffers::setSkipCutBuffer(int32_t skip, int32_t cut) {
if (mSkipCutBuffer != nullptr) {
size_t prevSize = mSkipCutBuffer->size();
@@ -208,7 +379,7 @@
ALOGD("[%s] Replacing SkipCutBuffer holding %zu bytes", mName, prevSize);
}
}
- mSkipCutBuffer = new SkipCutBuffer(skip, cut, mChannelCount);
+ mSkipCutBuffer = new MultiAccessUnitSkipCutBuffer(skip, cut, mChannelCount);
}
bool OutputBuffers::convert(
@@ -1160,7 +1331,16 @@
ALOGD("[%s] copy buffer failed", mName);
return WOULD_BLOCK;
}
- submit(c2Buffer);
+ if (buffer && buffer->hasInfo(C2AccessUnitInfos::output::PARAM_TYPE)) {
+ std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
+ std::static_pointer_cast<const C2AccessUnitInfos::output>(
+ buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
+ if (submit(c2Buffer, mSampleRate, mChannelCount, bufferMetadata)) {
+ buffer->removeInfo(C2AccessUnitInfos::output::PARAM_TYPE);
+ }
+ } else {
+ submit(c2Buffer);
+ }
handleImageData(c2Buffer);
*clientBuffer = c2Buffer;
ALOGV("[%s] grabbed buffer %zu", mName, *index);
diff --git a/media/codec2/sfplugin/CCodecBuffers.h b/media/codec2/sfplugin/CCodecBuffers.h
index cbef644..f0936bc 100644
--- a/media/codec2/sfplugin/CCodecBuffers.h
+++ b/media/codec2/sfplugin/CCodecBuffers.h
@@ -20,6 +20,7 @@
#include <optional>
#include <string>
+#include <vector>
#include <C2Config.h>
#include <DataConverter.h>
@@ -33,6 +34,8 @@
struct ICrypto;
class MemoryDealer;
class SkipCutBuffer;
+class MultiAccessUnitSkipCutBuffer;
+struct AccessUnitInfo;
constexpr size_t kLinearBufferSize = 1048576;
// This can fit an 8K frame.
@@ -382,13 +385,17 @@
sp<MediaCodecBuffer>* outBuffer);
protected:
- sp<SkipCutBuffer> mSkipCutBuffer;
+
+ sp<MultiAccessUnitSkipCutBuffer> mSkipCutBuffer;
/**
* Update the SkipCutBuffer object. No-op if it's never initialized.
*/
void updateSkipCutBuffer(int32_t sampleRate, int32_t channelCount);
+ bool submit(const sp<MediaCodecBuffer> &buffer, int32_t sampleRate,
+ int32_t channelCount, std::shared_ptr<const C2AccessUnitInfos::output> &infos);
+
/**
* Submit buffer to SkipCutBuffer object, if initialized.
*/
diff --git a/media/codec2/sfplugin/CCodecConfig.cpp b/media/codec2/sfplugin/CCodecConfig.cpp
index 6d49fa8..c22deca 100644
--- a/media/codec2/sfplugin/CCodecConfig.cpp
+++ b/media/codec2/sfplugin/CCodecConfig.cpp
@@ -402,10 +402,19 @@
add(ConfigMapper(KEY_MAX_INPUT_SIZE, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE, "value")
.limitTo(D::INPUT));
+
// remove when codecs switch to PARAMKEY
deprecated(ConfigMapper(KEY_MAX_INPUT_SIZE, "coded.max-frame-size", "value")
.limitTo(D::INPUT));
+ // large frame params
+ add(ConfigMapper(KEY_BUFFER_BATCH_MAX_OUTPUT_SIZE,
+ C2_PARAMKEY_OUTPUT_LARGE_FRAME, "max-size")
+ .limitTo(D::AUDIO & D::OUTPUT));
+ add(ConfigMapper(KEY_BUFFER_BATCH_THRESHOLD_OUTPUT_SIZE,
+ C2_PARAMKEY_OUTPUT_LARGE_FRAME, "threshold-size")
+ .limitTo(D::AUDIO & D::OUTPUT));
+
// Rotation
// Note: SDK rotation is clock-wise, while C2 rotation is counter-clock-wise
add(ConfigMapper(KEY_ROTATION, C2_PARAMKEY_VUI_ROTATION, "value")
diff --git a/media/codec2/vndk/platform/C2IgbaBuffer.cpp b/media/codec2/vndk/platform/C2IgbaBuffer.cpp
index eafdb22..3622d5e 100644
--- a/media/codec2/vndk/platform/C2IgbaBuffer.cpp
+++ b/media/codec2/vndk/platform/C2IgbaBuffer.cpp
@@ -192,28 +192,25 @@
c2_status_t res = _fetchGraphicBlock(
width, height, format, usage, kBlockingFetchTimeoutNs, &origId, block, &fence);
- if (res == C2_BLOCKING) {
+ if (res == C2_TIMED_OUT) {
+ // SyncFence waiting timeout.
+ // Usually HAL treats C2_TIMED_OUT as an irrecoverable error.
+ // We want HAL to re-try.
return C2_BLOCKING;
}
- if (res != C2_OK) {
- return res;
- }
- // TODO: bundle the fence to the block. Are API changes required?
- res = fence.wait(kSyncFenceWaitNs);
- if (res != C2_OK) {
- bool aidlRet = true;
- ::ndk::ScopedAStatus status = mIgba->deallocate(origId, &aidlRet);
- ALOGE("Waiting a sync fence failed %d aidl(%d: %d)",
- res, status.isOk(), aidlRet);
- }
- return C2_OK;
+ return res;
}
c2_status_t C2IgbaBlockPool::fetchGraphicBlock(
uint32_t width, uint32_t height, uint32_t format, C2MemoryUsage usage,
std::shared_ptr<C2GraphicBlock> *block, C2Fence *fence) {
uint64_t origId;
- return _fetchGraphicBlock(width, height, format, usage, 0LL, &origId, block, fence);
+ c2_status_t res = _fetchGraphicBlock(width, height, format, usage, 0LL, &origId, block, fence);
+ if (res == C2_TIMED_OUT) {
+ *fence = C2Fence();
+ return C2_BLOCKING;
+ }
+ return res;
}
c2_status_t C2IgbaBlockPool::_fetchGraphicBlock(
@@ -263,10 +260,27 @@
}
}
- *fence = _C2FenceFactory::CreateSyncFence(allocation.fence.release());
+ C2Fence syncFence = _C2FenceFactory::CreateSyncFence(allocation.fence.release());
AHardwareBuffer *ahwb = allocation.buffer.release(); // This is acquired.
CHECK(AHardwareBuffer_getId(ahwb, origId) == ::android::OK);
- c2_status_t res = CreateGraphicBlockFromAhwb(ahwb, mAllocator, mIgba, block);
+
+ // We are waiting for SyncFence here for backward compatibility.
+ // H/W based Sync Fence could be returned to improve pipeline latency.
+ //
+ // TODO: Add a component configuration for returning sync fence
+ // from fetchGraphicBlock() as the C2Fence output param(b/322283520).
+ // In the case C2_OK along with GraphicBlock must be returned together.
+ c2_status_t res = syncFence.wait(kSyncFenceWaitNs);
+ if (res != C2_OK) {
+ AHardwareBuffer_release(ahwb);
+ bool aidlRet = true;
+ ::ndk::ScopedAStatus status = mIgba->deallocate(*origId, &aidlRet);
+ ALOGE("Waiting a sync fence failed %d aidl(%d: %d)",
+ res, status.isOk(), aidlRet);
+ return C2_TIMED_OUT;
+ }
+
+ res = CreateGraphicBlockFromAhwb(ahwb, mAllocator, mIgba, block);
AHardwareBuffer_release(ahwb);
if (res != C2_OK) {
bool aidlRet = true;
diff --git a/media/libaudioclient/AudioProductStrategy.cpp b/media/libaudioclient/AudioProductStrategy.cpp
index d9fd58c..1417182 100644
--- a/media/libaudioclient/AudioProductStrategy.cpp
+++ b/media/libaudioclient/AudioProductStrategy.cpp
@@ -60,9 +60,13 @@
}
// Keep in sync with android/media/audiopolicy/AudioProductStrategy#attributeMatches
-int AudioProductStrategy::attributesMatchesScore(const audio_attributes_t refAttributes,
- const audio_attributes_t clientAttritubes)
+int AudioProductStrategy::attributesMatchesScore(audio_attributes_t refAttributes,
+ audio_attributes_t clientAttritubes)
{
+ refAttributes.flags = static_cast<audio_flags_mask_t>(
+ refAttributes.flags & AUDIO_FLAGS_AFFECT_STRATEGY_SELECTION);
+ clientAttritubes.flags = static_cast<audio_flags_mask_t>(
+ clientAttritubes.flags & AUDIO_FLAGS_AFFECT_STRATEGY_SELECTION);
if (refAttributes == clientAttritubes) {
return MATCH_EQUALS;
}
diff --git a/media/libaudioclient/TEST_MAPPING b/media/libaudioclient/TEST_MAPPING
index 234e858..68dba34 100644
--- a/media/libaudioclient/TEST_MAPPING
+++ b/media/libaudioclient/TEST_MAPPING
@@ -43,10 +43,9 @@
}
],
"postsubmit": [
- // TODO(b/302036943): Enable once we make it pass with AIDL HAL on CF.
- // {
- // "name": "audioeffect_analysis"
- // },
+ {
+ "name": "audioeffect_analysis"
+ },
{
"name": "CtsVirtualDevicesTestCases",
"options" : [
diff --git a/media/libaudioclient/include/media/AudioProductStrategy.h b/media/libaudioclient/include/media/AudioProductStrategy.h
index fcbb019..2505b11 100644
--- a/media/libaudioclient/include/media/AudioProductStrategy.h
+++ b/media/libaudioclient/include/media/AudioProductStrategy.h
@@ -58,11 +58,11 @@
* @return {@code INVALID_SCORE} if not matching, {@code MATCH_ON_DEFAULT_SCORE} if matching
* to default strategy, non zero positive score if matching a strategy.
*/
- static int attributesMatchesScore(const audio_attributes_t refAttributes,
- const audio_attributes_t clientAttritubes);
+ static int attributesMatchesScore(audio_attributes_t refAttributes,
+ audio_attributes_t clientAttritubes);
- static bool attributesMatches(const audio_attributes_t refAttributes,
- const audio_attributes_t clientAttritubes) {
+ static bool attributesMatches(audio_attributes_t refAttributes,
+ audio_attributes_t clientAttritubes) {
return attributesMatchesScore(refAttributes, clientAttritubes) > 0;
}
diff --git a/media/libaudioclient/tests/Android.bp b/media/libaudioclient/tests/Android.bp
index f72ac89..0da242d 100644
--- a/media/libaudioclient/tests/Android.bp
+++ b/media/libaudioclient/tests/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp
index fb1cc34..a4c2d50 100644
--- a/media/libaudiohal/impl/Android.bp
+++ b/media/libaudiohal/impl/Android.bp
@@ -257,7 +257,7 @@
shared_libs: [
"android.hardware.common-V2-ndk",
"android.hardware.common.fmq-V1-ndk",
- "av-audio-types-aidl-ndk",
+ "av-audio-types-aidl-V1-ndk",
"libaudio_aidl_conversion_common_cpp",
"libaudio_aidl_conversion_common_ndk",
"libaudio_aidl_conversion_common_ndk_cpp",
diff --git a/media/libaudiohal/impl/ConversionHelperAidl.cpp b/media/libaudiohal/impl/ConversionHelperAidl.cpp
index 46abfda..7a32811 100644
--- a/media/libaudiohal/impl/ConversionHelperAidl.cpp
+++ b/media/libaudiohal/impl/ConversionHelperAidl.cpp
@@ -37,10 +37,6 @@
using ParameterScope = IHalAdapterVendorExtension::ParameterScope;
if (parameterKeys.size() == 0) return OK;
const String8 rawKeys = parameterKeys.keysToString();
- if (vendorExt == nullptr) {
- ALOGW("%s: unknown parameters, ignored: \"%s\"", __func__, rawKeys.c_str());
- return OK;
- }
std::vector<std::string> parameterIds;
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(vendorExt->parseVendorParameterIds(
@@ -85,10 +81,6 @@
using ParameterScope = IHalAdapterVendorExtension::ParameterScope;
if (parameters.size() == 0) return OK;
const String8 rawKeysAndValues = parameters.toString();
- if (vendorExt == nullptr) {
- ALOGW("%s: unknown parameters, ignored: \"%s\"", __func__, rawKeysAndValues.c_str());
- return OK;
- }
std::vector<VendorParameter> syncParameters, asyncParameters;
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(vendorExt->parseVendorParameters(
diff --git a/media/libaudiohal/impl/DeviceHalAidl.cpp b/media/libaudiohal/impl/DeviceHalAidl.cpp
index db9a9b1..a601ad5 100644
--- a/media/libaudiohal/impl/DeviceHalAidl.cpp
+++ b/media/libaudiohal/impl/DeviceHalAidl.cpp
@@ -1052,15 +1052,11 @@
(void)VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<String8>(
parameters, String8(AudioParameter::keyReconfigA2dp),
[&](const String8& value) -> status_t {
- if (mVendorExt != nullptr) {
- std::vector<VendorParameter> result;
- RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
- mVendorExt->parseBluetoothA2dpReconfigureOffload(
- std::string(value.c_str()), &result)));
- reconfigureOffload = std::move(result);
- } else {
- reconfigureOffload = std::vector<VendorParameter>();
- }
+ std::vector<VendorParameter> result;
+ RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
+ mVendorExt->parseBluetoothA2dpReconfigureOffload(
+ std::string(value.c_str()), &result)));
+ reconfigureOffload = std::move(result);
return OK;
}));
if (mBluetoothA2dp != nullptr && a2dpEnabled.has_value()) {
diff --git a/media/libaudiohal/impl/DevicesFactoryHalAidl.cpp b/media/libaudiohal/impl/DevicesFactoryHalAidl.cpp
index 3dbc14a..01fc7fb 100644
--- a/media/libaudiohal/impl/DevicesFactoryHalAidl.cpp
+++ b/media/libaudiohal/impl/DevicesFactoryHalAidl.cpp
@@ -17,12 +17,14 @@
#include <algorithm>
#include <map>
#include <memory>
+#include <mutex>
#include <string>
#define LOG_TAG "DevicesFactoryHalAidl"
//#define LOG_NDEBUG 0
#include <aidl/android/hardware/audio/core/IModule.h>
+#include <aidl/android/media/audio/BnHalAdapterVendorExtension.h>
#include <android/binder_manager.h>
#include <media/AidlConversionNdkCpp.h>
#include <media/AidlConversionUtil.h>
@@ -35,6 +37,7 @@
using aidl::android::hardware::audio::core::IConfig;
using aidl::android::hardware::audio::core::IModule;
using aidl::android::hardware::audio::core::SurroundSoundConfig;
+using aidl::android::hardware::audio::core::VendorParameter;
using aidl::android::media::audio::common::AudioHalEngineConfig;
using aidl::android::media::audio::IHalAdapterVendorExtension;
using android::detail::AudioHalVersionInfo;
@@ -62,10 +65,84 @@
return cpp;
}
+class HalAdapterVendorExtensionWrapper :
+ public ::aidl::android::media::audio::BnHalAdapterVendorExtension {
+ private:
+ template<typename F>
+ ndk::ScopedAStatus callWithRetryOnCrash(F method) {
+ ndk::ScopedAStatus status = ndk::ScopedAStatus::ok();
+ for (auto service = getService(); service != nullptr; service = getService(true)) {
+ status = method(service);
+ if (status.getStatus() != STATUS_DEAD_OBJECT) break;
+ }
+ return status;
+ }
+
+ ndk::ScopedAStatus parseVendorParameterIds(ParameterScope in_scope,
+ const std::string& in_rawKeys,
+ std::vector<std::string>* _aidl_return) override {
+ return callWithRetryOnCrash([&](auto service) {
+ return service->parseVendorParameterIds(in_scope, in_rawKeys, _aidl_return);
+ });
+ }
+
+ ndk::ScopedAStatus parseVendorParameters(
+ ParameterScope in_scope, const std::string& in_rawKeysAndValues,
+ std::vector<VendorParameter>* out_syncParameters,
+ std::vector<VendorParameter>* out_asyncParameters) override {
+ return callWithRetryOnCrash([&](auto service) {
+ return service->parseVendorParameters(in_scope, in_rawKeysAndValues,
+ out_syncParameters, out_asyncParameters);
+ });
+ }
+
+ ndk::ScopedAStatus parseBluetoothA2dpReconfigureOffload(
+ const std::string& in_rawValue, std::vector<VendorParameter>* _aidl_return) override {
+ return callWithRetryOnCrash([&](auto service) {
+ return service->parseBluetoothA2dpReconfigureOffload(in_rawValue, _aidl_return);
+ });
+ }
+
+ ndk::ScopedAStatus parseBluetoothLeReconfigureOffload(const std::string& in_rawValue,
+ std::vector<VendorParameter>* _aidl_return) override {
+ return callWithRetryOnCrash([&](auto service) {
+ return service->parseBluetoothLeReconfigureOffload(in_rawValue, _aidl_return);
+ });
+ }
+
+ ndk::ScopedAStatus processVendorParameters(ParameterScope in_scope,
+ const std::vector<VendorParameter>& in_parameters,
+ std::string* _aidl_return) override {
+ return callWithRetryOnCrash([&](auto service) {
+ return service->processVendorParameters(in_scope, in_parameters, _aidl_return);
+ });
+ }
+
+ std::shared_ptr<IHalAdapterVendorExtension> getService(bool reset = false) {
+ std::lock_guard l(mLock);
+ if (reset || !mVendorExt.has_value()) {
+ auto serviceName = std::string(IHalAdapterVendorExtension::descriptor) + "/default";
+ if (AServiceManager_isDeclared(serviceName.c_str())) {
+ mVendorExt = std::shared_ptr<IHalAdapterVendorExtension>(
+ IHalAdapterVendorExtension::fromBinder(ndk::SpAIBinder(
+ AServiceManager_waitForService(serviceName.c_str()))));
+ } else {
+ mVendorExt = nullptr;
+ }
+ }
+ return mVendorExt.value();
+ }
+
+ std::mutex mLock;
+ std::optional<std::shared_ptr<::aidl::android::media::audio::IHalAdapterVendorExtension>>
+ mVendorExt GUARDED_BY(mLock);
+};
+
} // namespace
DevicesFactoryHalAidl::DevicesFactoryHalAidl(std::shared_ptr<IConfig> config)
- : mConfig(std::move(config)) {
+ : mConfig(std::move(config)),
+ mVendorExt(ndk::SharedRefBase::make<HalAdapterVendorExtensionWrapper>()) {
}
status_t DevicesFactoryHalAidl::getDeviceNames(std::vector<std::string> *names) {
@@ -110,7 +187,7 @@
ALOGE("%s fromBinder %s failed", __func__, serviceName.c_str());
return NO_INIT;
}
- *device = sp<DeviceHalAidl>::make(name, service, getVendorExtension());
+ *device = sp<DeviceHalAidl>::make(name, service, mVendorExt);
return OK;
}
@@ -149,20 +226,6 @@
return OK;
}
-std::shared_ptr<IHalAdapterVendorExtension> DevicesFactoryHalAidl::getVendorExtension() {
- if (!mVendorExt.has_value()) {
- auto serviceName = std::string(IHalAdapterVendorExtension::descriptor) + "/default";
- if (AServiceManager_isDeclared(serviceName.c_str())) {
- mVendorExt = std::shared_ptr<IHalAdapterVendorExtension>(
- IHalAdapterVendorExtension::fromBinder(ndk::SpAIBinder(
- AServiceManager_waitForService(serviceName.c_str()))));
- } else {
- mVendorExt = nullptr;
- }
- }
- return mVendorExt.value();
-}
-
// Main entry-point to the shared library.
extern "C" __attribute__((visibility("default"))) void* createIDevicesFactoryImpl() {
auto serviceName = std::string(IConfig::descriptor) + "/default";
diff --git a/media/libaudiohal/impl/DevicesFactoryHalAidl.h b/media/libaudiohal/impl/DevicesFactoryHalAidl.h
index 17bfe43..2a3a9e7 100644
--- a/media/libaudiohal/impl/DevicesFactoryHalAidl.h
+++ b/media/libaudiohal/impl/DevicesFactoryHalAidl.h
@@ -45,10 +45,7 @@
private:
const std::shared_ptr<::aidl::android::hardware::audio::core::IConfig> mConfig;
- std::optional<std::shared_ptr<::aidl::android::media::audio::IHalAdapterVendorExtension>>
- mVendorExt;
-
- std::shared_ptr<::aidl::android::media::audio::IHalAdapterVendorExtension> getVendorExtension();
+ const std::shared_ptr<::aidl::android::media::audio::IHalAdapterVendorExtension> mVendorExt;
~DevicesFactoryHalAidl() = default;
};
diff --git a/media/libaudiohal/impl/EffectConversionHelperAidl.cpp b/media/libaudiohal/impl/EffectConversionHelperAidl.cpp
index 39999a5..e1a82f8 100644
--- a/media/libaudiohal/impl/EffectConversionHelperAidl.cpp
+++ b/media/libaudiohal/impl/EffectConversionHelperAidl.cpp
@@ -187,13 +187,7 @@
IEffect::OpenEffectReturn openReturn;
RETURN_STATUS_IF_ERROR(
statusTFromBinderStatus(mEffect->open(common, std::nullopt, &openReturn)));
- updateMqs(openReturn);
-
- if (status_t status = updateEventFlags(); status != OK) {
- ALOGV("%s closing at status %d", __func__, status);
- mEffect->close();
- return status;
- }
+ updateMqsAndEventFlags(openReturn);
} else if (mCommon != common) {
ALOGI("%s at state %s, setParameter", __func__, android::internal::ToString(state).c_str());
Parameter aidlParam = UNION_MAKE(Parameter, common, common);
@@ -204,13 +198,21 @@
return *static_cast<int32_t*>(pReplyData) = OK;
}
-void EffectConversionHelperAidl::updateMqs(const IEffect::OpenEffectReturn& ret) {
+void EffectConversionHelperAidl::updateMqsAndEventFlags(const IEffect::OpenEffectReturn& ret) {
if (mIsProxyEffect) {
mStatusQ = std::static_pointer_cast<EffectProxy>(mEffect)->getStatusMQ();
+ } else {
+ mStatusQ = std::make_shared<StatusMQ>(ret.statusMQ);
+ }
+ updateEventFlags();
+ updateDataMqs(ret);
+}
+
+void EffectConversionHelperAidl::updateDataMqs(const IEffect::OpenEffectReturn& ret) {
+ if (mIsProxyEffect) {
mInputQ = std::static_pointer_cast<EffectProxy>(mEffect)->getInputMQ();
mOutputQ = std::static_pointer_cast<EffectProxy>(mEffect)->getOutputMQ();
} else {
- mStatusQ = std::make_shared<StatusMQ>(ret.statusMQ);
mInputQ = std::make_shared<DataMQ>(ret.inputDataMQ);
mOutputQ = std::make_shared<DataMQ>(ret.outputDataMQ);
}
@@ -407,10 +409,8 @@
}
// update FMQs if the effect instance already open
if (State state; effectProxy->getState(&state).isOk() && state != State::INIT) {
- mStatusQ = effectProxy->getStatusMQ();
- mInputQ = effectProxy->getInputMQ();
- mOutputQ = effectProxy->getOutputMQ();
- updateEventFlags();
+ IEffect::OpenEffectReturn openReturn;
+ updateMqsAndEventFlags(openReturn);
}
}
return *static_cast<int32_t*>(pReplyData) = OK;
@@ -512,7 +512,8 @@
IEffect::OpenEffectReturn openReturn;
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mEffect->reopen(&openReturn)));
- updateMqs(openReturn);
+ // status MQ won't be changed after open
+ updateDataMqs(openReturn);
return OK;
}
diff --git a/media/libaudiohal/impl/EffectConversionHelperAidl.h b/media/libaudiohal/impl/EffectConversionHelperAidl.h
index 8b9efb3..c4841c5 100644
--- a/media/libaudiohal/impl/EffectConversionHelperAidl.h
+++ b/media/libaudiohal/impl/EffectConversionHelperAidl.h
@@ -98,7 +98,6 @@
std::shared_ptr<StatusMQ> mStatusQ = nullptr;
std::shared_ptr<DataMQ> mInputQ = nullptr, mOutputQ = nullptr;
-
struct EventFlagDeleter {
void operator()(::android::hardware::EventFlag* flag) const {
if (flag) {
@@ -108,8 +107,10 @@
};
std::shared_ptr<android::hardware::EventFlag> mEfGroup = nullptr;
status_t updateEventFlags();
-
- void updateMqs(const ::aidl::android::hardware::audio::effect::IEffect::OpenEffectReturn& ret);
+ void updateDataMqs(
+ const ::aidl::android::hardware::audio::effect::IEffect::OpenEffectReturn& ret);
+ void updateMqsAndEventFlags(
+ const ::aidl::android::hardware::audio::effect::IEffect::OpenEffectReturn& ret);
status_t handleInit(uint32_t cmdSize, const void* pCmdData, uint32_t* replySize,
void* pReplyData);
diff --git a/media/libaudiohal/impl/EffectHalAidl.cpp b/media/libaudiohal/impl/EffectHalAidl.cpp
index 2836727..ebda86a 100644
--- a/media/libaudiohal/impl/EffectHalAidl.cpp
+++ b/media/libaudiohal/impl/EffectHalAidl.cpp
@@ -57,20 +57,22 @@
using ::aidl::android::hardware::audio::effect::IEffect;
using ::aidl::android::hardware::audio::effect::IFactory;
using ::aidl::android::hardware::audio::effect::kEventFlagDataMqUpdate;
+using ::aidl::android::hardware::audio::effect::kReopenSupportedVersion;
using ::aidl::android::hardware::audio::effect::State;
namespace android {
namespace effect {
EffectHalAidl::EffectHalAidl(const std::shared_ptr<IFactory>& factory,
- const std::shared_ptr<IEffect>& effect,
- int32_t sessionId, int32_t ioId, const Descriptor& desc,
- bool isProxyEffect)
+ const std::shared_ptr<IEffect>& effect, int32_t sessionId,
+ int32_t ioId, const Descriptor& desc, bool isProxyEffect)
: mFactory(factory),
mEffect(effect),
mSessionId(sessionId),
mIoId(ioId),
mIsProxyEffect(isProxyEffect) {
+ assert(mFactory != nullptr);
+ assert(mEffect != nullptr);
createAidlConversion(effect, sessionId, ioId, desc);
}
@@ -184,10 +186,18 @@
return INVALID_OPERATION;
}
- if (uint32_t efState = 0;
- ::android::OK == efGroup->wait(kEventFlagDataMqUpdate, &efState, 1 /* ns */,
- true /* retry */)) {
- ALOGI("%s %s receive dataMQUpdate eventFlag from HAL", __func__, effectName.c_str());
+ // use IFactory HAL version because IEffect can be an EffectProxy instance
+ static const int halVersion = [&]() {
+ int version = 0;
+ return mFactory->getInterfaceVersion(&version).isOk() ? version : 0;
+ }();
+
+ if (uint32_t efState = 0; halVersion >= kReopenSupportedVersion &&
+ ::android::OK == efGroup->wait(kEventFlagDataMqUpdate, &efState,
+ 1 /* ns */, true /* retry */) &&
+ efState & kEventFlagDataMqUpdate) {
+ ALOGI("%s %s V%d receive dataMQUpdate eventFlag from HAL", __func__, effectName.c_str(),
+ halVersion);
mConversion->reopen();
}
auto statusQ = mConversion->getStatusMQ();
diff --git a/media/libaudiohal/impl/StreamHalAidl.cpp b/media/libaudiohal/impl/StreamHalAidl.cpp
index 5f525d7..2a8ebc6 100644
--- a/media/libaudiohal/impl/StreamHalAidl.cpp
+++ b/media/libaudiohal/impl/StreamHalAidl.cpp
@@ -788,7 +788,7 @@
if (VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<int>(
parameters, String8(AudioParameter::keyOffloadCodecAverageBitRate),
[&](int value) {
- return value > 0 ?
+ return value >= 0 ?
mOffloadMetadata.averageBitRatePerSecond = value, OK : BAD_VALUE;
}))) {
updateMetadata = true;
diff --git a/media/libaudiohal/tests/Android.bp b/media/libaudiohal/tests/Android.bp
index 8f011c8..2e3a058 100644
--- a/media/libaudiohal/tests/Android.bp
+++ b/media/libaudiohal/tests/Android.bp
@@ -17,6 +17,7 @@
// frameworks/av/include.
package {
+ default_team: "trendy_team_android_media_audio_framework",
default_applicable_licenses: ["frameworks_av_license"],
}
diff --git a/media/libaudiohal/tests/CoreAudioHalAidl_test.cpp b/media/libaudiohal/tests/CoreAudioHalAidl_test.cpp
index 1204a3b..3541078 100644
--- a/media/libaudiohal/tests/CoreAudioHalAidl_test.cpp
+++ b/media/libaudiohal/tests/CoreAudioHalAidl_test.cpp
@@ -443,21 +443,6 @@
EXPECT_EQ(ScreenRotation::DEG_0, mModule->getScreenRotation());
}
-// Without a vendor extension, any unrecognized parameters must be ignored.
-TEST_F(DeviceHalAidlTest, VendorParameterIgnored) {
- EXPECT_EQ(0UL, mModule->getAsyncParameters().size());
- EXPECT_EQ(0UL, mModule->getSyncParameters().size());
- EXPECT_EQ(OK, mDevice->setParameters(createParameterString("random_name", "random_value")));
- EXPECT_EQ(0UL, mModule->getAsyncParameters().size());
- EXPECT_EQ(0UL, mModule->getSyncParameters().size());
-
- EXPECT_EQ(0UL, mModule->getRetrievedParameterIds().size());
- String8 values;
- EXPECT_EQ(OK, mDevice->getParameters(String8("random_name"), &values));
- EXPECT_EQ(0UL, mModule->getRetrievedParameterIds().size());
- EXPECT_EQ(0UL, values.length());
-}
-
class DeviceHalAidlVendorParametersTest : public testing::Test {
public:
void SetUp() override {
diff --git a/media/libeffects/downmix/aidl/EffectDownmix.cpp b/media/libeffects/downmix/aidl/EffectDownmix.cpp
index c82c23b..46156ce 100644
--- a/media/libeffects/downmix/aidl/EffectDownmix.cpp
+++ b/media/libeffects/downmix/aidl/EffectDownmix.cpp
@@ -195,6 +195,8 @@
const auto availableToWrite = outputMQ->availableToWrite() *
mImplContext->getInputFrameSize() /
mImplContext->getOutputFrameSize();
+ assert(mImplContext->getWorkBufferSize() >=
+ std::max(availableToRead(), availableToWrite));
auto processSamples = std::min(availableToRead, availableToWrite);
if (processSamples) {
inputMQ->read(buffer, processSamples);
diff --git a/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp b/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp
index 1fedea4..7e1549d 100644
--- a/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp
+++ b/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp
@@ -215,6 +215,10 @@
RETURN_OK_IF(mState != State::INIT);
mImplContext = createContext(common);
RETURN_IF(!mContext || !mImplContext, EX_NULL_POINTER, "createContextFailed");
+ int version = 0;
+ RETURN_IF(!getInterfaceVersion(&version).isOk(), EX_UNSUPPORTED_OPERATION,
+ "FailedToGetInterfaceVersion");
+ mImplContext->setVersion(version);
mEventFlag = mImplContext->getStatusEventFlag();
if (specific.has_value()) {
diff --git a/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp b/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp
index 031477f..2d3bdd0 100644
--- a/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp
+++ b/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp
@@ -185,7 +185,7 @@
IEffect::Status HapticGeneratorImpl::effectProcessImpl(float* in, float* out, int samples) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!mContext, status, "nullContext");
- return mContext->lvmProcess(in, out, samples);
+ return mContext->process(in, out, samples);
}
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp
index 354ee00..e671543 100644
--- a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp
+++ b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp
@@ -118,7 +118,7 @@
return RetCode::SUCCESS;
}
-IEffect::Status HapticGeneratorContext::lvmProcess(float* in, float* out, int samples) {
+IEffect::Status HapticGeneratorContext::process(float* in, float* out, int samples) {
LOG(DEBUG) << __func__ << " in " << in << " out " << out << " sample " << samples;
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
diff --git a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h
index 26e69e4..8618b7b 100644
--- a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h
+++ b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h
@@ -75,7 +75,7 @@
RetCode setHgVibratorInformation(const HapticGenerator::VibratorInformation& vibratorInfo);
HapticGenerator::VibratorInformation getHgVibratorInformation();
- IEffect::Status lvmProcess(float* in, float* out, int samples);
+ IEffect::Status process(float* in, float* out, int samples);
private:
static constexpr float DEFAULT_RESONANT_FREQUENCY = 150.0f;
diff --git a/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp b/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp
index a7d9282..bcf0db6 100644
--- a/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp
+++ b/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp
@@ -178,7 +178,7 @@
IEffect::Status LoudnessEnhancerImpl::effectProcessImpl(float* in, float* out, int samples) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!mContext, status, "nullContext");
- return mContext->lvmProcess(in, out, samples);
+ return mContext->process(in, out, samples);
}
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp
index bc3fa45..be914bf 100644
--- a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp
+++ b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp
@@ -65,7 +65,7 @@
return RetCode::SUCCESS;
}
-IEffect::Status LoudnessEnhancerContext::lvmProcess(float* in, float* out, int samples) {
+IEffect::Status LoudnessEnhancerContext::process(float* in, float* out, int samples) {
LOG(DEBUG) << __func__ << " in " << in << " out " << out << " sample " << samples;
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
diff --git a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h
index 9a1ec4c..fd688d7 100644
--- a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h
+++ b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h
@@ -42,7 +42,7 @@
RetCode setLeGain(int gainMb);
int getLeGain() const { return mGain; }
- IEffect::Status lvmProcess(float* in, float* out, int samples);
+ IEffect::Status process(float* in, float* out, int samples);
private:
std::mutex mMutex;
diff --git a/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp b/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp
index bb7e4c6..a9d0cc2 100644
--- a/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp
+++ b/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp
@@ -747,7 +747,7 @@
return angles;
}
-IEffect::Status BundleContext::lvmProcess(float* in, float* out, int samples) {
+IEffect::Status BundleContext::process(float* in, float* out, int samples) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!in, status, "nullInput");
RETURN_VALUE_IF(!out, status, "nullOutput");
@@ -854,21 +854,34 @@
LOG(DEBUG) << "Effect_process() processing last frame";
}
mNumberEffectsCalled = 0;
- float* outTmp = (accumulate ? getWorkBuffer() : out);
- /* Process the samples */
- LVM_ReturnStatus_en lvmStatus;
- {
- std::lock_guard lg(mMutex);
-
- lvmStatus = LVM_Process(mInstance, in, outTmp, inputFrameCount, 0);
- if (lvmStatus != LVM_SUCCESS) {
- LOG(ERROR) << __func__ << lvmStatus;
- return {EX_UNSUPPORTED_OPERATION, 0, 0};
- }
- if (accumulate) {
- for (int i = 0; i < samples; i++) {
- out[i] += outTmp[i];
+ int frames = samples * sizeof(float) / frameSize;
+ int bufferIndex = 0;
+ // LVM library supports max of int16_t frames at a time and should be multiple of
+ // kBlockSizeMultiple.
+ constexpr int kBlockSizeMultiple = 4;
+ constexpr int kMaxBlockFrames =
+ (std::numeric_limits<int16_t>::max() / kBlockSizeMultiple) * kBlockSizeMultiple;
+ while (frames > 0) {
+ float* outTmp = (accumulate ? getWorkBuffer() : out);
+ /* Process the samples */
+ LVM_ReturnStatus_en lvmStatus;
+ {
+ std::lock_guard lg(mMutex);
+ int processFrames = std::min(frames, kMaxBlockFrames);
+ lvmStatus = LVM_Process(mInstance, in + bufferIndex, outTmp + bufferIndex,
+ processFrames, 0);
+ if (lvmStatus != LVM_SUCCESS) {
+ LOG(ERROR) << "LVM lib failed with error: " << lvmStatus;
+ return {EX_UNSUPPORTED_OPERATION, 0, 0};
}
+ if (accumulate) {
+ for (int i = 0; i < samples; i++) {
+ out[i] += outTmp[i];
+ }
+ }
+ frames -= processFrames;
+ int processedSize = processFrames * frameSize / sizeof(float);
+ bufferIndex += processedSize;
}
}
} else {
diff --git a/media/libeffects/lvm/wrapper/Aidl/BundleContext.h b/media/libeffects/lvm/wrapper/Aidl/BundleContext.h
index 809f402..af46818 100644
--- a/media/libeffects/lvm/wrapper/Aidl/BundleContext.h
+++ b/media/libeffects/lvm/wrapper/Aidl/BundleContext.h
@@ -85,7 +85,7 @@
RetCode setVolumeStereo(const Parameter::VolumeStereo& volumeStereo) override;
Parameter::VolumeStereo getVolumeStereo() override { return {1.0f, 1.0f}; }
- IEffect::Status lvmProcess(float* in, float* out, int samples);
+ IEffect::Status process(float* in, float* out, int samples);
IEffect::Status processEffect(float* in, float* out, int sampleToProcess);
diff --git a/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp b/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp
index 257e972..755f57c 100644
--- a/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp
+++ b/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp
@@ -458,7 +458,7 @@
IEffect::Status EffectBundleAidl::effectProcessImpl(float* in, float* out, int sampleToProcess) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!mContext, status, "nullContext");
- return mContext->lvmProcess(in, out, sampleToProcess);
+ return mContext->process(in, out, sampleToProcess);
}
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp b/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp
index f9afe69..c714bc9 100644
--- a/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp
+++ b/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp
@@ -390,7 +390,7 @@
IEffect::Status EffectReverb::effectProcessImpl(float* in, float* out, int sampleToProcess) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!mContext, status, "nullContext");
- return mContext->lvmProcess(in, out, sampleToProcess);
+ return mContext->process(in, out, sampleToProcess);
}
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp
index 468b268..1c66c78 100644
--- a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp
+++ b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp
@@ -352,7 +352,7 @@
return kDefaultLPF;
}
-IEffect::Status ReverbContext::lvmProcess(float* in, float* out, int samples) {
+IEffect::Status ReverbContext::process(float* in, float* out, int samples) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!in, status, "nullInput");
RETURN_VALUE_IF(!out, status, "nullOutput");
diff --git a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h
index d11a081..4fc9c4a 100644
--- a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h
+++ b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h
@@ -100,7 +100,7 @@
}
bool getReflectionsLevel() const { return mReflectionsLevelMb; }
- IEffect::Status lvmProcess(float* in, float* out, int samples);
+ IEffect::Status process(float* in, float* out, int samples);
private:
static constexpr inline float kUnitVolume = 1;
diff --git a/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp b/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp
index 7552804..1675d97 100644
--- a/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp
+++ b/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp
@@ -446,7 +446,7 @@
IEffect::Status EffectPreProcessing::effectProcessImpl(float* in, float* out, int sampleToProcess) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!mContext, status, "nullContext");
- return mContext->lvmProcess(in, out, sampleToProcess);
+ return mContext->process(in, out, sampleToProcess);
}
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp b/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp
index 2c44e5c..7bb0cc3 100644
--- a/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp
+++ b/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp
@@ -16,6 +16,7 @@
#include <cstddef>
#define LOG_TAG "PreProcessingContext"
+#include <audio_utils/primitives.h>
#include <Utils.h>
#include "PreProcessingContext.h"
@@ -141,7 +142,7 @@
}
RetCode PreProcessingContext::setCommon(const Parameter::Common& common) {
- if(auto ret = updateIOFrameSize(common); ret != RetCode::SUCCESS) {
+ if (auto ret = updateIOFrameSize(common); ret != RetCode::SUCCESS) {
return ret;
}
mCommon = common;
@@ -152,10 +153,10 @@
void PreProcessingContext::updateConfigs(const Parameter::Common& common) {
mInputConfig.set_sample_rate_hz(common.input.base.sampleRate);
mInputConfig.set_num_channels(::aidl::android::hardware::audio::common::getChannelCount(
- common.input.base.channelMask));
+ common.input.base.channelMask));
mOutputConfig.set_sample_rate_hz(common.input.base.sampleRate);
mOutputConfig.set_num_channels(::aidl::android::hardware::audio::common::getChannelCount(
- common.output.base.channelMask));
+ common.output.base.channelMask));
}
RetCode PreProcessingContext::setAcousticEchoCancelerEchoDelay(int echoDelayUs) {
@@ -268,7 +269,7 @@
return mLevel;
}
-IEffect::Status PreProcessingContext::lvmProcess(float* in, float* out, int samples) {
+IEffect::Status PreProcessingContext::process(float* in, float* out, int samples) {
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!in, status, "nullInput");
RETURN_VALUE_IF(!out, status, "nullOutput");
@@ -281,33 +282,40 @@
LOG(DEBUG) << __func__ << " start processing";
std::lock_guard lg(mMutex);
- mProcessedMsk |= (1 << int(mType));
-
// webrtc implementation clear out was_stream_delay_set every time after ProcessStream() call
mAudioProcessingModule->set_stream_delay_ms(mEchoDelayUs / 1000);
+ std::vector<int16_t> in16(samples);
+ std::vector<int16_t> out16(samples);
+ memcpy_to_i16_from_float(in16.data(), in, samples);
+
+ mProcessedMsk |= (1 << int(mType));
+
if ((mProcessedMsk & mEnabledMsk) == mEnabledMsk) {
mProcessedMsk = 0;
- int processStatus = mAudioProcessingModule->ProcessStream(
- (const int16_t* const)in, mInputConfig, mOutputConfig, (int16_t* const)out);
+ int processStatus = mAudioProcessingModule->ProcessStream(in16.data(), mInputConfig,
+ mOutputConfig, out16.data());
if (processStatus != 0) {
LOG(ERROR) << "Process stream failed with error " << processStatus;
return status;
}
}
- mRevProcessedMsk |= (1 << int(mType));
-
- if ((mRevProcessedMsk & mRevEnabledMsk) == mRevEnabledMsk) {
- mRevProcessedMsk = 0;
- int revProcessStatus = mAudioProcessingModule->ProcessReverseStream(
- (const int16_t* const)in, mInputConfig, mInputConfig, (int16_t* const)out);
- if (revProcessStatus != 0) {
- LOG(ERROR) << "Process reverse stream failed with error " << revProcessStatus;
- return status;
+ if (mType == PreProcessingEffectType::ACOUSTIC_ECHO_CANCELLATION) {
+ mRevProcessedMsk |= (1 << int(mType));
+ if ((mRevProcessedMsk & mRevEnabledMsk) == mRevEnabledMsk) {
+ mRevProcessedMsk = 0;
+ int revProcessStatus = mAudioProcessingModule->ProcessReverseStream(
+ in16.data(), mInputConfig, mInputConfig, out16.data());
+ if (revProcessStatus != 0) {
+ LOG(ERROR) << "Process reverse stream failed with error " << revProcessStatus;
+ return status;
+ }
}
}
+ memcpy_to_float_from_i16(out, out16.data(), samples);
+
return {STATUS_OK, samples, samples};
}
diff --git a/media/libeffects/preprocessing/aidl/PreProcessingContext.h b/media/libeffects/preprocessing/aidl/PreProcessingContext.h
index 9ba1bbe..811bacf 100644
--- a/media/libeffects/preprocessing/aidl/PreProcessingContext.h
+++ b/media/libeffects/preprocessing/aidl/PreProcessingContext.h
@@ -76,7 +76,7 @@
RetCode setNoiseSuppressionLevel(NoiseSuppression::Level level);
NoiseSuppression::Level getNoiseSuppressionLevel() const;
- IEffect::Status lvmProcess(float* in, float* out, int samples);
+ IEffect::Status process(float* in, float* out, int samples);
private:
static constexpr inline int kAgcDefaultTargetLevel = 3;
diff --git a/media/libeffects/visualizer/aidl/Visualizer.cpp b/media/libeffects/visualizer/aidl/Visualizer.cpp
index 0303842..fa651a6 100644
--- a/media/libeffects/visualizer/aidl/Visualizer.cpp
+++ b/media/libeffects/visualizer/aidl/Visualizer.cpp
@@ -61,8 +61,8 @@
MAKE_RANGE(Visualizer, latencyMs, 0, VisualizerContext::kMaxLatencyMs),
MAKE_RANGE(Visualizer, captureSamples, 0, VisualizerContext::kMaxCaptureBufSize),
/* get only parameters, set invalid range (min > max) to indicate not support set */
- MAKE_RANGE(Visualizer, measurement, Visualizer::Measurement({.peak = 1, .rms = 1}),
- Visualizer::Measurement({.peak = 0, .rms = 0})),
+ MAKE_RANGE(Visualizer, measurement, Visualizer::Measurement({.rms = 1, .peak = 1}),
+ Visualizer::Measurement({.rms = 0, .peak = 0})),
MAKE_RANGE(Visualizer, captureSampleBuffer, std::vector<uint8_t>({1}),
std::vector<uint8_t>({0}))};
const Capability VisualizerImpl::kCapability = {
diff --git a/media/libheif/HeifDecoderImpl.cpp b/media/libheif/HeifDecoderImpl.cpp
index 085a7e4..ee4075f 100644
--- a/media/libheif/HeifDecoderImpl.cpp
+++ b/media/libheif/HeifDecoderImpl.cpp
@@ -32,6 +32,7 @@
#include <private/media/VideoFrame.h>
#include <utils/Log.h>
#include <utils/RefBase.h>
+#include <algorithm>
#include <vector>
HeifDecoder* createHeifDecoder() {
@@ -42,7 +43,10 @@
void initFrameInfo(HeifFrameInfo *info, const VideoFrame *videoFrame) {
info->mWidth = videoFrame->mDisplayWidth;
- info->mHeight = videoFrame->mDisplayHeight;
+ // Number of scanlines is mDisplayHeight. Clamp it to mHeight to guard
+ // against malformed streams claiming that mDisplayHeight is greater than
+ // mHeight.
+ info->mHeight = std::min(videoFrame->mDisplayHeight, videoFrame->mHeight);
info->mRotationAngle = videoFrame->mRotationAngle;
info->mBytesPerPixel = videoFrame->mBytesPerPixel;
info->mDurationUs = videoFrame->mDurationUs;
@@ -746,7 +750,9 @@
(videoFrame->mRowBytes * (mCurScanline + videoFrame->mDisplayTop)) +
(videoFrame->mBytesPerPixel * videoFrame->mDisplayLeft);
mCurScanline++;
- memcpy(dst, src, videoFrame->mBytesPerPixel * videoFrame->mDisplayWidth);
+ // Do not try to copy more than |videoFrame->mWidth| pixels.
+ uint32_t width = std::min(videoFrame->mDisplayWidth, videoFrame->mWidth);
+ memcpy(dst, src, videoFrame->mBytesPerPixel * width);
return true;
}
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 2145dd9..f9ceef2 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -2188,7 +2188,7 @@
int32_t colorFormat = OMX_COLOR_FormatUnused;
OMX_U32 flexibleEquivalent = OMX_COLOR_FormatUnused;
if (!outputFormat->findInt32("color-format", &colorFormat)) {
- ALOGE("ouptut port did not have a color format (wrong domain?)");
+ ALOGE("output port did not have a color format (wrong domain?)");
return BAD_VALUE;
}
ALOGD("[%s] Requested output format %#x and got %#x.",
diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp
index 712b405..896e021 100644
--- a/media/libstagefright/Android.bp
+++ b/media/libstagefright/Android.bp
@@ -315,6 +315,7 @@
"libaudioclient_aidl_conversion",
"packagemanager_aidl-cpp",
"server_configurable_flags",
+ "aconfig_mediacodec_flags_c_lib",
],
static_libs: [
diff --git a/media/libstagefright/FrameDecoder.cpp b/media/libstagefright/FrameDecoder.cpp
index 0ab954f..1a0bb7f 100644
--- a/media/libstagefright/FrameDecoder.cpp
+++ b/media/libstagefright/FrameDecoder.cpp
@@ -102,13 +102,6 @@
displayTop = 0;
}
}
- if (displayWidth > width) {
- displayWidth = width;
- }
- if (displayHeight > height) {
- displayHeight = height;
- }
-
if (allocRotated) {
if (rotationAngle == 90 || rotationAngle == 270) {
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index a0a2891..d50c06b 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -172,6 +172,7 @@
const char *getTrackType() const;
void resetInternal();
int64_t trackMetaDataSize();
+ bool isTimestampValid(int64_t timeUs);
private:
// A helper class to handle faster write box with table entries
@@ -2430,6 +2431,47 @@
return OK;
}
+bool MPEG4Writer::isSampleMetadataValid(size_t trackIndex, int64_t timeUs) {
+ // Track Index starts from zero, so it should be at least 1 less than size.
+ if (trackIndex >= mTracks.size()) {
+ ALOGE("Incorrect trackIndex %zu, mTracks->size() %zu", trackIndex, mTracks.size());
+ return false;
+ }
+
+ List<Track *>::iterator it = mTracks.begin();
+
+ // (*it) is already pointing to trackIndex 0.
+ for (int i = 1; i <= trackIndex; i++) {
+ it++;
+ }
+
+ return (*it)->isTimestampValid(timeUs);
+}
+
+bool MPEG4Writer::Track::isTimestampValid(int64_t timeUs) {
+ // No timescale if HEIF
+ if (mIsHeif) {
+ return true;
+ }
+
+ // Make sure abs(timeUs) does not overflow
+ if (timeUs == INT64_MIN) {
+ return false;
+ }
+
+ // Ensure that the timeUs value does not have extremely low or high values
+ // that would cause an underflow or overflow, like in the calculation -
+ // mdhdDuration = (trakDurationUs * mTimeScale + 5E5) / 1E6
+ if (abs(timeUs) >= (INT64_MAX - 5E5) / mTimeScale) {
+ return false;
+ }
+ // Limit check for calculations in ctts box
+ if (abs(timeUs) + kMaxCttsOffsetTimeUs >= INT64_MAX / mTimeScale) {
+ return false;
+ }
+ return true;
+}
+
bool MPEG4Writer::Track::isExifData(
MediaBufferBase *buffer, uint32_t *tiffHdrOffset) const {
if (!mIsHeif) {
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index 3c80f28..4d6a67b 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -271,6 +271,38 @@
// XXX suppress until we get our representation right
static bool kEmitHistogram = false;
+typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
+
+// Multi access unit helpers
+static status_t generateFlagsFromAccessUnitInfo(
+ sp<AMessage> &msg, const sp<BufferInfosWrapper> &bufferInfos) {
+ msg->setInt64("timeUs", bufferInfos->value[0].mTimestamp);
+ msg->setInt32("flags", bufferInfos->value[0].mFlags);
+ // will prevent any access-unit info copy.
+ if (bufferInfos->value.size() > 1) {
+ uint32_t bufferFlags = 0;
+ uint32_t flagsInAllAU = BUFFER_FLAG_DECODE_ONLY | BUFFER_FLAG_CODEC_CONFIG;
+ uint32_t andFlags = flagsInAllAU;
+ int infoIdx = 0;
+ bool foundEndOfStream = false;
+ for ( ; infoIdx < bufferInfos->value.size() && !foundEndOfStream; ++infoIdx) {
+ bufferFlags |= bufferInfos->value[infoIdx].mFlags;
+ andFlags &= bufferInfos->value[infoIdx].mFlags;
+ if (bufferFlags & BUFFER_FLAG_END_OF_STREAM) {
+ foundEndOfStream = true;
+ }
+ }
+ bufferFlags = bufferFlags & (andFlags | (~flagsInAllAU));
+ if (infoIdx != bufferInfos->value.size()) {
+ ALOGE("Error: incorrect access-units");
+ return -EINVAL;
+ }
+ msg->setInt32("flags", bufferFlags);
+ msg->setObject("accessUnitInfo", bufferInfos);
+ }
+ return OK;
+}
+
static int64_t getId(IResourceManagerClient const * client) {
return (int64_t) client;
}
@@ -2222,7 +2254,10 @@
static void mapFormat(AString componentName, const sp<AMessage> &format, const char *kind,
bool reverse);
-mediametrics_handle_t MediaCodec::createMediaMetrics(const sp<AMessage>& format, uint32_t flags) {
+mediametrics_handle_t MediaCodec::createMediaMetrics(const sp<AMessage>& format,
+ uint32_t flags,
+ status_t* err) {
+ *err = OK;
mediametrics_handle_t nextMetricsHandle = mediametrics_create(kCodecKeyName);
bool isEncoder = (flags & CONFIGURE_FLAG_ENCODE);
@@ -2302,7 +2337,9 @@
mErrorLog.log(LOG_TAG, base::StringPrintf(
"Invalid size(s), width=%d, height=%d", mWidth, mHeight));
mediametrics_delete(nextMetricsHandle);
- return BAD_VALUE;
+ // Set the error code and return null handle.
+ *err = BAD_VALUE;
+ return 0;
}
} else {
@@ -2385,7 +2422,11 @@
updateCodecImportance(format);
// Create and set up metrics for this codec.
- mediametrics_handle_t nextMetricsHandle = createMediaMetrics(format, flags);
+ status_t err = OK;
+ mediametrics_handle_t nextMetricsHandle = createMediaMetrics(format, flags, &err);
+ if (err != OK) {
+ return err;
+ }
sp<AMessage> msg = new AMessage(kWhatConfigure, this);
msg->setMessage("format", format);
@@ -2420,7 +2461,6 @@
sp<AMessage> callback = mCallback;
- status_t err;
std::vector<MediaResourceParcel> resources;
resources.push_back(MediaResource::CodecResource(mFlags & kFlagIsSecure,
toMediaResourceSubType(mIsHardware, mDomain)));
@@ -3174,7 +3214,49 @@
msg->setInt64("timeUs", presentationTimeUs);
msg->setInt32("flags", flags);
msg->setPointer("errorDetailMsg", errorDetailMsg);
+ sp<AMessage> response;
+ return PostAndAwaitResponse(msg, &response);
+}
+status_t MediaCodec::queueInputBuffers(
+ size_t index,
+ size_t offset,
+ size_t size,
+ const sp<BufferInfosWrapper> &infos,
+ AString *errorDetailMsg) {
+ sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, this);
+ uint32_t bufferFlags = 0;
+ uint32_t flagsinAllAU = BUFFER_FLAG_DECODE_ONLY | BUFFER_FLAG_CODECCONFIG;
+ uint32_t andFlags = flagsinAllAU;
+ if (infos == nullptr || infos->value.empty()) {
+ ALOGE("ERROR: Large Audio frame with no BufferInfo");
+ return BAD_VALUE;
+ }
+ int infoIdx = 0;
+ std::vector<AccessUnitInfo> &accessUnitInfo = infos->value;
+ int64_t minTimeUs = accessUnitInfo.front().mTimestamp;
+ bool foundEndOfStream = false;
+ for ( ; infoIdx < accessUnitInfo.size() && !foundEndOfStream; ++infoIdx) {
+ bufferFlags |= accessUnitInfo[infoIdx].mFlags;
+ andFlags &= accessUnitInfo[infoIdx].mFlags;
+ if (bufferFlags & BUFFER_FLAG_END_OF_STREAM) {
+ foundEndOfStream = true;
+ }
+ }
+ bufferFlags = bufferFlags & (andFlags | (~flagsinAllAU));
+ if (infoIdx != accessUnitInfo.size()) {
+ ALOGE("queueInputBuffers has incorrect access-units");
+ return -EINVAL;
+ }
+ msg->setSize("index", index);
+ msg->setSize("offset", offset);
+ msg->setSize("size", size);
+ msg->setInt64("timeUs", minTimeUs);
+ // Make this represent flags for the entire buffer
+ // decodeOnly Flag is set only when all buffers are decodeOnly
+ msg->setInt32("flags", bufferFlags);
+ msg->setObject("accessUnitInfo", infos);
+ msg->setPointer("errorDetailMsg", errorDetailMsg);
sp<AMessage> response;
return PostAndAwaitResponse(msg, &response);
}
@@ -3218,28 +3300,30 @@
status_t MediaCodec::queueBuffer(
size_t index,
const std::shared_ptr<C2Buffer> &buffer,
- int64_t presentationTimeUs,
- uint32_t flags,
+ const sp<BufferInfosWrapper> &bufferInfos,
const sp<AMessage> &tunings,
AString *errorDetailMsg) {
if (errorDetailMsg != NULL) {
errorDetailMsg->clear();
}
-
+ if (bufferInfos == nullptr || bufferInfos->value.empty()) {
+ return BAD_VALUE;
+ }
+ status_t err = OK;
sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, this);
msg->setSize("index", index);
sp<WrapperObject<std::shared_ptr<C2Buffer>>> obj{
new WrapperObject<std::shared_ptr<C2Buffer>>{buffer}};
msg->setObject("c2buffer", obj);
- msg->setInt64("timeUs", presentationTimeUs);
- msg->setInt32("flags", flags);
+ if (OK != (err = generateFlagsFromAccessUnitInfo(msg, bufferInfos))) {
+ return err;
+ }
if (tunings && tunings->countEntries() > 0) {
msg->setMessage("tunings", tunings);
}
msg->setPointer("errorDetailMsg", errorDetailMsg);
-
sp<AMessage> response;
- status_t err = PostAndAwaitResponse(msg, &response);
+ err = PostAndAwaitResponse(msg, &response);
return err;
}
@@ -3254,14 +3338,16 @@
const uint8_t iv[16],
CryptoPlugin::Mode mode,
const CryptoPlugin::Pattern &pattern,
- int64_t presentationTimeUs,
- uint32_t flags,
+ const sp<BufferInfosWrapper> &bufferInfos,
const sp<AMessage> &tunings,
AString *errorDetailMsg) {
if (errorDetailMsg != NULL) {
errorDetailMsg->clear();
}
-
+ if (bufferInfos == nullptr || bufferInfos->value.empty()) {
+ return BAD_VALUE;
+ }
+ status_t err = OK;
sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, this);
msg->setSize("index", index);
sp<WrapperObject<sp<hardware::HidlMemory>>> memory{
@@ -3275,15 +3361,16 @@
msg->setInt32("mode", mode);
msg->setInt32("encryptBlocks", pattern.mEncryptBlocks);
msg->setInt32("skipBlocks", pattern.mSkipBlocks);
- msg->setInt64("timeUs", presentationTimeUs);
- msg->setInt32("flags", flags);
+ if (OK != (err = generateFlagsFromAccessUnitInfo(msg, bufferInfos))) {
+ return err;
+ }
if (tunings && tunings->countEntries() > 0) {
msg->setMessage("tunings", tunings);
}
msg->setPointer("errorDetailMsg", errorDetailMsg);
sp<AMessage> response;
- status_t err = PostAndAwaitResponse(msg, &response);
+ err = PostAndAwaitResponse(msg, &response);
return err;
}
@@ -4758,6 +4845,35 @@
}
}
}
+ int32_t largeFrameParamMax = 0, largeFrameParamThreshold = 0;
+ if (format->findInt32(KEY_BUFFER_BATCH_MAX_OUTPUT_SIZE, &largeFrameParamMax) ||
+ format->findInt32(KEY_BUFFER_BATCH_THRESHOLD_OUTPUT_SIZE,
+ &largeFrameParamThreshold)) {
+ if (largeFrameParamMax > 0 || largeFrameParamThreshold > 0) {
+ if(mComponentName.startsWith("OMX")) {
+ mErrorLog.log(LOG_TAG,
+ "Large Frame params are not supported on OMX codecs."
+ "Currently only supported on C2 audio codec.");
+ PostReplyWithError(replyID, INVALID_OPERATION);
+ break;
+ }
+ AString mime;
+ CHECK(format->findString("mime", &mime));
+ if (!mime.startsWith("audio")) {
+ mErrorLog.log(LOG_TAG,
+ "Large Frame params only works with audio codec");
+ PostReplyWithError(replyID, INVALID_OPERATION);
+ break;
+ }
+ if (!(mFlags & kFlagIsAsync)) {
+ mErrorLog.log(LOG_TAG, "Large Frame audio" \
+ "config works only with async mode");
+ PostReplyWithError(replyID, INVALID_OPERATION);
+ break;
+ }
+ }
+ }
+
mReplyID = replyID;
setState(CONFIGURING);
@@ -5906,10 +6022,10 @@
status_t MediaCodec::onQueueInputBuffer(const sp<AMessage> &msg) {
size_t index;
- size_t offset;
- size_t size;
- int64_t timeUs;
- uint32_t flags;
+ size_t offset = 0;
+ size_t size = 0;
+ int64_t timeUs = 0;
+ uint32_t flags = 0;
CHECK(msg->findSize("index", &index));
CHECK(msg->findInt64("timeUs", &timeUs));
CHECK(msg->findInt32("flags", (int32_t *)&flags));
@@ -5991,9 +6107,13 @@
"client does not own the buffer #%zu", index));
return -EACCES;
}
- auto setInputBufferParams = [this, &buffer]
+ auto setInputBufferParams = [this, &msg, &buffer]
(int64_t timeUs, uint32_t flags = 0) -> status_t {
status_t err = OK;
+ sp<RefBase> obj;
+ if (msg->findObject("accessUnitInfo", &obj)) {
+ buffer->meta()->setObject("accessUnitInfo", obj);
+ }
buffer->meta()->setInt64("timeUs", timeUs);
if (flags & BUFFER_FLAG_EOS) {
buffer->meta()->setInt32("eos", true);
@@ -6503,10 +6623,11 @@
if (discardDecodeOnlyOutputBuffer(index)) {
continue;
}
+ sp<AMessage> msg = mCallback->dup();
const sp<MediaCodecBuffer> &buffer =
mPortBuffers[kPortIndexOutput][index].mData;
- sp<AMessage> msg = mCallback->dup();
- msg->setInt32("callbackID", CB_OUTPUT_AVAILABLE);
+ int32_t outputCallbackID = CB_OUTPUT_AVAILABLE;
+ sp<RefBase> accessUnitInfoObj;
msg->setInt32("index", index);
msg->setSize("offset", buffer->offset());
msg->setSize("size", buffer->size());
@@ -6520,6 +6641,15 @@
CHECK(buffer->meta()->findInt32("flags", &flags));
msg->setInt32("flags", flags);
+ buffer->meta()->findObject("accessUnitInfo", &accessUnitInfoObj);
+ if (accessUnitInfoObj) {
+ outputCallbackID = CB_LARGE_FRAME_OUTPUT_AVAILABLE;
+ msg->setObject("accessUnitInfo", accessUnitInfoObj);
+ sp<BufferInfosWrapper> auInfo(
+ (decltype(auInfo.get()))accessUnitInfoObj.get());
+ auInfo->value.back().mFlags |= flags & BUFFER_FLAG_END_OF_STREAM;
+ }
+ msg->setInt32("callbackID", outputCallbackID);
statsBufferReceived(timeUs, buffer);
diff --git a/media/libstagefright/TEST_MAPPING b/media/libstagefright/TEST_MAPPING
index 22885c9..5dd8423 100644
--- a/media/libstagefright/TEST_MAPPING
+++ b/media/libstagefright/TEST_MAPPING
@@ -1,8 +1,5 @@
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
// writerTest fails about 5 out of 66
// { "name": "writerTest" },
diff --git a/media/libstagefright/data/media_codecs_sw.xml b/media/libstagefright/data/media_codecs_sw.xml
index 24020d1..dc7d787 100644
--- a/media/libstagefright/data/media_codecs_sw.xml
+++ b/media/libstagefright/data/media_codecs_sw.xml
@@ -330,6 +330,7 @@
<!-- Video Quality control -->
<!-- supports QP bounding with standard keys -->
<Feature name="qp-bounds" />
+ <Feature name="bitrate-modes" value="VBR,CBR" />
<Attribute name="software-codec" />
</MediaCodec>
<MediaCodec name="c2.android.vp8.encoder" type="video/x-vnd.on2.vp8" variant="slow-cpu,!slow-cpu">
diff --git a/media/libstagefright/include/media/stagefright/CodecBase.h b/media/libstagefright/include/media/stagefright/CodecBase.h
index 0927653..8741daa 100644
--- a/media/libstagefright/include/media/stagefright/CodecBase.h
+++ b/media/libstagefright/include/media/stagefright/CodecBase.h
@@ -61,6 +61,16 @@
using hardware::cas::native::V1_0::IDescrambler;
+struct AccessUnitInfo {
+ uint32_t mFlags;
+ uint32_t mSize;
+ int64_t mTimestamp;
+ AccessUnitInfo(uint32_t flags, uint32_t size, int64_t ptsUs)
+ :mFlags(flags), mSize(size), mTimestamp(ptsUs) {
+ }
+ ~AccessUnitInfo() {}
+};
+
struct CodecParameterDescriptor {
std::string name;
AMessage::Type type;
diff --git a/media/libstagefright/include/media/stagefright/MPEG4Writer.h b/media/libstagefright/include/media/stagefright/MPEG4Writer.h
index 054a4b8..1ff8acf 100644
--- a/media/libstagefright/include/media/stagefright/MPEG4Writer.h
+++ b/media/libstagefright/include/media/stagefright/MPEG4Writer.h
@@ -77,6 +77,9 @@
virtual void setStartTimeOffsetMs(int ms) { mStartTimeOffsetMs = ms; }
virtual int32_t getStartTimeOffsetMs() const { return mStartTimeOffsetMs; }
virtual status_t setNextFd(int fd);
+ // Returns true if the timestamp is valid which is compatible with the Mpeg4.
+ // Note that this overloads that method in the base class.
+ bool isSampleMetadataValid(size_t trackIndex, int64_t timeUs) override;
protected:
virtual ~MPEG4Writer();
diff --git a/media/libstagefright/include/media/stagefright/MediaCodec.h b/media/libstagefright/include/media/stagefright/MediaCodec.h
index 2f94e5e..b0b1427 100644
--- a/media/libstagefright/include/media/stagefright/MediaCodec.h
+++ b/media/libstagefright/include/media/stagefright/MediaCodec.h
@@ -28,6 +28,7 @@
#include <media/MediaMetrics.h>
#include <media/MediaProfiles.h>
#include <media/stagefright/foundation/AHandler.h>
+#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/CodecErrorLog.h>
#include <media/stagefright/FrameRenderTracker.h>
#include <media/stagefright/MediaHistogram.h>
@@ -56,6 +57,7 @@
struct AString;
struct BatteryChecker;
class BufferChannelBase;
+struct AccessUnitInfo;
struct CodecBase;
struct CodecParameterDescriptor;
class IBatteryStats;
@@ -78,6 +80,8 @@
using aidl::android::media::MediaResourceParcel;
using aidl::android::media::ClientConfigParcel;
+typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
+
struct MediaCodec : public AHandler {
enum Domain {
DOMAIN_UNKNOWN = 0,
@@ -115,6 +119,7 @@
CB_OUTPUT_FORMAT_CHANGED = 4,
CB_RESOURCE_RECLAIMED = 5,
CB_CRYPTO_ERROR = 6,
+ CB_LARGE_FRAME_OUTPUT_AVAILABLE = 7,
};
static const pid_t kNoPid = -1;
@@ -185,6 +190,13 @@
uint32_t flags,
AString *errorDetailMsg = NULL);
+ status_t queueInputBuffers(
+ size_t index,
+ size_t offset,
+ size_t size,
+ const sp<BufferInfosWrapper> &accessUnitInfo,
+ AString *errorDetailMsg = NULL);
+
status_t queueSecureInputBuffer(
size_t index,
size_t offset,
@@ -201,8 +213,7 @@
status_t queueBuffer(
size_t index,
const std::shared_ptr<C2Buffer> &buffer,
- int64_t presentationTimeUs,
- uint32_t flags,
+ const sp<BufferInfosWrapper> &bufferInfos,
const sp<AMessage> &tunings,
AString *errorDetailMsg = NULL);
@@ -216,8 +227,7 @@
const uint8_t iv[16],
CryptoPlugin::Mode mode,
const CryptoPlugin::Pattern &pattern,
- int64_t presentationTimeUs,
- uint32_t flags,
+ const sp<BufferInfosWrapper> &bufferInfos,
const sp<AMessage> &tunings,
AString *errorDetailMsg = NULL);
@@ -321,7 +331,10 @@
friend struct ResourceManagerClient;
// to create the metrics associated with this codec.
- mediametrics_handle_t createMediaMetrics(const sp<AMessage>& format, uint32_t flags);
+ // Any error in this function will be captured by the output argument err.
+ mediametrics_handle_t createMediaMetrics(const sp<AMessage>& format,
+ uint32_t flags,
+ status_t* err);
private:
enum State {
diff --git a/media/libstagefright/include/media/stagefright/SkipCutBuffer.h b/media/libstagefright/include/media/stagefright/SkipCutBuffer.h
index 0fb5690..66f0bb1 100644
--- a/media/libstagefright/include/media/stagefright/SkipCutBuffer.h
+++ b/media/libstagefright/include/media/stagefright/SkipCutBuffer.h
@@ -59,6 +59,12 @@
int32_t mReadHead;
int32_t mCapacity;
char* mCutBuffer;
+
+ /*
+ * Added to use Access unit skip cut in Codec2 framework
+ */
+ friend class MultiAccessUnitSkipCutBuffer;
+
DISALLOW_EVIL_CONSTRUCTORS(SkipCutBuffer);
};
diff --git a/media/libstagefright/timedtext/TEST_MAPPING b/media/libstagefright/timedtext/TEST_MAPPING
index 35a5b11..f011d04 100644
--- a/media/libstagefright/timedtext/TEST_MAPPING
+++ b/media/libstagefright/timedtext/TEST_MAPPING
@@ -1,9 +1,5 @@
-// mappings for frameworks/av/media/libstagefright/timedtext
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
{ "name": "TimedTextUnitTest" }
]
}
diff --git a/media/module/codecs/amrnb/TEST_MAPPING b/media/module/codecs/amrnb/TEST_MAPPING
index 343d08a..306921f 100644
--- a/media/module/codecs/amrnb/TEST_MAPPING
+++ b/media/module/codecs/amrnb/TEST_MAPPING
@@ -1,9 +1,5 @@
-// mappings for frameworks/av/media/libstagefright/codecs/amrnb
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
{ "name": "AmrnbDecoderTest"},
{ "name": "AmrnbEncoderTest"}
]
diff --git a/media/module/codecs/amrwb/TEST_MAPPING b/media/module/codecs/amrwb/TEST_MAPPING
new file mode 100644
index 0000000..3f05c90
--- /dev/null
+++ b/media/module/codecs/amrwb/TEST_MAPPING
@@ -0,0 +1,6 @@
+{
+ "postsubmit": [
+ { "name": "AmrwbDecoderTest"},
+ { "name": "AmrwbEncoderTest"}
+ ]
+}
diff --git a/media/module/codecs/amrwb/dec/TEST_MAPPING b/media/module/codecs/amrwb/dec/TEST_MAPPING
deleted file mode 100644
index 0278d26..0000000
--- a/media/module/codecs/amrwb/dec/TEST_MAPPING
+++ /dev/null
@@ -1,10 +0,0 @@
-// mappings for frameworks/av/media/libstagefright/codecs/amrwb
-{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
- { "name": "AmrwbDecoderTest"}
-
- ]
-}
diff --git a/media/module/codecs/amrwb/enc/TEST_MAPPING b/media/module/codecs/amrwb/enc/TEST_MAPPING
deleted file mode 100644
index 045e8b3..0000000
--- a/media/module/codecs/amrwb/enc/TEST_MAPPING
+++ /dev/null
@@ -1,10 +0,0 @@
-// mappings for frameworks/av/media/libstagefright/codecs/amrwbenc
-{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
- { "name": "AmrwbEncoderTest"}
-
- ]
-}
diff --git a/media/module/codecs/flac/TEST_MAPPING b/media/module/codecs/flac/TEST_MAPPING
new file mode 100644
index 0000000..725ea90
--- /dev/null
+++ b/media/module/codecs/flac/TEST_MAPPING
@@ -0,0 +1,5 @@
+{
+ "postsubmit": [
+ { "name": "FlacDecoderTest"}
+ ]
+}
diff --git a/media/module/codecs/flac/dec/test/Android.bp b/media/module/codecs/flac/dec/test/Android.bp
index a4c2735..8004c4a 100644
--- a/media/module/codecs/flac/dec/test/Android.bp
+++ b/media/module/codecs/flac/dec/test/Android.bp
@@ -28,6 +28,7 @@
cc_test {
name: "FlacDecoderTest",
gtest: true,
+ test_suites: ["device-tests"],
srcs: [
"FlacDecoderTest.cpp",
diff --git a/media/module/codecs/m4v_h263/TEST_MAPPING b/media/module/codecs/m4v_h263/TEST_MAPPING
index ba3ff1c..8599fa5 100644
--- a/media/module/codecs/m4v_h263/TEST_MAPPING
+++ b/media/module/codecs/m4v_h263/TEST_MAPPING
@@ -1,18 +1,6 @@
-// mappings for frameworks/av/media/libstagefright/codecs/m4v_h263
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
-
- // the decoder reports something bad about an unexpected newline in the *config file
- // and the config file looks like the AndroidTest.xml file that we put in there.
- // I don't get this from the Encoder -- and I don't see any substantive difference
- // between decode and encode AndroidTest.xml files -- except that encode does NOT
- // finish with a newline.
- // strange.
+ "postsubmit": [
{ "name": "Mpeg4H263DecoderTest"},
{ "name": "Mpeg4H263EncoderTest"}
-
]
}
diff --git a/media/module/codecs/mp3dec/TEST_MAPPING b/media/module/codecs/mp3dec/TEST_MAPPING
index 4ef4317..5faece6 100644
--- a/media/module/codecs/mp3dec/TEST_MAPPING
+++ b/media/module/codecs/mp3dec/TEST_MAPPING
@@ -1,9 +1,5 @@
-// mappings for frameworks/av/media/libstagefright/codecs/mp3dec
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
{ "name": "Mp3DecoderTest"}
]
}
diff --git a/media/module/esds/TEST_MAPPING b/media/module/esds/TEST_MAPPING
index 9368b6d..0337743 100644
--- a/media/module/esds/TEST_MAPPING
+++ b/media/module/esds/TEST_MAPPING
@@ -1,9 +1,5 @@
-// mappings for frameworks/av/media/module/esds
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
{ "name": "ESDSTest" }
]
}
diff --git a/media/module/esds/tests/Android.bp b/media/module/esds/tests/Android.bp
index aea611e..427b275 100644
--- a/media/module/esds/tests/Android.bp
+++ b/media/module/esds/tests/Android.bp
@@ -25,6 +25,7 @@
cc_test {
name: "ESDSTest",
gtest: true,
+ test_suites: ["device-tests"],
srcs: [
"ESDSTest.cpp",
diff --git a/media/module/foundation/TEST_MAPPING b/media/module/foundation/TEST_MAPPING
index a70c352..ea4e4fd 100644
--- a/media/module/foundation/TEST_MAPPING
+++ b/media/module/foundation/TEST_MAPPING
@@ -1,9 +1,6 @@
-// mappings for frameworks/av/media/libstagefright/foundation
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
+ { "name": "AVCUtilsUnitTest" },
{ "name": "OpusHeaderTest" }
],
diff --git a/media/module/foundation/include/media/stagefright/foundation/AMessage.h b/media/module/foundation/include/media/stagefright/foundation/AMessage.h
index 7594565..b301c53 100644
--- a/media/module/foundation/include/media/stagefright/foundation/AMessage.h
+++ b/media/module/foundation/include/media/stagefright/foundation/AMessage.h
@@ -356,6 +356,16 @@
DISALLOW_EVIL_CONSTRUCTORS(AMessage);
};
+/*
+ * Helper struct for wrapping any object with RefBase.
+ */
+template <typename T>
+struct WrapperObject : public RefBase {
+ WrapperObject(const T& v) : value(v) {}
+ WrapperObject(T&& v) : value(std::move(v)) {}
+ T value;
+};
+
} // namespace android
#endif // A_MESSAGE_H_
diff --git a/media/module/foundation/tests/AVCUtils/Android.bp b/media/module/foundation/tests/AVCUtils/Android.bp
index ee7db21..c306c73 100644
--- a/media/module/foundation/tests/AVCUtils/Android.bp
+++ b/media/module/foundation/tests/AVCUtils/Android.bp
@@ -28,6 +28,7 @@
cc_test {
name: "AVCUtilsUnitTest",
gtest: true,
+ test_suites: ["device-tests"],
srcs: [
"AVCUtilsUnitTest.cpp",
diff --git a/media/module/foundation/tests/AVCUtils/AndroidTest.xml b/media/module/foundation/tests/AVCUtils/AndroidTest.xml
index e30bfbf..315373f 100644
--- a/media/module/foundation/tests/AVCUtils/AndroidTest.xml
+++ b/media/module/foundation/tests/AVCUtils/AndroidTest.xml
@@ -16,7 +16,7 @@
<configuration description="Test module config for AVC Utils unit tests">
<option name="test-suite-tag" value="AVCUtilsUnitTest" />
<target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
- <option name="cleanup" value="false" />
+ <option name="cleanup" value="true" />
<option name="push" value="AVCUtilsUnitTest->/data/local/tmp/AVCUtilsUnitTest" />
</target_preparer>
diff --git a/media/module/id3/TEST_MAPPING b/media/module/id3/TEST_MAPPING
index 6106908..497d984 100644
--- a/media/module/id3/TEST_MAPPING
+++ b/media/module/id3/TEST_MAPPING
@@ -1,9 +1,5 @@
-// frameworks/av/media/libstagefright/id3
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
{ "name": "ID3Test" }
],
diff --git a/media/module/mpeg2ts/TEST_MAPPING b/media/module/mpeg2ts/TEST_MAPPING
index 9f4bbdf..536450f 100644
--- a/media/module/mpeg2ts/TEST_MAPPING
+++ b/media/module/mpeg2ts/TEST_MAPPING
@@ -1,9 +1,5 @@
-// frameworks/av/media/libstagefright/mpeg2ts
{
- // tests which require dynamic content
- // invoke with: atest -- --enable-module-dynamic-download=true
- // TODO(b/148094059): unit tests not allowed to download content
- "dynamic-presubmit": [
+ "postsubmit": [
{ "name": "Mpeg2tsUnitTest" }
]
}
diff --git a/services/audioflinger/IAfTrack.h b/services/audioflinger/IAfTrack.h
index 2302e13..ac4ed36 100644
--- a/services/audioflinger/IAfTrack.h
+++ b/services/audioflinger/IAfTrack.h
@@ -18,6 +18,7 @@
#include <android/media/BnAudioRecord.h>
#include <android/media/BnAudioTrack.h>
+#include <audio_utils/mutex.h>
#include <audiomanager/IAudioManager.h>
#include <binder/IMemory.h>
#include <fastpath/FastMixerDumpState.h>
@@ -351,7 +352,8 @@
virtual sp<os::ExternalVibration> getExternalVibration() const = 0;
// This function should be called with holding thread lock.
- virtual void updateTeePatches_l() = 0;
+ virtual void updateTeePatches_l() REQUIRES(audio_utils::ThreadBase_Mutex)
+ EXCLUDES_BELOW_ThreadBase_Mutex = 0;
// Argument teePatchesToUpdate is by value, use std::move to optimize.
virtual void setTeePatchesToUpdate_l(TeePatches teePatchesToUpdate) = 0;
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index b4cb805..826ba65 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -194,7 +194,8 @@
sp<os::ExternalVibration> getExternalVibration() const final { return mExternalVibration; }
// This function should be called with holding thread lock.
- void updateTeePatches_l() final;
+ void updateTeePatches_l() final REQUIRES(audio_utils::ThreadBase_Mutex)
+ EXCLUDES_BELOW_ThreadBase_Mutex;
void setTeePatchesToUpdate_l(TeePatches teePatchesToUpdate) final;
void tallyUnderrunFrames(size_t frames) final {
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index f9f6b40..767c502 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -724,8 +724,9 @@
{
audio_utils::unique_lock _l(event->mutex());
while (event->mWaitStatus) {
- if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
- == std::cv_status::timeout) {
+ if (event->mCondition.wait_for(
+ _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
+ == std::cv_status::timeout) {
event->mStatus = TIMED_OUT;
event->mWaitStatus = false;
}
@@ -3319,7 +3320,11 @@
return {}; // nothing to do
}
StreamOutHalInterface::SourceMetadata metadata;
- if (com_android_media_audio_stereo_spatialization()) {
+ static const bool stereo_spatialization_property =
+ property_get_bool("ro.audio.stereo_spatialization_enabled", false);
+ const bool stereo_spatialization_enabled =
+ stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
+ if (stereo_spatialization_enabled) {
std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
for (const sp<IAfTrack>& track : mActiveTracks) {
std::vector<playback_track_metadata_v7_t>& sessionMetadata =
@@ -4183,6 +4188,30 @@
metadataUpdate = updateMetadata_l();
+ // Acquire a local copy of active tracks with lock (release w/o lock).
+ //
+ // Control methods on the track acquire the ThreadBase lock (e.g. start()
+ // stop(), pause(), etc.), but the threadLoop is entitled to call audio
+ // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
+ activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
+
+ setHalLatencyMode_l();
+
+ // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
+ // so this is done before we lock our effect chains.
+ for (const auto& track : mActiveTracks) {
+ track->updateTeePatches_l();
+ }
+
+ // signal actual start of output stream when the render position reported by
+ // the kernel starts moving.
+ if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
+ && (mKernelPositionOnStandby
+ != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
+ mHalStarted = true;
+ mWaitHalStartCV.notify_all();
+ }
+
// prevent any changes in effect chain list and in each effect chain
// during mixing and effect process as the audio buffers could be deleted
// or modified if an effect is created or deleted
@@ -4210,28 +4239,6 @@
}
}
}
-
- // Acquire a local copy of active tracks with lock (release w/o lock).
- //
- // Control methods on the track acquire the ThreadBase lock (e.g. start()
- // stop(), pause(), etc.), but the threadLoop is entitled to call audio
- // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
- activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
-
- setHalLatencyMode_l();
-
- for (const auto &track : mActiveTracks ) {
- track->updateTeePatches_l();
- }
-
- // signal actual start of output stream when the render position reported by the kernel
- // starts moving.
- if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
- && (mKernelPositionOnStandby
- != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
- mHalStarted = true;
- mWaitHalStartCV.notify_all();
- }
} // mutex() scope ends
if (mBytesRemaining == 0) {
@@ -7896,16 +7903,12 @@
// (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
// AND
// - At least one active track is spatialized
- bool hasSpatializedActiveTrack = false;
for (const auto& track : mActiveTracks) {
if (track->isSpatialized()) {
- hasSpatializedActiveTrack = true;
+ latencyMode = mRequestedLatencyMode;
break;
}
}
- if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
- latencyMode = AUDIO_LATENCY_MODE_LOW;
- }
}
if (latencyMode != mSetLatencyMode) {
@@ -7919,7 +7922,7 @@
}
status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
- if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
+ if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
return BAD_VALUE;
}
audio_utils::lock_guard _l(mutex());
diff --git a/services/audioflinger/sounddose/tests/Android.bp b/services/audioflinger/sounddose/tests/Android.bp
index 2a2addf..60e170d 100644
--- a/services/audioflinger/sounddose/tests/Android.bp
+++ b/services/audioflinger/sounddose/tests/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_base_license"
@@ -11,7 +12,7 @@
name: "sounddosemanager_tests",
srcs: [
- "sounddosemanager_tests.cpp"
+ "sounddosemanager_tests.cpp",
],
defaults: [
diff --git a/services/audioparameterparser/Android.bp b/services/audioparameterparser/Android.bp
new file mode 100644
index 0000000..18205bd
--- /dev/null
+++ b/services/audioparameterparser/Android.bp
@@ -0,0 +1,70 @@
+// Copyright (C) 2024 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 {
+ default_applicable_licenses: [
+ "frameworks_av_services_audioparameterparser_license",
+ ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+ name: "frameworks_av_services_audioparameterparser_license",
+ visibility: [":__subpackages__"],
+ license_kinds: [
+ "SPDX-license-identifier-Apache-2.0",
+ ],
+ license_text: [
+ "NOTICE",
+ ],
+}
+
+cc_defaults {
+ name: "android.hardware.audio.parameter_parser.example_defaults",
+ defaults: [
+ "latest_android_hardware_audio_core_ndk_shared",
+ ],
+
+ shared_libs: [
+ "av-audio-types-aidl-V1-ndk",
+ "libbase",
+ "libbinder_ndk",
+ ],
+
+ cflags: [
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-Wthread-safety",
+ ],
+}
+
+cc_binary {
+ name: "android.hardware.audio.parameter_parser.example_service",
+ system_ext_specific: true,
+ relative_install_path: "hw",
+
+ init_rc: ["android.hardware.audio.parameter_parser.example_service.rc"],
+ vintf_fragments: ["android.hardware.audio.parameter_parser.example_service.xml"],
+
+ defaults: [
+ "android.hardware.audio.parameter_parser.example_defaults",
+ ],
+
+ srcs: [
+ "ParameterParser.cpp",
+ "main.cpp",
+ ],
+}
diff --git a/services/audioparameterparser/NOTICE b/services/audioparameterparser/NOTICE
new file mode 100644
index 0000000..44158cb
--- /dev/null
+++ b/services/audioparameterparser/NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2005-2024, The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/services/audioparameterparser/ParameterParser.cpp b/services/audioparameterparser/ParameterParser.cpp
new file mode 100644
index 0000000..8d6a64f
--- /dev/null
+++ b/services/audioparameterparser/ParameterParser.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 "ParameterParser.h"
+
+#define LOG_TAG "Audio_ParameterParser"
+#include <android-base/logging.h>
+
+namespace vendor::audio::parserservice {
+
+using ::aidl::android::hardware::audio::core::VendorParameter;
+using ParameterScope = ::aidl::android::media::audio::IHalAdapterVendorExtension::ParameterScope;
+
+::ndk::ScopedAStatus ParameterParser::parseVendorParameterIds(ParameterScope in_scope,
+ const std::string& in_rawKeys,
+ std::vector<std::string>*) {
+ LOG(DEBUG) << __func__ << ": scope: " << toString(in_scope) << ", keys: " << in_rawKeys;
+ return ::ndk::ScopedAStatus::ok();
+}
+
+::ndk::ScopedAStatus ParameterParser::parseVendorParameters(ParameterScope in_scope,
+ const std::string& in_rawKeysAndValues,
+ std::vector<VendorParameter>*,
+ std::vector<VendorParameter>*) {
+ LOG(DEBUG) << __func__ << ": scope: " << toString(in_scope)
+ << ", keys/values: " << in_rawKeysAndValues;
+ return ::ndk::ScopedAStatus::ok();
+}
+
+::ndk::ScopedAStatus ParameterParser::parseBluetoothA2dpReconfigureOffload(
+ const std::string& in_rawValue, std::vector<VendorParameter>*) {
+ LOG(DEBUG) << __func__ << ": value: " << in_rawValue;
+ return ::ndk::ScopedAStatus::ok();
+}
+
+::ndk::ScopedAStatus ParameterParser::parseBluetoothLeReconfigureOffload(
+ const std::string& in_rawValue, std::vector<VendorParameter>*) {
+ LOG(DEBUG) << __func__ << ": value: " << in_rawValue;
+ return ::ndk::ScopedAStatus::ok();
+}
+
+::ndk::ScopedAStatus ParameterParser::processVendorParameters(
+ ParameterScope in_scope, const std::vector<VendorParameter>& in_parameters, std::string*) {
+ LOG(DEBUG) << __func__ << ": scope: " << toString(in_scope)
+ << ", parameters: " << ::android::internal::ToString(in_parameters);
+ return ::ndk::ScopedAStatus::ok();
+}
+
+} // namespace vendor::audio::parserservice
diff --git a/services/audioparameterparser/ParameterParser.h b/services/audioparameterparser/ParameterParser.h
new file mode 100644
index 0000000..1e0e333
--- /dev/null
+++ b/services/audioparameterparser/ParameterParser.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <aidl/android/media/audio/BnHalAdapterVendorExtension.h>
+
+namespace vendor::audio::parserservice {
+
+class ParameterParser : public ::aidl::android::media::audio::BnHalAdapterVendorExtension {
+ public:
+ ParameterParser() = default;
+
+ private:
+ ::ndk::ScopedAStatus parseVendorParameterIds(
+ ::aidl::android::media::audio::IHalAdapterVendorExtension::ParameterScope in_scope,
+ const std::string& in_rawKeys, std::vector<std::string>* _aidl_return) override;
+
+ ::ndk::ScopedAStatus parseVendorParameters(
+ ::aidl::android::media::audio::IHalAdapterVendorExtension::ParameterScope in_scope,
+ const std::string& in_rawKeysAndValues,
+ std::vector<::aidl::android::hardware::audio::core::VendorParameter>*
+ out_syncParameters,
+ std::vector<::aidl::android::hardware::audio::core::VendorParameter>*
+ out_asyncParameters) override;
+
+ ::ndk::ScopedAStatus parseBluetoothA2dpReconfigureOffload(
+ const std::string& in_rawValue,
+ std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return)
+ override;
+
+ ::ndk::ScopedAStatus parseBluetoothLeReconfigureOffload(
+ const std::string& in_rawValue,
+ std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return)
+ override;
+
+ ::ndk::ScopedAStatus processVendorParameters(
+ ::aidl::android::media::audio::IHalAdapterVendorExtension::ParameterScope in_scope,
+ const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&
+ in_parameters,
+ std::string* _aidl_return) override;
+};
+
+} // namespace vendor::audio::parserservice
diff --git a/services/audioparameterparser/android.hardware.audio.parameter_parser.example_service.rc b/services/audioparameterparser/android.hardware.audio.parameter_parser.example_service.rc
new file mode 100644
index 0000000..b6aca5c
--- /dev/null
+++ b/services/audioparameterparser/android.hardware.audio.parameter_parser.example_service.rc
@@ -0,0 +1,6 @@
+service audio_parameter_parser_service /system_ext/bin/hw/android.hardware.audio.parameter_parser.example_service
+ class core
+ user audioserver
+ group media
+ ioprio rt 4
+ task_profiles ProcessCapacityHigh HighPerformance
diff --git a/services/audioparameterparser/android.hardware.audio.parameter_parser.example_service.xml b/services/audioparameterparser/android.hardware.audio.parameter_parser.example_service.xml
new file mode 100644
index 0000000..91addaa
--- /dev/null
+++ b/services/audioparameterparser/android.hardware.audio.parameter_parser.example_service.xml
@@ -0,0 +1,7 @@
+<manifest version="1.0" type="framework">
+ <hal format="aidl">
+ <name>android.media.audio</name>
+ <version>1</version>
+ <fqname>IHalAdapterVendorExtension/default</fqname>
+ </hal>
+</manifest>
diff --git a/services/audioparameterparser/main.cpp b/services/audioparameterparser/main.cpp
new file mode 100644
index 0000000..d22eb55
--- /dev/null
+++ b/services/audioparameterparser/main.cpp
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 "Audio_ParameterParser"
+#include <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+
+#include "ParameterParser.h"
+
+using vendor::audio::parserservice::ParameterParser;
+
+int main() {
+ // This is a debug implementation, always enable debug logging.
+ android::base::SetMinimumLogSeverity(::android::base::DEBUG);
+
+ auto parser = ndk::SharedRefBase::make<ParameterParser>();
+ const std::string parserFqn =
+ std::string().append(ParameterParser::descriptor).append("/default");
+ binder_status_t status =
+ AServiceManager_addService(parser->asBinder().get(), parserFqn.c_str());
+ if (status != STATUS_OK) {
+ LOG(ERROR) << "failed to register service for \"" << parserFqn << "\"";
+ }
+
+ ABinderProcess_joinThreadPool();
+ return EXIT_FAILURE; // should not reach
+}
diff --git a/services/audiopolicy/Android.bp b/services/audiopolicy/Android.bp
index e018dd3..b33bba3 100644
--- a/services/audiopolicy/Android.bp
+++ b/services/audiopolicy/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/common/Android.bp b/services/audiopolicy/common/Android.bp
index 91701ad..a699b8b 100644
--- a/services/audiopolicy/common/Android.bp
+++ b/services/audiopolicy/common/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/common/managerdefinitions/Android.bp b/services/audiopolicy/common/managerdefinitions/Android.bp
index 8b76842..598d52d 100644
--- a/services/audiopolicy/common/managerdefinitions/Android.bp
+++ b/services/audiopolicy/common/managerdefinitions/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/config/Android.bp b/services/audiopolicy/config/Android.bp
index 86600f4..7d529df 100644
--- a/services/audiopolicy/config/Android.bp
+++ b/services/audiopolicy/config/Android.bp
@@ -18,6 +18,7 @@
}
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -31,41 +32,49 @@
vendor: true,
src: ":a2dp_in_audio_policy_configuration",
}
+
prebuilt_etc {
name: "a2dp_audio_policy_configuration.xml",
vendor: true,
src: ":a2dp_audio_policy_configuration",
}
+
prebuilt_etc {
name: "audio_policy_configuration.xml",
vendor: true,
src: ":audio_policy_configuration_generic",
}
+
prebuilt_etc {
name: "r_submix_audio_policy_configuration.xml",
vendor: true,
src: ":r_submix_audio_policy_configuration",
}
+
prebuilt_etc {
name: "audio_policy_volumes.xml",
vendor: true,
src: ":audio_policy_volumes",
}
+
prebuilt_etc {
name: "default_volume_tables.xml",
vendor: true,
src: ":default_volume_tables",
}
+
prebuilt_etc {
name: "surround_sound_configuration_5_0.xml",
vendor: true,
src: ":surround_sound_configuration_5_0",
}
+
prebuilt_etc {
name: "usb_audio_policy_configuration.xml",
vendor: true,
src: ":usb_audio_policy_configuration",
}
+
prebuilt_etc {
name: "primary_audio_policy_configuration.xml",
src: ":primary_audio_policy_configuration",
@@ -76,50 +85,62 @@
name: "a2dp_in_audio_policy_configuration",
srcs: ["a2dp_in_audio_policy_configuration.xml"],
}
+
filegroup {
name: "a2dp_audio_policy_configuration",
srcs: ["a2dp_audio_policy_configuration.xml"],
}
+
filegroup {
name: "primary_audio_policy_configuration",
srcs: ["primary_audio_policy_configuration.xml"],
}
+
filegroup {
name: "surround_sound_configuration_5_0",
srcs: ["surround_sound_configuration_5_0.xml"],
}
+
filegroup {
name: "default_volume_tables",
srcs: ["default_volume_tables.xml"],
}
+
filegroup {
name: "audio_policy_volumes",
srcs: ["audio_policy_volumes.xml"],
}
+
filegroup {
name: "audio_policy_configuration_generic",
srcs: ["audio_policy_configuration_generic.xml"],
}
+
filegroup {
name: "audio_policy_configuration_generic_configurable",
srcs: ["audio_policy_configuration_generic_configurable.xml"],
}
+
filegroup {
name: "usb_audio_policy_configuration",
srcs: ["usb_audio_policy_configuration.xml"],
}
+
filegroup {
name: "r_submix_audio_policy_configuration",
srcs: ["r_submix_audio_policy_configuration.xml"],
}
+
filegroup {
name: "bluetooth_audio_policy_configuration_7_0",
srcs: ["bluetooth_audio_policy_configuration_7_0.xml"],
}
+
filegroup {
name: "bluetooth_with_le_audio_policy_configuration_7_0",
srcs: ["bluetooth_with_le_audio_policy_configuration_7_0.xml"],
}
+
filegroup {
name: "hearing_aid_audio_policy_configuration_7_0",
srcs: ["hearing_aid_audio_policy_configuration_7_0.xml"],
diff --git a/services/audiopolicy/engine/common/Android.bp b/services/audiopolicy/engine/common/Android.bp
index 0034a04..a93c816 100644
--- a/services/audiopolicy/engine/common/Android.bp
+++ b/services/audiopolicy/engine/common/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/engine/config/Android.bp b/services/audiopolicy/engine/config/Android.bp
index 12597de..0864e6a 100644
--- a/services/audiopolicy/engine/config/Android.bp
+++ b/services/audiopolicy/engine/config/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/engine/config/tests/Android.bp b/services/audiopolicy/engine/config/tests/Android.bp
index 5d1aa16..8c7b7db 100644
--- a/services/audiopolicy/engine/config/tests/Android.bp
+++ b/services/audiopolicy/engine/config/tests/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/engine/config/tests/resources/Android.bp b/services/audiopolicy/engine/config/tests/resources/Android.bp
index 9cee978..99d62a3 100644
--- a/services/audiopolicy/engine/config/tests/resources/Android.bp
+++ b/services/audiopolicy/engine/config/tests/resources/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/engine/interface/Android.bp b/services/audiopolicy/engine/interface/Android.bp
index 5dd5adb..b1f7666 100644
--- a/services/audiopolicy/engine/interface/Android.bp
+++ b/services/audiopolicy/engine/interface/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/engineconfigurable/Android.bp b/services/audiopolicy/engineconfigurable/Android.bp
index eb2e2f4..d59ab5a 100644
--- a/services/audiopolicy/engineconfigurable/Android.bp
+++ b/services/audiopolicy/engineconfigurable/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -40,7 +41,7 @@
"libaudiopolicyengineconfigurable_pfwwrapper",
],
- shared_libs: [
+ shared_libs: [
"libaudio_aidl_conversion_common_cpp",
"libaudiofoundation",
"libaudiopolicycomponents",
diff --git a/services/audiopolicy/engineconfigurable/config/Android.bp b/services/audiopolicy/engineconfigurable/config/Android.bp
index b3d1f97..8dd13e8 100644
--- a/services/audiopolicy/engineconfigurable/config/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/Android.bp
@@ -17,6 +17,7 @@
// Root soong_namespace for common components
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -30,10 +31,12 @@
vendor: true,
src: ":audio_policy_engine_criteria",
}
+
filegroup {
name: "audio_policy_engine_criterion_types_template",
srcs: ["example/common/audio_policy_engine_criterion_types.xml.in"],
}
+
filegroup {
name: "audio_policy_engine_criteria",
srcs: ["example/common/audio_policy_engine_criteria.xml"],
diff --git a/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp b/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp
index e46b60f..fb1a71c 100644
--- a/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp
@@ -23,6 +23,7 @@
}
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -42,16 +43,19 @@
":audio_policy_engine_volumes.xml",
],
}
+
prebuilt_etc {
name: "audio_policy_engine_product_strategies.xml",
vendor: true,
src: "audio_policy_engine_product_strategies.xml",
}
+
prebuilt_etc {
name: "audio_policy_engine_volumes.xml",
vendor: true,
src: ":audio_policy_engine_volumes",
}
+
prebuilt_etc {
name: "audio_policy_engine_criterion_types.xml",
vendor: true,
@@ -69,6 +73,7 @@
":audio_policy_configuration_files",
],
}
+
filegroup {
name: "audio_policy_configuration_files",
srcs: [
@@ -79,18 +84,22 @@
":primary_audio_policy_configuration",
],
}
+
filegroup {
- name : "audio_policy_configuration_top_file",
+ name: "audio_policy_configuration_top_file",
srcs: [":audio_policy_configuration_generic"],
}
+
filegroup {
name: "audio_policy_engine_configuration",
srcs: ["audio_policy_engine_configuration.xml"],
}
+
filegroup {
name: "audio_policy_engine_volumes",
srcs: ["audio_policy_engine_volumes.xml"],
}
+
filegroup {
name: "audio_policy_engine_configuration_files",
srcs: [
diff --git a/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp b/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp
index ad6eeb1..b9abb54 100644
--- a/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp
@@ -24,6 +24,7 @@
}
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -43,11 +44,13 @@
":audio_policy_engine_volumes.xml",
],
}
+
prebuilt_etc {
name: "audio_policy_engine_product_strategies.xml",
vendor: true,
src: "audio_policy_engine_product_strategies.xml",
}
+
prebuilt_etc {
name: "audio_policy_engine_criterion_types.xml",
vendor: true,
@@ -65,6 +68,7 @@
":audio_policy_configuration_files",
],
}
+
filegroup {
name: "audio_policy_configuration_files",
srcs: [
@@ -75,10 +79,12 @@
":primary_audio_policy_configuration",
],
}
+
filegroup {
- name : "audio_policy_configuration_top_file",
+ name: "audio_policy_configuration_top_file",
srcs: [":audio_policy_configuration_generic"],
}
+
filegroup {
name: "audio_policy_engine_configuration_files",
srcs: [
diff --git a/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp b/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp
index 773a99a..67a6128 100644
--- a/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp
@@ -23,6 +23,7 @@
}
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -42,21 +43,25 @@
":audio_policy_engine_volumes.xml",
],
}
+
prebuilt_etc {
name: "audio_policy_engine_product_strategies.xml",
vendor: true,
src: "audio_policy_engine_product_strategies.xml",
}
+
prebuilt_etc {
name: "audio_policy_engine_stream_volumes.xml",
vendor: true,
src: ":audio_policy_engine_stream_volumes",
}
+
prebuilt_etc {
name: "audio_policy_engine_default_stream_volumes.xml",
vendor: true,
src: ":audio_policy_engine_default_stream_volumes",
}
+
prebuilt_etc {
name: "audio_policy_engine_criterion_types.xml",
vendor: true,
@@ -74,6 +79,7 @@
":audio_policy_configuration_files",
],
}
+
filegroup {
name: "audio_policy_configuration_files",
srcs: [
@@ -84,22 +90,27 @@
":primary_audio_policy_configuration",
],
}
+
filegroup {
- name : "audio_policy_configuration_top_file",
+ name: "audio_policy_configuration_top_file",
srcs: [":audio_policy_configuration_generic"],
}
+
filegroup {
name: "audio_policy_engine_configuration",
srcs: ["audio_policy_engine_configuration.xml"],
}
+
filegroup {
name: "audio_policy_engine_stream_volumes",
srcs: ["audio_policy_engine_stream_volumes.xml"],
}
+
filegroup {
name: "audio_policy_engine_default_stream_volumes",
srcs: ["audio_policy_engine_default_stream_volumes.xml"],
}
+
filegroup {
name: "audio_policy_engine_configuration_files",
srcs: [
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp
index ee62d5e..7fe111f 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp
@@ -17,6 +17,7 @@
// Root soong_namespace for common components
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -31,18 +32,21 @@
src: ":PolicyClass",
sub_dir: "parameter-framework/Structure/Policy",
}
+
prebuilt_etc {
name: "PolicySubsystem.xml",
vendor: true,
src: ":PolicySubsystem",
sub_dir: "parameter-framework/Structure/Policy",
}
+
prebuilt_etc {
name: "PolicySubsystem-CommonTypes.xml",
vendor: true,
src: ":buildcommontypesstructure_gen",
sub_dir: "parameter-framework/Structure/Policy",
}
+
genrule {
name: "buildcommontypesstructure_gen",
defaults: ["buildcommontypesstructurerule"],
@@ -52,34 +56,42 @@
name: "product_strategies_structure_template",
srcs: ["examples/common/Structure/ProductStrategies.xml.in"],
}
+
filegroup {
name: "PolicySubsystem",
srcs: ["examples/common/Structure/PolicySubsystem.xml"],
}
+
filegroup {
name: "PolicySubsystem-no-strategy",
srcs: ["examples/common/Structure/PolicySubsystem-no-strategy.xml"],
}
+
filegroup {
name: "common_types_structure_template",
srcs: ["examples/common/Structure/PolicySubsystem-CommonTypes.xml.in"],
}
+
filegroup {
name: "PolicyClass",
srcs: ["examples/common/Structure/PolicyClass.xml"],
}
+
filegroup {
name: "volumes.pfw",
srcs: ["examples/Settings/volumes.pfw"],
}
+
filegroup {
name: "device_for_input_source.pfw",
srcs: ["examples/Settings/device_for_input_source.pfw"],
}
+
filegroup {
name: "ParameterFrameworkConfigurationPolicy.userdebug.xml",
srcs: ["examples/ParameterFrameworkConfigurationPolicy.userdebug.xml"],
}
+
filegroup {
name: "ParameterFrameworkConfigurationPolicy.user.xml",
srcs: ["examples/ParameterFrameworkConfigurationPolicy.user.xml"],
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp
index 7d2d293..38451f2 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp
@@ -27,6 +27,7 @@
// Generate Audio Policy Parameter Framework Product Strategies Structure file from template
//
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -42,6 +43,7 @@
sub_dir: "parameter-framework/Structure/Policy",
required: ["libpolicy-subsystem"],
}
+
genrule {
name: "buildstrategiesstructure_gen",
defaults: ["buildstrategiesstructurerule"],
@@ -67,6 +69,7 @@
"PolicySubsystem-CommonTypes.xml",
],
}
+
genrule {
name: "domaingeneratorpolicyrule_gen",
enabled: false, // TODO: This module fails to build
@@ -78,6 +81,7 @@
":edd_files",
],
}
+
filegroup {
name: "edd_files",
srcs: [
@@ -86,11 +90,13 @@
"Settings/device_for_product_strategies.pfw",
],
}
+
// This is for Settings generation, must use socket port, so userdebug version is required
filegroup {
name: "audio_policy_pfw_toplevel",
srcs: [":ParameterFrameworkConfigurationPolicy.userdebug.xml"],
}
+
filegroup {
name: "audio_policy_pfw_structure_files",
srcs: [
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp
index f825e5f..eae6ae2 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp
@@ -28,6 +28,7 @@
// Generate Audio Policy Parameter Framework Product Strategies Structure file from template
//
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -43,6 +44,7 @@
sub_dir: "parameter-framework/Structure/Policy",
required: ["libpolicy-subsystem"],
}
+
genrule {
name: "buildstrategiesstructure_gen",
defaults: ["buildstrategiesstructurerule"],
@@ -68,6 +70,7 @@
"PolicySubsystem-CommonTypes.xml",
],
}
+
genrule {
name: "domaingeneratorpolicyrule_gen",
enabled: false, // TODO: This module fails to build
@@ -79,6 +82,7 @@
":edd_files",
],
}
+
filegroup {
name: "edd_files",
srcs: [
@@ -87,11 +91,13 @@
"Settings/device_for_product_strategies.pfw",
],
}
+
// This is for Settings generation, must use socket port, so userdebug version is required
filegroup {
name: "audio_policy_pfw_toplevel",
srcs: [":ParameterFrameworkConfigurationPolicy.userdebug.xml"],
}
+
filegroup {
name: "audio_policy_pfw_structure_files",
srcs: [
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp
index 4a83cbc..4e8654b 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp
@@ -27,6 +27,7 @@
// Generate Audio Policy Parameter Framework Product Strategies Structure file from template
//
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -42,6 +43,7 @@
sub_dir: "parameter-framework/Structure/Policy",
required: ["libpolicy-subsystem"],
}
+
genrule {
name: "buildstrategiesstructure_gen",
defaults: ["buildstrategiesstructurerule"],
@@ -67,6 +69,7 @@
"PolicySubsystem-CommonTypes.xml",
],
}
+
genrule {
name: "domaingeneratorpolicyrule_gen",
enabled: false, // TODO: This module fails to build
@@ -78,6 +81,7 @@
":edd_files",
],
}
+
filegroup {
name: "edd_files",
srcs: [
@@ -95,11 +99,13 @@
"Settings/device_for_product_strategy_patch.pfw",
],
}
+
// This is for Settings generation, must use socket port, so userdebug version is required
filegroup {
name: "audio_policy_pfw_toplevel",
srcs: [":ParameterFrameworkConfigurationPolicy.userdebug.xml"],
}
+
filegroup {
name: "audio_policy_pfw_structure_files",
srcs: [
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp
index 89ab892..e279a8f 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp
@@ -24,6 +24,7 @@
}
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -57,10 +58,12 @@
":edd_files",
],
}
+
filegroup {
name: "audio_policy_pfw_toplevel",
srcs: [":ParameterFrameworkConfigurationPolicy.userdebug.xml"],
}
+
filegroup {
name: "audio_policy_pfw_structure_files",
srcs: [
@@ -69,6 +72,7 @@
":buildcommontypesstructure_gen",
],
}
+
filegroup {
name: "edd_files",
srcs: [
@@ -76,6 +80,7 @@
":volumes.pfw",
],
}
+
prebuilt_etc {
name: "PolicySubsystem.xml",
vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp
index 4880547..47b8b54 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp
@@ -24,6 +24,7 @@
}
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -45,6 +46,7 @@
"PolicySubsystem-CommonTypes.xml",
],
}
+
genrule {
name: "domaingeneratorpolicyrule_gen",
enabled: false, // TODO: This module fails to build
@@ -56,10 +58,12 @@
":edd_files",
],
}
+
filegroup {
name: "audio_policy_pfw_toplevel",
srcs: [":ParameterFrameworkConfigurationPolicy.userdebug.xml"],
}
+
filegroup {
name: "audio_policy_pfw_structure_files",
srcs: [
@@ -68,6 +72,7 @@
":buildcommontypesstructure_gen",
],
}
+
filegroup {
name: "edd_files",
srcs: [
@@ -76,6 +81,7 @@
":device_for_input_source.pfw",
],
}
+
prebuilt_etc {
name: "PolicySubsystem.xml",
vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
index f7159c5..aa2163e 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -40,6 +41,6 @@
"liblog",
"libutils",
"libmedia_helper",
- "libparameter"
+ "libparameter",
],
}
diff --git a/services/audiopolicy/engineconfigurable/tools/Android.bp b/services/audiopolicy/engineconfigurable/tools/Android.bp
index 3aec064..2f77372 100644
--- a/services/audiopolicy/engineconfigurable/tools/Android.bp
+++ b/services/audiopolicy/engineconfigurable/tools/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -36,13 +37,13 @@
name: "buildpolicycriteriontypesrule",
tools: ["buildPolicyCriterionTypes"],
cmd: "cp $(locations :audio_policy_configuration_files) $(genDir)/. && " +
- "cp $(location :audio_policy_configuration_top_file) $(genDir)/audio_policy_configuration.xml && " +
- "$(location buildPolicyCriterionTypes) " +
- " --androidaudiobaseheader $(location :libaudio_system_audio_base) " +
- " --androidaudiocommonbaseheader $(location :libaudio_system_audio_common_base) " +
- "--audiopolicyconfigurationfile $(genDir)/audio_policy_configuration.xml " +
- "--criteriontypes $(location :audio_policy_engine_criterion_types_template) " +
- "--outputfile $(out)",
+ "cp $(location :audio_policy_configuration_top_file) $(genDir)/audio_policy_configuration.xml && " +
+ "$(location buildPolicyCriterionTypes) " +
+ " --androidaudiobaseheader $(location :libaudio_system_audio_base) " +
+ " --androidaudiocommonbaseheader $(location :libaudio_system_audio_common_base) " +
+ "--audiopolicyconfigurationfile $(genDir)/audio_policy_configuration.xml " +
+ "--criteriontypes $(location :audio_policy_engine_criterion_types_template) " +
+ "--outputfile $(out)",
srcs: [
// The commented inputs must be provided to use this genrule_defaults
// @todo uncomment if 1428659 is merged":android_audio_base_header_file",
@@ -81,17 +82,17 @@
"domainGeneratorConnector",
],
cmd: "mkdir -p $(genDir)/Structure/Policy && " +
- "cp $(locations :audio_policy_pfw_structure_files) $(genDir)/Structure/Policy && " +
- "cp $(location :audio_policy_pfw_toplevel) $(genDir)/top_level && " +
- "$(location domainGeneratorPolicy) " +
- "--validate " +
- "--domain-generator-tool $(location domainGeneratorConnector) " +
- "--toplevel-config $(genDir)/top_level " +
- "--criteria $(location :audio_policy_engine_criteria) " +
- "--criteriontypes $(location :audio_policy_engine_criterion_types) " +
- "--add-edds $(locations :edd_files) " +
- "--schemas-dir external/parameter-framework/upstream/schemas " +
- " > $(out)",
+ "cp $(locations :audio_policy_pfw_structure_files) $(genDir)/Structure/Policy && " +
+ "cp $(location :audio_policy_pfw_toplevel) $(genDir)/top_level && " +
+ "$(location domainGeneratorPolicy) " +
+ "--validate " +
+ "--domain-generator-tool $(location domainGeneratorConnector) " +
+ "--toplevel-config $(genDir)/top_level " +
+ "--criteria $(location :audio_policy_engine_criteria) " +
+ "--criteriontypes $(location :audio_policy_engine_criterion_types) " +
+ "--add-edds $(locations :edd_files) " +
+ "--schemas-dir external/parameter-framework/upstream/schemas " +
+ " > $(out)",
srcs: [
// The commented inputs must be provided to use this genrule_defaults
// ":audio_policy_pfw_toplevel",
@@ -118,11 +119,11 @@
genrule_defaults {
name: "buildstrategiesstructurerule",
tools: ["buildStrategiesStructureFile"],
- cmd: "cp $(locations :audio_policy_engine_configuration_files) $(genDir) && ls -l $(genDir) &&"+
- "$(location buildStrategiesStructureFile) " +
- "--audiopolicyengineconfigurationfile $(genDir)/audio_policy_engine_configuration.xml "+
- "--productstrategiesstructurefile $(location :product_strategies_structure_template) " +
- "--outputfile $(out)",
+ cmd: "cp $(locations :audio_policy_engine_configuration_files) $(genDir) && ls -l $(genDir) &&" +
+ "$(location buildStrategiesStructureFile) " +
+ "--audiopolicyengineconfigurationfile $(genDir)/audio_policy_engine_configuration.xml " +
+ "--productstrategiesstructurefile $(location :product_strategies_structure_template) " +
+ "--outputfile $(out)",
srcs: [
// The commented inputs must be provided to use this genrule_defaults
// ":audio_policy_engine_configuration_files",
@@ -146,9 +147,9 @@
name: "buildcommontypesstructurerule",
tools: ["buildCommonTypesStructureFile"],
cmd: "$(location buildCommonTypesStructureFile) " +
- "--androidaudiobaseheader $(location :libaudio_system_audio_base) " +
- "--commontypesstructure $(location :common_types_structure_template) " +
- "--outputfile $(out)",
+ "--androidaudiobaseheader $(location :libaudio_system_audio_base) " +
+ "--commontypesstructure $(location :common_types_structure_template) " +
+ "--outputfile $(out)",
srcs: [
":common_types_structure_template",
":libaudio_system_audio_base",
diff --git a/services/audiopolicy/engineconfigurable/wrapper/Android.bp b/services/audiopolicy/engineconfigurable/wrapper/Android.bp
index 0ef0b82..a897880 100644
--- a/services/audiopolicy/engineconfigurable/wrapper/Android.bp
+++ b/services/audiopolicy/engineconfigurable/wrapper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/enginedefault/Android.bp b/services/audiopolicy/enginedefault/Android.bp
index 7d4ccab..98adff0 100644
--- a/services/audiopolicy/enginedefault/Android.bp
+++ b/services/audiopolicy/enginedefault/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/enginedefault/config/example/Android.bp b/services/audiopolicy/enginedefault/config/example/Android.bp
index 59a704b..f305c39 100644
--- a/services/audiopolicy/enginedefault/config/example/Android.bp
+++ b/services/audiopolicy/enginedefault/config/example/Android.bp
@@ -20,6 +20,7 @@
}
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -38,16 +39,19 @@
":audio_policy_engine_product_strategies.xml",
],
}
+
prebuilt_etc {
name: "audio_policy_engine_product_strategies.xml",
vendor: true,
src: "phone/audio_policy_engine_product_strategies.xml",
}
+
prebuilt_etc {
name: "audio_policy_engine_stream_volumes.xml",
vendor: true,
src: "phone/audio_policy_engine_stream_volumes.xml",
}
+
prebuilt_etc {
name: "audio_policy_engine_default_stream_volumes.xml",
vendor: true,
diff --git a/services/audiopolicy/fuzzer/Android.bp b/services/audiopolicy/fuzzer/Android.bp
index fd240e3..fca02e4 100644
--- a/services/audiopolicy/fuzzer/Android.bp
+++ b/services/audiopolicy/fuzzer/Android.bp
@@ -17,6 +17,7 @@
******************************************************************************/
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/fuzzer/aidl/Android.bp b/services/audiopolicy/fuzzer/aidl/Android.bp
index 38a2cde..8b37d36 100644
--- a/services/audiopolicy/fuzzer/aidl/Android.bp
+++ b/services/audiopolicy/fuzzer/aidl/Android.bp
@@ -16,6 +16,10 @@
*
******************************************************************************/
+package {
+ default_team: "trendy_team_android_media_audio_framework",
+}
+
cc_defaults {
name: "audiopolicy_aidl_fuzzer_defaults",
shared_libs: [
diff --git a/services/audiopolicy/fuzzer/resources/Android.bp b/services/audiopolicy/fuzzer/resources/Android.bp
index 22ee256..2a2b83b 100644
--- a/services/audiopolicy/fuzzer/resources/Android.bp
+++ b/services/audiopolicy/fuzzer/resources/Android.bp
@@ -17,6 +17,7 @@
******************************************************************************/
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/audiopolicy/managerdefault/Android.bp b/services/audiopolicy/managerdefault/Android.bp
index 6a37b4e..8b2f9ea 100644
--- a/services/audiopolicy/managerdefault/Android.bp
+++ b/services/audiopolicy/managerdefault/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -44,7 +45,7 @@
"libaudioclient_aidl_conversion",
"audioclient-types-aidl-cpp",
// Flag support
- "com.android.media.audioserver-aconfig-cc"
+ "com.android.media.audioserver-aconfig-cc",
],
header_libs: [
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index 46e4d60..cce2e93 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -1632,10 +1632,13 @@
*flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
}
+ // Use the spatializer output if the content can be spatialized, no preferred mixer
+ // was specified and offload or direct playback is not explicitly requested.
*isSpatialized = false;
if (mSpatializerOutput != nullptr
&& canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
- && prefMixerConfigInfo == nullptr) {
+ && prefMixerConfigInfo == nullptr
+ && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
*isSpatialized = true;
return mSpatializerOutput->mIoHandle;
}
@@ -3328,6 +3331,7 @@
// requested device or one of the devices selected by the engine for this stream
// - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
// no specific device volume value exists for currently selected device.
+ // - Only apply the volume if the requested device is the desired device for volume control.
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
DeviceTypeSet curDevices = desc->devices().types();
@@ -3347,7 +3351,8 @@
if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
curSrcDevices.insert(device);
applyVolume = (curSrcDevices.find(
- Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
+ Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
+ && Volume::getDeviceForVolume(curSrcDevices) == device;
} else {
applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
}
@@ -6001,11 +6006,14 @@
// The caller can have the audio config criteria ignored by either passing a null ptr or
// the AUDIO_CONFIG_INITIALIZER value.
// If an audio config is specified, current policy is to only allow spatialization for
- // some positional channel masks and PCM format
+ // some positional channel masks and PCM format and for stereo if low latency performance
+ // mode is not requested.
if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
+ static const bool stereo_spatialization_enabled =
+ property_get_bool("ro.audio.stereo_spatialization_enabled", false);
const bool channel_mask_spatialized =
- com_android_media_audio_stereo_spatialization()
+ (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
? audio_channel_mask_contains_stereo(config->channel_mask)
: audio_is_channel_mask_spatialized(config->channel_mask);
if (!channel_mask_spatialized) {
@@ -6014,6 +6022,10 @@
if (!audio_is_linear_pcm(config->format)) {
return false;
}
+ if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
+ && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
+ return false;
+ }
}
sp<IOProfile> profile =
diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp
index fb55225..cddbf39 100644
--- a/services/audiopolicy/service/Android.bp
+++ b/services/audiopolicy/service/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -52,7 +53,7 @@
static_libs: [
"libeffectsconfig",
"libaudiopolicycomponents",
- ]
+ ],
}
cc_library {
@@ -75,10 +76,9 @@
],
include_dirs: [
- "frameworks/av/services/audioflinger"
+ "frameworks/av/services/audioflinger",
],
-
static_libs: [
"framework-permission-aidl-cpp",
],
diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp
index 57e2718..aed6458 100644
--- a/services/audiopolicy/service/AudioPolicyService.cpp
+++ b/services/audiopolicy/service/AudioPolicyService.cpp
@@ -2481,7 +2481,7 @@
while (command->mWaitStatus) {
nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
if (command->mCond.wait_for(
- ul, std::chrono::nanoseconds(timeOutNs)) == std::cv_status::timeout) {
+ ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
command->mStatus = TIMED_OUT;
command->mWaitStatus = false;
}
diff --git a/services/audiopolicy/service/Spatializer.cpp b/services/audiopolicy/service/Spatializer.cpp
index ca3e0e0..d85ac57 100644
--- a/services/audiopolicy/service/Spatializer.cpp
+++ b/services/audiopolicy/service/Spatializer.cpp
@@ -31,6 +31,7 @@
#include <audio_utils/fixedfft.h>
#include <com_android_media_audio.h>
#include <cutils/bitops.h>
+#include <cutils/properties.h>
#include <hardware/sensors.h>
#include <media/stagefright/foundation/AHandler.h>
#include <media/stagefright/foundation/AMessage.h>
@@ -394,8 +395,10 @@
return status;
}
for (const auto channelMask : channelMasks) {
+ static const bool stereo_spatialization_enabled =
+ property_get_bool("ro.audio.stereo_spatialization_enabled", false);
const bool channel_mask_spatialized =
- com_android_media_audio_stereo_spatialization()
+ (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
? audio_channel_mask_contains_stereo(channelMask)
: audio_is_channel_mask_spatialized(channelMask);
if (!channel_mask_spatialized) {
diff --git a/services/audiopolicy/tests/Android.bp b/services/audiopolicy/tests/Android.bp
index a4a0cd4..32c7db6 100644
--- a/services/audiopolicy/tests/Android.bp
+++ b/services/audiopolicy/tests/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
@@ -49,7 +50,7 @@
srcs: ["audiopolicymanager_tests.cpp"],
- data: [":audiopolicytest_configuration_files",],
+ data: [":audiopolicytest_configuration_files"],
cflags: [
"-Werror",
@@ -63,7 +64,6 @@
}
-
cc_test {
name: "audio_health_tests",
diff --git a/services/audiopolicy/tests/resources/Android.bp b/services/audiopolicy/tests/resources/Android.bp
index 5e71210..43e2e39 100644
--- a/services/audiopolicy/tests/resources/Android.bp
+++ b/services/audiopolicy/tests/resources/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_android_media_audio_framework",
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
// all of the 'license_kinds' from "frameworks_av_license"
diff --git a/services/camera/libcameraservice/Android.bp b/services/camera/libcameraservice/Android.bp
index 575e0fb..5b76bb0 100644
--- a/services/camera/libcameraservice/Android.bp
+++ b/services/camera/libcameraservice/Android.bp
@@ -112,6 +112,7 @@
"libcameraservice_device_independent",
"libdynamic_depth",
"libprocessinfoservice_aidl",
+ "libvirtualdevicebuildflags",
"media_permission-aidl-cpp",
],
}
diff --git a/services/camera/libcameraservice/common/CameraProviderManager.cpp b/services/camera/libcameraservice/common/CameraProviderManager.cpp
index be5ed4e..2e471be 100644
--- a/services/camera/libcameraservice/common/CameraProviderManager.cpp
+++ b/services/camera/libcameraservice/common/CameraProviderManager.cpp
@@ -33,6 +33,7 @@
#include <future>
#include <inttypes.h>
#include <android_companion_virtualdevice_flags.h>
+#include <android_companion_virtualdevice_build_flags.h>
#include <android/binder_manager.h>
#include <android/hidl/manager/1.2/IServiceManager.h>
#include <hidl/ServiceManagement.h>
@@ -3266,7 +3267,8 @@
}
bool CameraProviderManager::isVirtualCameraHalEnabled() {
- return vd_flags::virtual_camera_service_discovery();
+ return vd_flags::virtual_camera_service_discovery() &&
+ vd_flags::virtual_camera_service_build_flag();
}
} // namespace android
diff --git a/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp b/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp
index 5d5c54c..89e08a1 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp
+++ b/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp
@@ -499,7 +499,8 @@
states.inflightIntf.onInflightEntryRemovedLocked(duration);
}
-void removeInFlightRequestIfReadyLocked(CaptureOutputStates& states, int idx) {
+void removeInFlightRequestIfReadyLocked(CaptureOutputStates& states, int idx,
+ std::vector<BufferToReturn> *returnableBuffers) {
InFlightRequestMap& inflightMap = states.inflightMap;
const InFlightRequest &request = inflightMap.valueAt(idx);
const uint32_t frameNumber = inflightMap.keyAt(idx);
@@ -537,12 +538,13 @@
assert(request.requestStatus != OK ||
request.pendingOutputBuffers.size() == 0);
- returnOutputBuffers(
+ collectReturnableOutputBuffers(
states.useHalBufManager, states.halBufManagedStreamIds,
states.listener,
request.pendingOutputBuffers.array(),
request.pendingOutputBuffers.size(), /*timestamp*/0, /*readoutTimestamp*/0,
/*requested*/true, request.requestTimeNs, states.sessionStatsBuilder,
+ /*out*/ returnableBuffers,
/*timestampIncreasing*/true,
request.outputSurfaces, request.resultExtras,
request.errorBufStrategy, request.transform);
@@ -637,6 +639,7 @@
// in-flight request and they will be returned when the shutter timestamp
// arrives. Update the in-flight status and remove the in-flight entry if
// all result data and shutter timestamp have been received.
+ std::vector<BufferToReturn> returnableBuffers{};
nsecs_t shutterTimestamp = 0;
{
std::lock_guard<std::mutex> l(states.inflightLock);
@@ -798,10 +801,11 @@
request.pendingOutputBuffers.appendArray(result->output_buffers,
result->num_output_buffers);
if (shutterTimestamp != 0) {
- returnAndRemovePendingOutputBuffers(
+ collectAndRemovePendingOutputBuffers(
states.useHalBufManager, states.halBufManagedStreamIds,
states.listener,
- request, states.sessionStatsBuilder);
+ request, states.sessionStatsBuilder,
+ /*out*/ &returnableBuffers);
}
if (result->result != NULL && !isPartialResult) {
@@ -826,9 +830,18 @@
request.physicalMetadatas);
}
}
- removeInFlightRequestIfReadyLocked(states, idx);
+ removeInFlightRequestIfReadyLocked(states, idx, &returnableBuffers);
+ if (!flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
} // scope for states.inFlightLock
+ if (flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
+
if (result->input_buffer != NULL) {
if (hasInputBufferInRequest) {
Camera3Stream *stream =
@@ -849,17 +862,17 @@
}
}
-void returnOutputBuffers(
+void collectReturnableOutputBuffers(
bool useHalBufManager,
const std::set<int32_t> &halBufferManagedStreams,
sp<NotificationListener> listener,
const camera_stream_buffer_t *outputBuffers, size_t numBuffers,
nsecs_t timestamp, nsecs_t readoutTimestamp, bool requested,
nsecs_t requestTimeNs, SessionStatsBuilder& sessionStatsBuilder,
+ /*out*/ std::vector<BufferToReturn> *returnableBuffers,
bool timestampIncreasing, const SurfaceMap& outputSurfaces,
- const CaptureResultExtras &inResultExtras,
+ const CaptureResultExtras &resultExtras,
ERROR_BUF_STRATEGY errorBufStrategy, int32_t transform) {
-
for (size_t i = 0; i < numBuffers; i++)
{
Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
@@ -869,7 +882,7 @@
if (outputBuffers[i].status == CAMERA_BUFFER_STATUS_ERROR &&
errorBufStrategy == ERROR_BUF_RETURN_NOTIFY) {
if (listener != nullptr) {
- CaptureResultExtras extras = inResultExtras;
+ CaptureResultExtras extras = resultExtras;
extras.errorStreamId = streamId;
listener->notifyError(
hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
@@ -894,22 +907,35 @@
}
const auto& it = outputSurfaces.find(streamId);
- status_t res = OK;
// Do not return the buffer if the buffer status is error, and the error
// buffer strategy is CACHE.
if (outputBuffers[i].status != CAMERA_BUFFER_STATUS_ERROR ||
errorBufStrategy != ERROR_BUF_CACHE) {
if (it != outputSurfaces.end()) {
- res = stream->returnBuffer(
+ returnableBuffers->emplace_back(stream,
outputBuffers[i], timestamp, readoutTimestamp, timestampIncreasing,
- it->second, inResultExtras.frameNumber, transform);
+ it->second, resultExtras,
+ transform, requested ? requestTimeNs : 0);
} else {
- res = stream->returnBuffer(
+ returnableBuffers->emplace_back(stream,
outputBuffers[i], timestamp, readoutTimestamp, timestampIncreasing,
- std::vector<size_t> (), inResultExtras.frameNumber, transform);
+ std::vector<size_t> (), resultExtras,
+ transform, requested ? requestTimeNs : 0 );
}
}
+ }
+}
+
+void finishReturningOutputBuffers(const std::vector<BufferToReturn> &returnableBuffers,
+ sp<NotificationListener> listener, SessionStatsBuilder& sessionStatsBuilder) {
+ for (auto& b : returnableBuffers) {
+ const int streamId = b.stream->getId();
+
+ status_t res = b.stream->returnBuffer(b.buffer, b.timestamp,
+ b.readoutTimestamp, b.timestampIncreasing,
+ b.surfaceIds, b.resultExtras.frameNumber, b.transform);
+
// Note: stream may be deallocated at this point, if this buffer was
// the last reference to it.
bool dropped = false;
@@ -920,51 +946,55 @@
ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
dropped = true;
} else {
- if (outputBuffers[i].status == CAMERA_BUFFER_STATUS_ERROR || timestamp == 0) {
+ if (b.buffer.status == CAMERA_BUFFER_STATUS_ERROR || b.timestamp == 0) {
dropped = true;
}
}
- if (requested) {
+ if (b.requestTimeNs > 0) {
nsecs_t bufferTimeNs = systemTime();
- int32_t captureLatencyMs = ns2ms(bufferTimeNs - requestTimeNs);
+ int32_t captureLatencyMs = ns2ms(bufferTimeNs - b.requestTimeNs);
sessionStatsBuilder.incCounter(streamId, dropped, captureLatencyMs);
}
// Long processing consumers can cause returnBuffer timeout for shared stream
// If that happens, cancel the buffer and send a buffer error to client
- if (it != outputSurfaces.end() && res == TIMED_OUT &&
- outputBuffers[i].status == CAMERA_BUFFER_STATUS_OK) {
+ if (b.surfaceIds.size() > 0 && res == TIMED_OUT &&
+ b.buffer.status == CAMERA_BUFFER_STATUS_OK) {
// cancel the buffer
- camera_stream_buffer_t sb = outputBuffers[i];
+ camera_stream_buffer_t sb = b.buffer;
sb.status = CAMERA_BUFFER_STATUS_ERROR;
- stream->returnBuffer(sb, /*timestamp*/0, /*readoutTimestamp*/0,
- timestampIncreasing, std::vector<size_t> (),
- inResultExtras.frameNumber, transform);
+ b.stream->returnBuffer(sb, /*timestamp*/0, /*readoutTimestamp*/0,
+ b.timestampIncreasing, std::vector<size_t> (),
+ b.resultExtras.frameNumber, b.transform);
if (listener != nullptr) {
- CaptureResultExtras extras = inResultExtras;
+ CaptureResultExtras extras = b.resultExtras;
extras.errorStreamId = streamId;
listener->notifyError(
hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
extras);
}
}
+
}
}
-void returnAndRemovePendingOutputBuffers(bool useHalBufManager,
+void collectAndRemovePendingOutputBuffers(bool useHalBufManager,
const std::set<int32_t> &halBufferManagedStreams,
sp<NotificationListener> listener, InFlightRequest& request,
- SessionStatsBuilder& sessionStatsBuilder) {
+ SessionStatsBuilder& sessionStatsBuilder,
+ std::vector<BufferToReturn> *returnableBuffers) {
bool timestampIncreasing =
!((request.zslCapture && request.stillCapture) || request.hasInputBuffer);
nsecs_t readoutTimestamp = request.resultExtras.hasReadoutTimestamp ?
request.resultExtras.readoutTimestamp : 0;
- returnOutputBuffers(useHalBufManager, halBufferManagedStreams, listener,
+ collectReturnableOutputBuffers(useHalBufManager, halBufferManagedStreams, listener,
request.pendingOutputBuffers.array(),
request.pendingOutputBuffers.size(),
request.shutterTimestamp, readoutTimestamp,
- /*requested*/true, request.requestTimeNs, sessionStatsBuilder, timestampIncreasing,
+ /*requested*/true, request.requestTimeNs, sessionStatsBuilder,
+ /*out*/ returnableBuffers,
+ timestampIncreasing,
request.outputSurfaces, request.resultExtras,
request.errorBufStrategy, request.transform);
@@ -984,6 +1014,9 @@
ATRACE_CALL();
ssize_t idx;
+ std::vector<BufferToReturn> returnableBuffers{};
+ CaptureResultExtras pendingNotificationResultExtras{};
+
// Set timestamp for the request in the in-flight tracking
// and get the request ID to send upstream
{
@@ -1050,9 +1083,13 @@
states.lastCompletedReprocessFrameNumber;
r.resultExtras.lastCompletedZslFrameNumber =
states.lastCompletedZslFrameNumber;
- states.listener->notifyShutter(r.resultExtras, msg.timestamp);
+ if (flags::return_buffers_outside_locks()) {
+ pendingNotificationResultExtras = r.resultExtras;
+ } else {
+ states.listener->notifyShutter(r.resultExtras, msg.timestamp);
+ }
}
- // send pending result and buffers
+ // send pending result and buffers; this queues them up for delivery later
const auto& cameraIdsWithZoom = getCameraIdsWithZoomLocked(
inflightMap, r.pendingMetadata, r.cameraIdsWithZoom);
sendCaptureResult(states,
@@ -1061,17 +1098,35 @@
r.hasInputBuffer, r.zslCapture && r.stillCapture,
r.rotateAndCropAuto, cameraIdsWithZoom, r.physicalMetadatas);
}
- returnAndRemovePendingOutputBuffers(
+ collectAndRemovePendingOutputBuffers(
states.useHalBufManager, states.halBufManagedStreamIds,
- states.listener, r, states.sessionStatsBuilder);
+ states.listener, r, states.sessionStatsBuilder, &returnableBuffers);
- removeInFlightRequestIfReadyLocked(states, idx);
+ if (!flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
+
+ removeInFlightRequestIfReadyLocked(states, idx, &returnableBuffers);
+
}
}
if (idx < 0) {
SET_ERR("Shutter notification for non-existent frame number %d",
msg.frame_number);
}
+ // Call notifyShutter outside of in-flight mutex
+ if (flags::return_buffers_outside_locks() && pendingNotificationResultExtras.isValid()) {
+ states.listener->notifyShutter(pendingNotificationResultExtras, msg.timestamp);
+ }
+
+ // With no locks held, finish returning buffers to streams, which may take a while since
+ // binder calls are involved
+ if (flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
+
}
void notifyError(CaptureOutputStates& states, const camera_error_msg_t &msg) {
@@ -1117,6 +1172,8 @@
break;
case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
+ {
+ std::vector<BufferToReturn> returnableBuffers{};
{
std::lock_guard<std::mutex> l(states.inflightLock);
ssize_t idx = states.inflightMap.indexOfKey(msg.frame_number);
@@ -1153,7 +1210,12 @@
// Check whether the buffers returned. If they returned,
// remove inflight request.
- removeInFlightRequestIfReadyLocked(states, idx);
+ removeInFlightRequestIfReadyLocked(states, idx, &returnableBuffers);
+ if (!flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
+
}
} else {
resultExtras.frameNumber = msg.frame_number;
@@ -1162,6 +1224,12 @@
resultExtras.frameNumber);
}
}
+
+ if (flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
+
resultExtras.errorStreamId = streamId;
if (states.listener != nullptr) {
states.listener->notifyError(errorCode, resultExtras);
@@ -1170,6 +1238,7 @@
states.cameraId.c_str(), __FUNCTION__);
}
break;
+ }
case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
// Do not depend on HAL ERROR_CAMERA_BUFFER to send buffer error
// callback to the app. Rather, use STATUS_ERROR of image buffers.
@@ -1199,18 +1268,24 @@
void flushInflightRequests(FlushInflightReqStates& states) {
ATRACE_CALL();
+ std::vector<BufferToReturn> returnableBuffers{};
{ // First return buffers cached in inFlightMap
std::lock_guard<std::mutex> l(states.inflightLock);
for (size_t idx = 0; idx < states.inflightMap.size(); idx++) {
const InFlightRequest &request = states.inflightMap.valueAt(idx);
- returnOutputBuffers(
+ collectReturnableOutputBuffers(
states.useHalBufManager, states.halBufManagedStreamIds,
states.listener,
request.pendingOutputBuffers.array(),
request.pendingOutputBuffers.size(), /*timestamp*/0, /*readoutTimestamp*/0,
/*requested*/true, request.requestTimeNs, states.sessionStatsBuilder,
+ /*out*/ &returnableBuffers,
/*timestampIncreasing*/true, request.outputSurfaces, request.resultExtras,
request.errorBufStrategy);
+ if (!flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
ALOGW("%s: Frame %d | Timestamp: %" PRId64 ", metadata"
" arrived: %s, buffers left: %d.\n", __FUNCTION__,
states.inflightMap.keyAt(idx), request.shutterTimestamp,
@@ -1221,6 +1296,10 @@
states.inflightMap.clear();
states.inflightIntf.onInflightMapFlushedLocked();
}
+ if (flags::return_buffers_outside_locks()) {
+ finishReturningOutputBuffers(returnableBuffers,
+ states.listener, states.sessionStatsBuilder);
+ }
// Then return all inflight buffers not returned by HAL
std::vector<std::pair<int32_t, int32_t>> inflightKeys;
diff --git a/services/camera/libcameraservice/device3/Camera3OutputUtils.h b/services/camera/libcameraservice/device3/Camera3OutputUtils.h
index d155fa2..75864d7 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputUtils.h
+++ b/services/camera/libcameraservice/device3/Camera3OutputUtils.h
@@ -44,16 +44,50 @@
* Helper methods shared between Camera3Device/Camera3OfflineSession for HAL callbacks
*/
- // helper function to return the output buffers to output streams. The
- // function also optionally calls notify(ERROR_BUFFER).
- void returnOutputBuffers(
+ struct BufferToReturn {
+ Camera3StreamInterface *stream;
+ camera_stream_buffer_t buffer;
+ nsecs_t timestamp;
+ nsecs_t readoutTimestamp;
+ bool timestampIncreasing;
+ std::vector<size_t> surfaceIds;
+ const CaptureResultExtras resultExtras;
+ int32_t transform;
+ nsecs_t requestTimeNs;
+
+ BufferToReturn(Camera3StreamInterface *stream,
+ camera_stream_buffer_t buffer,
+ nsecs_t timestamp, nsecs_t readoutTimestamp,
+ bool timestampIncreasing, std::vector<size_t> surfaceIds,
+ const CaptureResultExtras &resultExtras,
+ int32_t transform, nsecs_t requestTimeNs):
+ stream(stream),
+ buffer(buffer),
+ timestamp(timestamp),
+ readoutTimestamp(readoutTimestamp),
+ timestampIncreasing(timestampIncreasing),
+ surfaceIds(surfaceIds),
+ resultExtras(resultExtras),
+ transform(transform),
+ requestTimeNs(requestTimeNs) {}
+ };
+
+ // helper function to return the output buffers to output
+ // streams. The function also optionally calls
+ // notify(ERROR_BUFFER). Returns the list of buffers to hand back
+ // to streams in returnableBuffers. Does not make any two-way
+ // binder calls, so suitable for use when critical locks are being
+ // held
+ void collectReturnableOutputBuffers(
bool useHalBufManager,
const std::set<int32_t> &halBufferManagedStreams,
sp<NotificationListener> listener, // Only needed when outputSurfaces is not empty
const camera_stream_buffer_t *outputBuffers,
size_t numBuffers, nsecs_t timestamp,
nsecs_t readoutTimestamp, bool requested, nsecs_t requestTimeNs,
- SessionStatsBuilder& sessionStatsBuilder, bool timestampIncreasing = true,
+ SessionStatsBuilder& sessionStatsBuilder,
+ /*out*/ std::vector<BufferToReturn> *returnableBuffers,
+ bool timestampIncreasing = true,
// The following arguments are only meant for surface sharing use case
const SurfaceMap& outputSurfaces = SurfaceMap{},
// Used to send buffer error callback when failing to return buffer
@@ -61,14 +95,24 @@
ERROR_BUF_STRATEGY errorBufStrategy = ERROR_BUF_RETURN,
int32_t transform = -1);
- // helper function to return the output buffers to output streams, and
- // remove the returned buffers from the inflight request's pending buffers
- // vector.
- void returnAndRemovePendingOutputBuffers(
+ // helper function to collect the output buffers ready to be
+ // returned to output streams, and to remove these buffers from
+ // the inflight request's pending buffers vector. Does not make
+ // any two-way binder calls, so suitable for use when critical
+ // locks are being held
+ void collectAndRemovePendingOutputBuffers(
bool useHalBufManager,
const std::set<int32_t> &halBufferManagedStreams,
sp<NotificationListener> listener, // Only needed when outputSurfaces is not empty
- InFlightRequest& request, SessionStatsBuilder& sessionStatsBuilder);
+ InFlightRequest& request, SessionStatsBuilder& sessionStatsBuilder,
+ /*out*/ std::vector<BufferToReturn> *returnableBuffers);
+
+ // Actually return filled output buffers to the consumer to use, using the list
+ // provided by collectReturnableOutputBuffers / collectAndRemovePendingOutputBuffers
+ // Makes two-way binder calls to applications, so do not hold any critical locks when
+ // calling.
+ void finishReturningOutputBuffers(const std::vector<BufferToReturn> &returnableBuffers,
+ sp<NotificationListener> listener, SessionStatsBuilder& sessionStatsBuilder);
// Camera3Device/Camera3OfflineSession internal states used in notify/processCaptureResult
// callbacks
diff --git a/services/camera/libcameraservice/device3/Camera3OutputUtilsTemplated.h b/services/camera/libcameraservice/device3/Camera3OutputUtilsTemplated.h
index 2c30b15..aca7a67 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputUtilsTemplated.h
+++ b/services/camera/libcameraservice/device3/Camera3OutputUtilsTemplated.h
@@ -345,10 +345,15 @@
continue;
}
streamBuffer.stream = stream->asHalStream();
- returnOutputBuffers(states.useHalBufManager, states.halBufManagedStreamIds,
+ std::vector<BufferToReturn> returnableBuffers{};
+ collectReturnableOutputBuffers(states.useHalBufManager, states.halBufManagedStreamIds,
/*listener*/nullptr, &streamBuffer, /*size*/1, /*timestamp*/ 0,
/*readoutTimestamp*/0, /*requested*/false, /*requestTimeNs*/0,
+ states.sessionStatsBuilder,
+ /*out*/&returnableBuffers);
+ finishReturningOutputBuffers(returnableBuffers, /*listener*/ nullptr,
states.sessionStatsBuilder);
+
}
}
diff --git a/services/camera/libcameraservice/device3/aidl/AidlCamera3OutputUtils.cpp b/services/camera/libcameraservice/device3/aidl/AidlCamera3OutputUtils.cpp
index 3fc070b..d9c8e57 100644
--- a/services/camera/libcameraservice/device3/aidl/AidlCamera3OutputUtils.cpp
+++ b/services/camera/libcameraservice/device3/aidl/AidlCamera3OutputUtils.cpp
@@ -319,10 +319,15 @@
sb.acquire_fence = -1;
sb.status = CAMERA_BUFFER_STATUS_ERROR;
}
- returnOutputBuffers(states.useHalBufManager,states.halBufManagedStreamIds, nullptr,
- streamBuffers.data(), numAllocatedBuffers, 0,
- 0, false,
- 0, states.sessionStatsBuilder);
+ std::vector<BufferToReturn> returnableBuffers{};
+ collectReturnableOutputBuffers(states.useHalBufManager, states.halBufManagedStreamIds,
+ /*listener*/ nullptr,
+ streamBuffers.data(), numAllocatedBuffers, /*timestamp*/ 0,
+ /*readoutTimestamp*/ 0, /*requested*/ false,
+ /*requestTimeNs*/ 0, states.sessionStatsBuilder,
+ /*out*/ &returnableBuffers);
+ finishReturningOutputBuffers(returnableBuffers, /*listener*/ nullptr,
+ states.sessionStatsBuilder);
for (auto buf : newBuffers) {
states.bufferRecordsIntf.removeOneBufferCache(streamId, buf);
}
diff --git a/services/camera/virtualcamera/Android.bp b/services/camera/virtualcamera/Android.bp
index cb4e10f..94007cd 100644
--- a/services/camera/virtualcamera/Android.bp
+++ b/services/camera/virtualcamera/Android.bp
@@ -54,7 +54,7 @@
"util/EglProgram.cc",
"util/EglSurfaceTexture.cc",
"util/EglUtil.cc",
- "util/Permissions.cc"
+ "util/Permissions.cc",
],
defaults: [
"libvirtualcamera_defaults",
diff --git a/services/camera/virtualcamera/VirtualCameraDevice.cc b/services/camera/virtualcamera/VirtualCameraDevice.cc
index 768dffb..5a824cc 100644
--- a/services/camera/virtualcamera/VirtualCameraDevice.cc
+++ b/services/camera/virtualcamera/VirtualCameraDevice.cc
@@ -72,26 +72,14 @@
constexpr MetadataBuilder::ControlRegion kDefaultEmptyControlRegion{};
-const std::array<int32_t, 3> kOutputFormats{
- ANDROID_SCALER_AVAILABLE_FORMATS_IMPLEMENTATION_DEFINED,
- ANDROID_SCALER_AVAILABLE_FORMATS_YCbCr_420_888,
- ANDROID_SCALER_AVAILABLE_FORMATS_BLOB};
+const std::array<PixelFormat, 3> kOutputFormats{
+ PixelFormat::IMPLEMENTATION_DEFINED, PixelFormat::YCBCR_420_888,
+ PixelFormat::BLOB};
-struct Resolution {
- Resolution(const int w, const int h) : width(w), height(h) {
- }
-
- bool operator<(const Resolution& other) const {
- return width * height < other.width * other.height;
- }
-
- bool operator==(const Resolution& other) const {
- return width == other.width && height == other.height;
- }
-
- const int width;
- const int height;
-};
+bool isSupportedOutputFormat(const PixelFormat pixelFormat) {
+ return std::find(kOutputFormats.begin(), kOutputFormats.end(), pixelFormat) !=
+ kOutputFormats.end();
+}
std::optional<Resolution> getMaxResolution(
const std::vector<SupportedStreamConfiguration>& configs) {
@@ -151,11 +139,18 @@
.setFlashAvailable(false)
.setLensFacing(
static_cast<camera_metadata_enum_android_lens_facing>(lensFacing))
+ .setFocalLength(43.0)
.setSensorOrientation(static_cast<int32_t>(sensorOrientation))
+ .setSensorReadoutTimestamp(
+ ANDROID_SENSOR_READOUT_TIMESTAMP_NOT_SUPPORTED)
+ .setSensorTimestampSource(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN)
+ .setSensorPhysicalSize(36.0, 24.0)
.setAvailableFaceDetectModes({ANDROID_STATISTICS_FACE_DETECT_MODE_OFF})
.setAvailableMaxDigitalZoom(1.0)
.setControlAvailableModes({ANDROID_CONTROL_MODE_AUTO})
.setControlAfAvailableModes({ANDROID_CONTROL_AF_MODE_OFF})
+ .setControlAvailableSceneModes({ANDROID_CONTROL_SCENE_MODE_DISABLED})
+ .setControlAvailableEffects({ANDROID_CONTROL_EFFECT_MODE_OFF})
.setControlAeAvailableFpsRange(10, 30)
.setControlMaxRegions(0, 0, 0)
.setControlAfRegions({kDefaultEmptyControlRegion})
@@ -163,13 +158,23 @@
.setControlAwbRegions({kDefaultEmptyControlRegion})
.setControlAeCompensationRange(0, 1)
.setControlAeCompensationStep(camera_metadata_rational_t{0, 1})
+ .setControlAwbLockAvailable(false)
+ .setControlAeLockAvailable(false)
+ .setControlAvailableAwbModes({ANDROID_CONTROL_AWB_MODE_AUTO})
.setControlZoomRatioRange(/*min=*/1.0, /*max=*/1.0)
+ // TODO(b/301023410) Add JPEG Exif + thumbnail support.
+ .setJpegAvailableThumbnailSizes({Resolution(0, 0)})
.setMaxJpegSize(kMaxJpegSize)
+ .setMaxNumberOutputStreams(
+ VirtualCameraDevice::kMaxNumberOfRawStreams,
+ VirtualCameraDevice::kMaxNumberOfProcessedStreams,
+ VirtualCameraDevice::kMaxNumberOfStallStreams)
+ .setSyncMaxLatency(ANDROID_SYNC_MAX_LATENCY_UNKNOWN)
+ .setAvailableRequestKeys({})
.setAvailableRequestKeys({ANDROID_CONTROL_AF_MODE})
.setAvailableResultKeys({ANDROID_CONTROL_AF_MODE})
.setAvailableCapabilities(
- {ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE})
- .setAvailableCharacteristicKeys();
+ {ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE});
// Active array size must correspond to largest supported input resolution.
std::optional<Resolution> maxResolution =
@@ -179,6 +184,7 @@
}
builder.setSensorActiveArraySize(0, 0, maxResolution->width,
maxResolution->height);
+ builder.setSensorPixelArraySize(maxResolution->width, maxResolution->height);
std::vector<MetadataBuilder::StreamConfiguration> outputConfigurations;
@@ -189,7 +195,7 @@
getResolutionToMaxFpsMap(supportedInputConfig);
// Add configurations for all unique input resolutions and output formats.
- for (int32_t format : kOutputFormats) {
+ for (const PixelFormat format : kOutputFormats) {
std::transform(
resolutionToMaxFpsMap.begin(), resolutionToMaxFpsMap.end(),
std::back_inserter(outputConfigurations), [format](const auto& entry) {
@@ -198,7 +204,7 @@
return MetadataBuilder::StreamConfiguration{
.width = resolution.width,
.height = resolution.height,
- .format = format,
+ .format = static_cast<int32_t>(format),
.minFrameDuration = std::chrono::nanoseconds(1s) / maxFps,
.minStallDuration = 0s};
});
@@ -207,7 +213,7 @@
ALOGV("Adding %zu output configurations", outputConfigurations.size());
builder.setAvailableOutputStreamConfigurations(outputConfigurations);
- auto metadata = builder.build();
+ auto metadata = builder.setAvailableCharacteristicKeys().build();
if (metadata == nullptr) {
ALOGE("Failed to build metadata!");
return CameraMetadata();
@@ -288,6 +294,8 @@
return false;
}
+ int numberOfProcessedStreams = 0;
+ int numberOfStallStreams = 0;
for (const Stream& stream : streamConfiguration.streams) {
ALOGV("%s: Configuration queried: %s", __func__, stream.toString().c_str());
@@ -296,15 +304,18 @@
return false;
}
- // TODO(b/301023410) remove hardcoded format checks, verify against configuration.
if (stream.rotation != StreamRotation::ROTATION_0 ||
- (stream.format != PixelFormat::IMPLEMENTATION_DEFINED &&
- stream.format != PixelFormat::YCBCR_420_888 &&
- stream.format != PixelFormat::BLOB)) {
+ !isSupportedOutputFormat(stream.format)) {
ALOGV("Unsupported output stream type");
return false;
}
+ if (stream.format == PixelFormat::BLOB) {
+ numberOfStallStreams++;
+ } else {
+ numberOfProcessedStreams++;
+ }
+
auto matchesSupportedInputConfig =
[&stream](const SupportedStreamConfiguration& config) {
return stream.width == config.width && stream.height == config.height;
@@ -316,6 +327,19 @@
return false;
}
}
+
+ if (numberOfProcessedStreams > kMaxNumberOfProcessedStreams) {
+ ALOGE("%s: %d processed streams exceeds the supported maximum of %d",
+ __func__, numberOfProcessedStreams, kMaxNumberOfProcessedStreams);
+ return false;
+ }
+
+ if (numberOfStallStreams > kMaxNumberOfStallStreams) {
+ ALOGE("%s: %d stall streams exceeds the supported maximum of %d", __func__,
+ numberOfStallStreams, kMaxNumberOfStallStreams);
+ return false;
+ }
+
return true;
}
diff --git a/services/camera/virtualcamera/VirtualCameraDevice.h b/services/camera/virtualcamera/VirtualCameraDevice.h
index 10d52af..3700625 100644
--- a/services/camera/virtualcamera/VirtualCameraDevice.h
+++ b/services/camera/virtualcamera/VirtualCameraDevice.h
@@ -94,6 +94,19 @@
uint32_t getCameraId() const { return mCameraId; }
+ // Maximal number of RAW streams - virtual camera doesn't support RAW streams.
+ static const int32_t kMaxNumberOfRawStreams = 0;
+
+ // Maximal number of non-jpeg streams configured concurrently in single
+ // session. This should be at least 3 and can be increased at the potential
+ // cost of more CPU/GPU load if there are many concurrent streams.
+ static const int32_t kMaxNumberOfProcessedStreams = 3;
+
+ // Maximal number of stalling (in case of virtual camera only jpeg for now)
+ // streams. Can be increaed at the cost of potential cost of more GPU/CPU
+ // load.
+ static const int32_t kMaxNumberOfStallStreams = 1;
+
private:
std::shared_ptr<VirtualCameraDevice> sharedFromThis();
diff --git a/services/camera/virtualcamera/aidl/Android.bp b/services/camera/virtualcamera/aidl/Android.bp
index a9c2195..a02d390 100644
--- a/services/camera/virtualcamera/aidl/Android.bp
+++ b/services/camera/virtualcamera/aidl/Android.bp
@@ -23,6 +23,9 @@
cpp: {
enabled: false,
},
+ rust: {
+ enabled: false,
+ },
ndk: {
enabled: true,
additional_shared_libraries: [
@@ -33,6 +36,6 @@
java: {
enabled: true,
platform_apis: true,
- }
+ },
},
}
diff --git a/services/camera/virtualcamera/flags/Android.bp b/services/camera/virtualcamera/flags/Android.bp
new file mode 100644
index 0000000..3ff67ea
--- /dev/null
+++ b/services/camera/virtualcamera/flags/Android.bp
@@ -0,0 +1,33 @@
+soong_config_module_type {
+ name: "virtual_device_build_flags_cc_defaults",
+ module_type: "cc_defaults",
+ config_namespace: "vdm",
+ bool_variables: [
+ "virtual_camera_service_enabled",
+ ],
+ properties: [
+ "cflags",
+ ],
+}
+
+soong_config_bool_variable {
+ name: "virtual_camera_service_enabled",
+}
+
+virtual_device_build_flags_cc_defaults {
+ name: "virtual_device_build_flags_defaults",
+ soong_config_variables: {
+ virtual_camera_service_enabled: {
+ cflags: ["-DVIRTUAL_CAMERA_SERVICE_ENABLED=1"],
+ },
+ },
+}
+
+cc_library_static {
+ name: "libvirtualdevicebuildflags",
+ srcs: [
+ "android_companion_virtualdevice_build_flags.cc",
+ ],
+ export_include_dirs: ["."],
+ defaults: ["virtual_device_build_flags_defaults"],
+}
diff --git a/services/camera/virtualcamera/flags/android_companion_virtualdevice_build_flags.cc b/services/camera/virtualcamera/flags/android_companion_virtualdevice_build_flags.cc
new file mode 100644
index 0000000..5525bc9
--- /dev/null
+++ b/services/camera/virtualcamera/flags/android_companion_virtualdevice_build_flags.cc
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace android {
+namespace companion {
+namespace virtualdevice {
+namespace flags {
+
+bool virtual_camera_service_build_flag() {
+#if VIRTUAL_CAMERA_SERVICE_ENABLED
+ return true;
+#else
+ return false;
+#endif
+}
+
+} // namespace flags
+} // namespace virtualdevice
+} // namespace companion
+} // namespace android
diff --git a/services/camera/virtualcamera/flags/android_companion_virtualdevice_build_flags.h b/services/camera/virtualcamera/flags/android_companion_virtualdevice_build_flags.h
new file mode 100644
index 0000000..718ce9b
--- /dev/null
+++ b/services/camera/virtualcamera/flags/android_companion_virtualdevice_build_flags.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace android {
+namespace companion {
+namespace virtualdevice {
+namespace flags {
+
+// Returns true if the virtual camera service is enabled
+// in the build.
+//
+// TODO(b/309090563) - Deprecate in favor of autogened library to query build
+// flags once available.
+bool virtual_camera_service_build_flag();
+
+} // namespace flags
+} // namespace virtualdevice
+} // namespace companion
+} // namespace android
diff --git a/services/camera/virtualcamera/fuzzer/Android.bp b/services/camera/virtualcamera/fuzzer/Android.bp
index 71e8f50..afa1e44 100644
--- a/services/camera/virtualcamera/fuzzer/Android.bp
+++ b/services/camera/virtualcamera/fuzzer/Android.bp
@@ -15,7 +15,7 @@
* limitations under the License.
*
*****************************************************************************/
- package {
+package {
// See: http://go/android-license-faq
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/services/camera/virtualcamera/tests/Android.bp b/services/camera/virtualcamera/tests/Android.bp
index bc46ba0..13104c1 100644
--- a/services/camera/virtualcamera/tests/Android.bp
+++ b/services/camera/virtualcamera/tests/Android.bp
@@ -14,11 +14,13 @@
"libgtest",
"libgmock",
],
- srcs: ["EglUtilTest.cc",
- "VirtualCameraDeviceTest.cc",
- "VirtualCameraProviderTest.cc",
- "VirtualCameraRenderThreadTest.cc",
- "VirtualCameraServiceTest.cc",
- "VirtualCameraSessionTest.cc"],
+ srcs: [
+ "EglUtilTest.cc",
+ "VirtualCameraDeviceTest.cc",
+ "VirtualCameraProviderTest.cc",
+ "VirtualCameraRenderThreadTest.cc",
+ "VirtualCameraServiceTest.cc",
+ "VirtualCameraSessionTest.cc",
+ ],
test_suites: ["device-tests"],
}
diff --git a/services/camera/virtualcamera/tests/VirtualCameraDeviceTest.cc b/services/camera/virtualcamera/tests/VirtualCameraDeviceTest.cc
index 027ecb7..35bf752 100644
--- a/services/camera/virtualcamera/tests/VirtualCameraDeviceTest.cc
+++ b/services/camera/virtualcamera/tests/VirtualCameraDeviceTest.cc
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#include <algorithm>
+#include <iterator>
#include <memory>
#include "VirtualCameraDevice.h"
@@ -22,6 +24,7 @@
#include "aidl/android/companion/virtualcamera/VirtualCameraConfiguration.h"
#include "aidl/android/hardware/camera/device/CameraMetadata.h"
#include "aidl/android/hardware/camera/device/StreamConfiguration.h"
+#include "aidl/android/hardware/graphics/common/PixelFormat.h"
#include "android/binder_interface_utils.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
@@ -55,6 +58,20 @@
constexpr int kHdHeight = 720;
constexpr int kMaxFps = 30;
+const Stream kVgaYUV420Stream = Stream{
+ .streamType = StreamType::OUTPUT,
+ .width = kVgaWidth,
+ .height = kVgaHeight,
+ .format = PixelFormat::YCBCR_420_888,
+};
+
+const Stream kVgaJpegStream = Stream{
+ .streamType = StreamType::OUTPUT,
+ .width = kVgaWidth,
+ .height = kVgaHeight,
+ .format = PixelFormat::BLOB,
+};
+
struct AvailableStreamConfiguration {
const int width;
const int height;
@@ -105,10 +122,11 @@
std::vector<AvailableStreamConfiguration> expectedAvailableStreamConfigs;
};
-class VirtualCameraDeviceTest
+class VirtualCameraDeviceCharacterisicsTest
: public testing::TestWithParam<VirtualCameraConfigTestParam> {};
-TEST_P(VirtualCameraDeviceTest, cameraCharacteristicsForInputFormat) {
+TEST_P(VirtualCameraDeviceCharacterisicsTest,
+ cameraCharacteristicsForInputFormat) {
const VirtualCameraConfigTestParam& param = GetParam();
std::shared_ptr<VirtualCameraDevice> camera =
ndk::SharedRefBase::make<VirtualCameraDevice>(kCameraId,
@@ -137,7 +155,7 @@
}
INSTANTIATE_TEST_SUITE_P(
- cameraCharacteristicsForInputFormat, VirtualCameraDeviceTest,
+ cameraCharacteristicsForInputFormat, VirtualCameraDeviceCharacterisicsTest,
testing::Values(
VirtualCameraConfigTestParam{
.inputConfig =
@@ -227,6 +245,67 @@
.streamConfiguration =
ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT}}}));
+class VirtualCameraDeviceTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ mCamera = ndk::SharedRefBase::make<VirtualCameraDevice>(
+ kCameraId, VirtualCameraConfiguration{
+ .supportedStreamConfigs = {SupportedStreamConfiguration{
+ .width = kVgaWidth,
+ .height = kVgaHeight,
+ .pixelFormat = Format::YUV_420_888,
+ .maxFps = kMaxFps}},
+ .virtualCameraCallback = nullptr,
+ .sensorOrientation = SensorOrientation::ORIENTATION_0,
+ .lensFacing = LensFacing::FRONT});
+ }
+
+ protected:
+ std::shared_ptr<VirtualCameraDevice> mCamera;
+};
+
+TEST_F(VirtualCameraDeviceTest, configureMaximalNumberOfNonStallStreamsSuceeds) {
+ StreamConfiguration config;
+ std::fill_n(std::back_insert_iterator(config.streams),
+ VirtualCameraDevice::kMaxNumberOfProcessedStreams,
+ kVgaYUV420Stream);
+
+ bool aidl_ret;
+ ASSERT_TRUE(mCamera->isStreamCombinationSupported(config, &aidl_ret).isOk());
+ EXPECT_TRUE(aidl_ret);
+}
+
+TEST_F(VirtualCameraDeviceTest, configureTooManyNonStallStreamsFails) {
+ StreamConfiguration config;
+ std::fill_n(std::back_insert_iterator(config.streams),
+ VirtualCameraDevice::kMaxNumberOfProcessedStreams + 1,
+ kVgaYUV420Stream);
+
+ bool aidl_ret;
+ ASSERT_TRUE(mCamera->isStreamCombinationSupported(config, &aidl_ret).isOk());
+ EXPECT_FALSE(aidl_ret);
+}
+
+TEST_F(VirtualCameraDeviceTest, configureMaximalNumberOfStallStreamsSuceeds) {
+ StreamConfiguration config;
+ std::fill_n(std::back_insert_iterator(config.streams),
+ VirtualCameraDevice::kMaxNumberOfStallStreams, kVgaJpegStream);
+
+ bool aidl_ret;
+ ASSERT_TRUE(mCamera->isStreamCombinationSupported(config, &aidl_ret).isOk());
+ EXPECT_TRUE(aidl_ret);
+}
+
+TEST_F(VirtualCameraDeviceTest, configureTooManyStallStreamsFails) {
+ StreamConfiguration config;
+ std::fill_n(std::back_insert_iterator(config.streams),
+ VirtualCameraDevice::kMaxNumberOfStallStreams + 1, kVgaJpegStream);
+
+ bool aidl_ret;
+ ASSERT_TRUE(mCamera->isStreamCombinationSupported(config, &aidl_ret).isOk());
+ EXPECT_FALSE(aidl_ret);
+}
+
} // namespace
} // namespace virtualcamera
} // namespace companion
diff --git a/services/camera/virtualcamera/util/MetadataBuilder.cc b/services/camera/virtualcamera/util/MetadataBuilder.cc
index 70e22be..b30f2b5 100644
--- a/services/camera/virtualcamera/util/MetadataBuilder.cc
+++ b/services/camera/virtualcamera/util/MetadataBuilder.cc
@@ -31,6 +31,7 @@
#include "aidl/android/hardware/camera/device/CameraMetadata.h"
#include "log/log.h"
#include "system/camera_metadata.h"
+#include "util/Util.h"
#include "utils/Errors.h"
namespace android {
@@ -74,12 +75,35 @@
return *this;
}
+MetadataBuilder& MetadataBuilder::setSensorReadoutTimestamp(
+ const camera_metadata_enum_android_sensor_readout_timestamp_t
+ sensorReadoutTimestamp) {
+ mEntryMap[ANDROID_SENSOR_READOUT_TIMESTAMP] =
+ std::vector<uint8_t>({static_cast<uint8_t>(sensorReadoutTimestamp)});
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setFocalLength(float focalLength) {
+ std::vector<float> focalLengths({focalLength});
+ mEntryMap[ANDROID_LENS_FOCAL_LENGTH] = focalLengths;
+ mEntryMap[ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS] = focalLengths;
+ return *this;
+}
+
MetadataBuilder& MetadataBuilder::setSensorOrientation(int32_t sensorOrientation) {
mEntryMap[ANDROID_SENSOR_ORIENTATION] =
std::vector<int32_t>({sensorOrientation});
return *this;
}
+MetadataBuilder& MetadataBuilder::setSensorTimestampSource(
+ const camera_metadata_enum_android_sensor_info_timestamp_source_t
+ timestampSource) {
+ mEntryMap[ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE] =
+ std::vector<uint8_t>({static_cast<uint8_t>(timestampSource)});
+ return *this;
+}
+
MetadataBuilder& MetadataBuilder::setSensorTimestamp(
std::chrono::nanoseconds timestamp) {
mEntryMap[ANDROID_SENSOR_TIMESTAMP] =
@@ -103,6 +127,22 @@
return *this;
}
+MetadataBuilder& MetadataBuilder::setControlAvailableSceneModes(
+ const std::vector<camera_metadata_enum_android_control_scene_mode>&
+ availableSceneModes) {
+ mEntryMap[ANDROID_CONTROL_AVAILABLE_SCENE_MODES] =
+ convertTo<uint8_t>(availableSceneModes);
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setControlAvailableEffects(
+ const std::vector<camera_metadata_enum_android_control_effect_mode>&
+ availableEffects) {
+ mEntryMap[ANDROID_CONTROL_AVAILABLE_EFFECTS] =
+ convertTo<uint8_t>(availableEffects);
+ return *this;
+}
+
MetadataBuilder& MetadataBuilder::setControlAfAvailableModes(
const std::vector<camera_metadata_enum_android_control_af_mode_t>&
availableModes) {
@@ -133,6 +173,32 @@
return *this;
}
+MetadataBuilder& MetadataBuilder::setControlAvailableAwbModes(
+ const std::vector<camera_metadata_enum_android_control_awb_mode>& awbModes) {
+ mEntryMap[ANDROID_CONTROL_AWB_AVAILABLE_MODES] = convertTo<uint8_t>(awbModes);
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setControlAwbLockAvailable(
+ const bool awbLockAvailable) {
+ const uint8_t lockAvailable = awbLockAvailable
+ ? ANDROID_CONTROL_AWB_LOCK_AVAILABLE_TRUE
+ : ANDROID_CONTROL_AWB_LOCK_AVAILABLE_FALSE;
+ mEntryMap[ANDROID_CONTROL_AWB_LOCK_AVAILABLE] =
+ std::vector<uint8_t>({lockAvailable});
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setControlAeLockAvailable(
+ const bool aeLockAvailable) {
+ const uint8_t lockAvailable = aeLockAvailable
+ ? ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE
+ : ANDROID_CONTROL_AE_LOCK_AVAILABLE_FALSE;
+ mEntryMap[ANDROID_CONTROL_AE_LOCK_AVAILABLE] =
+ std::vector<uint8_t>({lockAvailable});
+ return *this;
+}
+
MetadataBuilder& MetadataBuilder::setControlAeRegions(
const std::vector<ControlRegion>& aeRegions) {
std::vector<int32_t> regions;
@@ -190,6 +256,41 @@
return *this;
}
+MetadataBuilder& MetadataBuilder::setJpegAvailableThumbnailSizes(
+ const std::vector<Resolution>& thumbnailSizes) {
+ std::vector<int32_t> sizes;
+ sizes.reserve(thumbnailSizes.size() * 2);
+ for (const Resolution& resolution : thumbnailSizes) {
+ sizes.push_back(resolution.width);
+ sizes.push_back(resolution.height);
+ }
+ mEntryMap[ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES] = sizes;
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setMaxNumberOutputStreams(
+ const int32_t maxRawStreams, const int32_t maxProcessedStreams,
+ const int32_t maxStallStreams) {
+ mEntryMap[ANDROID_REQUEST_MAX_NUM_OUTPUT_STREAMS] = std::vector<int32_t>(
+ {maxRawStreams, maxProcessedStreams, maxStallStreams});
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setSyncMaxLatency(
+ camera_metadata_enum_android_sync_max_latency latency) {
+ mEntryMap[ANDROID_SYNC_MAX_LATENCY] =
+ std::vector<int32_t>({static_cast<int32_t>(latency)});
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setAvailableRequestCapabilities(
+ const std::vector<camera_metadata_enum_android_request_available_capabilities_t>&
+ requestCapabilities) {
+ mEntryMap[ANDROID_REQUEST_AVAILABLE_CAPABILITIES] =
+ convertTo<uint8_t>(requestCapabilities);
+ return *this;
+}
+
MetadataBuilder& MetadataBuilder::setAvailableOutputStreamConfigurations(
const std::vector<StreamConfiguration>& streamConfigurations) {
std::vector<int32_t> metadataStreamConfigs;
@@ -228,7 +329,7 @@
MetadataBuilder& MetadataBuilder::setAvailableMaxDigitalZoom(const float maxZoom) {
mEntryMap[ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM] =
- std::vector<float>(maxZoom);
+ std::vector<float>({maxZoom});
return *this;
}
@@ -245,6 +346,20 @@
return *this;
}
+MetadataBuilder& MetadataBuilder::setSensorPixelArraySize(int width,
+ int height) {
+ mEntryMap[ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE] =
+ std::vector<int32_t>({width, height});
+ return *this;
+}
+
+MetadataBuilder& MetadataBuilder::setSensorPhysicalSize(float width,
+ float height) {
+ mEntryMap[ANDROID_SENSOR_INFO_PHYSICAL_SIZE] =
+ std::vector<float>({width, height});
+ return *this;
+}
+
MetadataBuilder& MetadataBuilder::setControlAeCompensationRange(int32_t min,
int32_t max) {
mEntryMap[ANDROID_CONTROL_AE_COMPENSATION_RANGE] =
@@ -287,19 +402,23 @@
}
MetadataBuilder& MetadataBuilder::setAvailableCharacteristicKeys() {
- std::vector<camera_metadata_tag_t> availableKeys;
- availableKeys.reserve(mEntryMap.size());
- for (const auto& [key, _] : mEntryMap) {
- if (key != ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS) {
- availableKeys.push_back(key);
- }
- }
- setAvailableCharacteristicKeys(availableKeys);
+ mExtendWithAvailableCharacteristicsKeys = true;
return *this;
}
std::unique_ptr<aidl::android::hardware::camera::device::CameraMetadata>
-MetadataBuilder::build() const {
+MetadataBuilder::build() {
+ if (mExtendWithAvailableCharacteristicsKeys) {
+ std::vector<camera_metadata_tag_t> availableKeys;
+ availableKeys.reserve(mEntryMap.size());
+ for (const auto& [key, _] : mEntryMap) {
+ if (key != ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS) {
+ availableKeys.push_back(key);
+ }
+ }
+ setAvailableCharacteristicKeys(availableKeys);
+ }
+
CameraMetadata metadataHelper;
for (const auto& entry : mEntryMap) {
status_t ret = std::visit(
diff --git a/services/camera/virtualcamera/util/MetadataBuilder.h b/services/camera/virtualcamera/util/MetadataBuilder.h
index 46f4c43..71832d9 100644
--- a/services/camera/virtualcamera/util/MetadataBuilder.h
+++ b/services/camera/virtualcamera/util/MetadataBuilder.h
@@ -26,6 +26,7 @@
#include "aidl/android/hardware/camera/device/CameraMetadata.h"
#include "system/camera_metadata.h"
+#include "util/Util.h"
namespace android {
namespace companion {
@@ -73,6 +74,15 @@
MetadataBuilder& setLensFacing(
camera_metadata_enum_android_lens_facing lensFacing);
+ // See ANDROID_SENSOR_READOUT_TIMESTAMP in CameraMetadataTag.aidl.
+ MetadataBuilder& setSensorReadoutTimestamp(
+ camera_metadata_enum_android_sensor_readout_timestamp_t
+ sensorReadoutTimestamp);
+
+ // See ANDROID_LENS_FOCAL_LENGTH and ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS
+ // in CameraMetadataTag.aidl.
+ MetadataBuilder& setFocalLength(float focalLength);
+
// See ANDROID_SENSOR_ORIENTATION in CameraMetadataTag.aidl.
MetadataBuilder& setSensorOrientation(int32_t sensorOrientation);
@@ -82,9 +92,19 @@
// See ANDROID_SENSOR_TIMESTAMP in CameraMetadataTag.aidl.
MetadataBuilder& setSensorTimestamp(std::chrono::nanoseconds timestamp);
+ // See SENSOR_INFO_TIMESTAMP_SOURCE in CameraCharacteristic.java.
+ MetadataBuilder& setSensorTimestampSource(
+ camera_metadata_enum_android_sensor_info_timestamp_source_t timestampSource);
+
// See ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE in CameraMetadataTag.aidl.
MetadataBuilder& setSensorActiveArraySize(int x0, int y0, int x1, int y1);
+ // See ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE in CameraMetadataTag.aidl.
+ MetadataBuilder& setSensorPixelArraySize(int width, int height);
+
+ // See ANDROID_SENSOR_INFO_PHYSICAL_SIZE in CameraMetadataTag.aidl.
+ MetadataBuilder& setSensorPhysicalSize(float width, float height);
+
// See ANDROID_STATISTICS_FACE_DETECT_MODE in CameraMetadataTag.aidl.
MetadataBuilder& setAvailableFaceDetectModes(
const std::vector<camera_metadata_enum_android_statistics_face_detect_mode_t>&
@@ -104,6 +124,16 @@
const std::vector<camera_metadata_enum_android_control_mode_t>&
availableModes);
+ // See ANDROID_CONTROL_AVAILABLE_SCENE_MODES in CameraMetadataTag.aidl.
+ MetadataBuilder& setControlAvailableSceneModes(
+ const std::vector<camera_metadata_enum_android_control_scene_mode>&
+ availableSceneModes);
+
+ // See ANDROID_CONTROL_AVAILABLE_EFFECTS in CameraMetadataTag.aidl.
+ MetadataBuilder& setControlAvailableEffects(
+ const std::vector<camera_metadata_enum_android_control_effect_mode>&
+ availableEffects);
+
// See ANDROID_CONTROL_AE_COMPENSATION_RANGE in CameraMetadataTag.aidl.
MetadataBuilder& setControlAeCompensationRange(int32_t min, int32_t max);
@@ -131,6 +161,16 @@
int32_t maxAwbRegions,
int32_t maxAfRegions);
+ // See ANDROID_CONTROL_AWB_AVAILABLE_MODES in CameraMetadataTag.aidl.
+ MetadataBuilder& setControlAvailableAwbModes(
+ const std::vector<camera_metadata_enum_android_control_awb_mode>& awbModes);
+
+ // See CONTROL_AWB_LOCK_AVAILABLE in CameraMetadataTag.aidl.
+ MetadataBuilder& setControlAwbLockAvailable(bool awbLockAvailable);
+
+ // See CONTROL_AE_LOCK_AVAILABLE in CameraMetadataTag.aidl.
+ MetadataBuilder& setControlAeLockAvailable(bool aeLockAvailable);
+
// See ANDROID_CONTROL_AE_REGIONS in CameraMetadataTag.aidl.
MetadataBuilder& setControlAeRegions(
const std::vector<ControlRegion>& aeRegions);
@@ -148,12 +188,34 @@
// See ANDROID_JPEG_SIZE in CameraMetadataTag.aidl.
MetadataBuilder& setMaxJpegSize(int32_t size);
+ // See JPEG_AVAILABLE_THUMBNAIL_SIZES in CameraCharacteristic.java.
+ MetadataBuilder& setJpegAvailableThumbnailSizes(
+ const std::vector<Resolution>& thumbnailSizes);
+
+ // The maximum numbers of different types of output streams
+ // that can be configured and used simultaneously by a camera device.
+ //
+ // See ANDROID_REQUEST_MAX_NUM_OUTPUT_STREAMS in CameraMetadataTag.aidl.
+ MetadataBuilder& setMaxNumberOutputStreams(int32_t maxRawStreams,
+ int32_t maxProcessedStreams,
+ int32_t maxStallStreams);
+
+ // See ANDROID_SYNC_MAX_LATENCY in CameraMetadataTag.aidl.
+ MetadataBuilder& setSyncMaxLatency(
+ camera_metadata_enum_android_sync_max_latency setSyncMaxLatency);
+
// See ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM in CameraMetadataTag.aidl.
MetadataBuilder& setAvailableMaxDigitalZoom(const float maxZoom);
// See ANDROID_CONTROL_ZOOM_RATIO_RANGE in CameraMetadataTag.aidl.
MetadataBuilder& setControlZoomRatioRange(float min, float max);
+ // See ANDROID_REQUEST_AVAILABLE_CAPABILITIES in CameraMetadataTag.aidl.
+ MetadataBuilder& setAvailableRequestCapabilities(
+ const std::vector<
+ camera_metadata_enum_android_request_available_capabilities_t>&
+ requestCapabilities);
+
// A list of all keys that the camera device has available to use with
// CaptureRequest.
//
@@ -179,14 +241,14 @@
const std::vector<camera_metadata_tag_t>& keys);
// Extends metadata with ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS
- // containing all previously set tags.
+ // containing all set tags.
MetadataBuilder& setAvailableCharacteristicKeys();
// Build CameraMetadata instance.
//
// Returns nullptr in case something went wrong.
std::unique_ptr<::aidl::android::hardware::camera::device::CameraMetadata>
- build() const;
+ build();
private:
// Maps metadata tags to vectors of values for the given tag.
@@ -195,6 +257,8 @@
std::vector<uint8_t>, std::vector<float>,
std::vector<camera_metadata_rational_t>>>
mEntryMap;
+ // Extend metadata with ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS.
+ bool mExtendWithAvailableCharacteristicsKeys = false;
};
} // namespace virtualcamera
diff --git a/services/camera/virtualcamera/util/Util.h b/services/camera/virtualcamera/util/Util.h
index e0a31c0..9f81bb1 100644
--- a/services/camera/virtualcamera/util/Util.h
+++ b/services/camera/virtualcamera/util/Util.h
@@ -52,6 +52,27 @@
int width, int height,
::aidl::android::companion::virtualcamera::Format format, int maxFps);
+// Representation of resolution / size.
+struct Resolution {
+ Resolution(const int w, const int h) : width(w), height(h) {
+ }
+
+ // Order by increasing pixel count, and by width for same pixel count.
+ bool operator<(const Resolution& other) const {
+ const int pixCount = width * height;
+ const int otherPixCount = other.width * other.height;
+ return pixCount == otherPixCount ? width < other.width
+ : pixCount < otherPixCount;
+ }
+
+ bool operator==(const Resolution& other) const {
+ return width == other.width && height == other.height;
+ }
+
+ const int width;
+ const int height;
+};
+
} // namespace virtualcamera
} // namespace companion
} // namespace android
diff --git a/services/mediaresourcemanager/DefaultResourceModel.cpp b/services/mediaresourcemanager/DefaultResourceModel.cpp
index 7bad715..990df82 100644
--- a/services/mediaresourcemanager/DefaultResourceModel.cpp
+++ b/services/mediaresourcemanager/DefaultResourceModel.cpp
@@ -44,7 +44,9 @@
clients.clear();
MediaResourceParcel mediaResource{.type = reclimRequestInfo.mResources[0].type,
.subType = reclimRequestInfo.mResources[0].subType};
- ResourceRequestInfo resourceRequestInfo{reclimRequestInfo.mCallingPid, &mediaResource};
+ ResourceRequestInfo resourceRequestInfo{reclimRequestInfo.mCallingPid,
+ reclimRequestInfo.mClientId,
+ &mediaResource};
// Resolve the secure-unsecure codec conflicts if there is any.
switch (reclimRequestInfo.mResources[0].type) {
@@ -116,7 +118,9 @@
const ReclaimRequestInfo& reclimRequestInfo,
std::vector<ClientInfo>& clients) {
MediaResourceParcel mediaResource;
- ResourceRequestInfo resourceRequestInfo{reclimRequestInfo.mCallingPid, &mediaResource};
+ ResourceRequestInfo resourceRequestInfo{reclimRequestInfo.mCallingPid,
+ reclimRequestInfo.mClientId,
+ &mediaResource};
// 1. Look to find the client(s) with the other resources, for the given
// primary type.
diff --git a/services/mediaresourcemanager/ResourceManagerService.cpp b/services/mediaresourcemanager/ResourceManagerService.cpp
index 3a02443..305f6fe 100644
--- a/services/mediaresourcemanager/ResourceManagerService.cpp
+++ b/services/mediaresourcemanager/ResourceManagerService.cpp
@@ -474,6 +474,7 @@
const std::vector<MediaResourceParcel>& resources,
std::vector<ClientInfo>& targetClients) {
int32_t callingPid = clientInfo.pid;
+ int64_t clientId = clientInfo.id;
std::scoped_lock lock{mLock};
if (!mProcessInfo->isPidTrusted(callingPid)) {
pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
@@ -508,7 +509,7 @@
if (secureCodec != NULL) {
MediaResourceParcel mediaResource{.type = MediaResource::Type::kSecureCodec,
.subType = secureCodec->subType};
- ResourceRequestInfo resourceRequestInfo{callingPid, &mediaResource};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &mediaResource};
if (!mSupportsMultipleSecureCodecs) {
if (!getAllClients_l(resourceRequestInfo, targetClients)) {
return false;
@@ -525,7 +526,7 @@
if (!mSupportsSecureWithNonSecureCodec) {
MediaResourceParcel mediaResource{.type = MediaResource::Type::kSecureCodec,
.subType = nonSecureCodec->subType};
- ResourceRequestInfo resourceRequestInfo{callingPid, &mediaResource};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &mediaResource};
if (!getAllClients_l(resourceRequestInfo, targetClients)) {
return false;
}
@@ -533,7 +534,7 @@
}
if (drmSession != NULL) {
- ResourceRequestInfo resourceRequestInfo{callingPid, drmSession};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, drmSession};
getClientForResource_l(resourceRequestInfo, targetClients);
if (targetClients.size() == 0) {
return false;
@@ -542,18 +543,18 @@
if (targetClients.size() == 0 && graphicMemory != nullptr) {
// if no secure/non-secure codec conflict, run second pass to handle other resources.
- ResourceRequestInfo resourceRequestInfo{callingPid, graphicMemory};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, graphicMemory};
getClientForResource_l(resourceRequestInfo, targetClients);
}
if (targetClients.size() == 0) {
// if we are here, run the third pass to free one codec with the same type.
if (secureCodec != nullptr) {
- ResourceRequestInfo resourceRequestInfo{callingPid, secureCodec};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, secureCodec};
getClientForResource_l(resourceRequestInfo, targetClients);
}
if (nonSecureCodec != nullptr) {
- ResourceRequestInfo resourceRequestInfo{callingPid, nonSecureCodec};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, nonSecureCodec};
getClientForResource_l(resourceRequestInfo, targetClients);
}
}
@@ -562,12 +563,12 @@
// if we are here, run the fourth pass to free one codec with the different type.
if (secureCodec != nullptr) {
MediaResource temp(MediaResource::Type::kNonSecureCodec, secureCodec->subType, 1);
- ResourceRequestInfo resourceRequestInfo{callingPid, &temp};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &temp};
getClientForResource_l(resourceRequestInfo, targetClients);
}
if (nonSecureCodec != nullptr) {
MediaResource temp(MediaResource::Type::kSecureCodec, nonSecureCodec->subType, 1);
- ResourceRequestInfo resourceRequestInfo{callingPid, &temp};
+ ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &temp};
getClientForResource_l(resourceRequestInfo, targetClients);
}
}
@@ -914,6 +915,11 @@
for (auto& [pid, infos] : mMap) {
for (const auto& [id, info] : infos) {
+ if (pid == resourceRequestInfo.mCallingPid && id == resourceRequestInfo.mClientId) {
+ ALOGI("%s: Skip the client[%jd] for which the resource request is made",
+ __func__, id);
+ continue;
+ }
if (hasResourceType(type, subType, info.resources)) {
if (!isCallingPriorityHigher_l(resourceRequestInfo.mCallingPid, pid)) {
// some higher/equal priority process owns the resource,
diff --git a/services/mediaresourcemanager/ResourceManagerServiceNew.cpp b/services/mediaresourcemanager/ResourceManagerServiceNew.cpp
index af093ca..0a0a8f4 100644
--- a/services/mediaresourcemanager/ResourceManagerServiceNew.cpp
+++ b/services/mediaresourcemanager/ResourceManagerServiceNew.cpp
@@ -248,7 +248,7 @@
// Use the Resource Model to get a list of all the clients that hold the
// needed/requested resources.
uint32_t callingImportance = std::max(0, clientInfo.importance);
- ReclaimRequestInfo reclaimRequestInfo{callingPid, callingImportance, resources};
+ ReclaimRequestInfo reclaimRequestInfo{callingPid, clientInfo.id, callingImportance, resources};
std::vector<ClientInfo> clients;
if (!mDefaultResourceModel->getAllClients(reclaimRequestInfo, clients)) {
if (clients.empty()) {
@@ -300,7 +300,10 @@
// Use the DefaultResourceModel to get all the clients with the resources requested.
std::vector<MediaResourceParcel> resources{*resourceRequestInfo.mResource};
- ReclaimRequestInfo reclaimRequestInfo{resourceRequestInfo.mCallingPid, 0, resources};
+ ReclaimRequestInfo reclaimRequestInfo{resourceRequestInfo.mCallingPid,
+ resourceRequestInfo.mClientId,
+ 0, // default importance
+ resources};
std::vector<ClientInfo> clients;
mDefaultResourceModel->getAllClients(reclaimRequestInfo, clients);
diff --git a/services/mediaresourcemanager/ResourceManagerServiceUtils.h b/services/mediaresourcemanager/ResourceManagerServiceUtils.h
index 32cb219..e8f1515 100644
--- a/services/mediaresourcemanager/ResourceManagerServiceUtils.h
+++ b/services/mediaresourcemanager/ResourceManagerServiceUtils.h
@@ -166,11 +166,13 @@
/*
* Resource Reclaim request info that encapsulates
* - the calling/requesting process pid.
+ * - id of the client that made reclaim request.
* - the calling/requesting client's importance.
* - the list of resources requesting (to be reclaimed from others)
*/
struct ReclaimRequestInfo {
int mCallingPid = -1;
+ int64_t mClientId = 0;
uint32_t mCallingClientImportance = 0;
const std::vector<::aidl::android::media::MediaResourceParcel>& mResources;
};
@@ -178,11 +180,14 @@
/*
* Resource request info that encapsulates
* - the calling/requesting process pid.
+ * - the calling/requesting client's id.
* - the resource requesting (to be reclaimed from others)
*/
struct ResourceRequestInfo {
// pid of the calling/requesting process.
int mCallingPid = -1;
+ // id of the calling/requesting client.
+ int64_t mClientId = 0;
// resources requested.
const ::aidl::android::media::MediaResourceParcel* mResource;
};
diff --git a/services/mediaresourcemanager/ResourceTracker.cpp b/services/mediaresourcemanager/ResourceTracker.cpp
index 22381c3..3ee20cd 100644
--- a/services/mediaresourcemanager/ResourceTracker.cpp
+++ b/services/mediaresourcemanager/ResourceTracker.cpp
@@ -715,6 +715,11 @@
MediaResource::SubType subType = resourceRequestInfo.mResource->subType;
for (auto& [pid, /* ResourceInfos */ infos] : mMap) {
for (const auto& [id, /* ResourceInfo */ info] : infos) {
+ if (pid == resourceRequestInfo.mCallingPid && id == resourceRequestInfo.mClientId) {
+ ALOGI("%s: Skip the client[%jd] for which the resource request is made",
+ __func__, id);
+ continue;
+ }
if (hasResourceType(type, subType, info.resources)) {
if (!isCallingPriorityHigher(resourceRequestInfo.mCallingPid, pid)) {
// some higher/equal priority process owns the resource,
diff --git a/services/mediaresourcemanager/test/ResourceManagerServiceTestUtils.h b/services/mediaresourcemanager/test/ResourceManagerServiceTestUtils.h
index 7e8a4a0..2c8659d 100644
--- a/services/mediaresourcemanager/test/ResourceManagerServiceTestUtils.h
+++ b/services/mediaresourcemanager/test/ResourceManagerServiceTestUtils.h
@@ -165,6 +165,7 @@
DISALLOW_EVIL_CONSTRUCTORS(TestClient);
};
+// [pid, uid] used by the test.
static const int kTestPid1 = 30;
static const int kTestUid1 = 1010;
@@ -175,6 +176,12 @@
static const int kMidPriorityPid = 25;
static const int kHighPriorityPid = 10;
+// Client Ids used by the test.
+static const int kLowPriorityClientId = 1111;
+static const int kMidPriorityClientId = 2222;
+static const int kHighPriorityClientId = 3333;
+
+// Client importance used by the test.
static const int32_t kHighestCodecImportance = 0;
static const int32_t kLowestCodecImportance = 100;
static const int32_t kMidCodecImportance = 50;
diff --git a/services/mediaresourcemanager/test/ResourceManagerService_test.cpp b/services/mediaresourcemanager/test/ResourceManagerService_test.cpp
index b3a0932..027987e 100644
--- a/services/mediaresourcemanager/test/ResourceManagerService_test.cpp
+++ b/services/mediaresourcemanager/test/ResourceManagerService_test.cpp
@@ -337,7 +337,7 @@
// priority too low to reclaim resource
ClientInfoParcel clientInfo{.pid = static_cast<int32_t>(kLowPriorityPid),
.uid = static_cast<int32_t>(kTestUid1),
- .id = 0,
+ .id = kLowPriorityClientId,
.name = "none"};
CHECK_STATUS_FALSE(mService->reclaimResource(clientInfo, resources, &result));
@@ -475,9 +475,9 @@
MediaResource resource(MediaResource::Type::kSecureCodec,
MediaResource::SubType::kUnspecifiedSubType,
1);
- ResourceRequestInfo requestInfoHigh { kHighPriorityPid, &resource};
- ResourceRequestInfo requestInfoMid { kMidPriorityPid, &resource};
- ResourceRequestInfo requestInfoLow { kLowPriorityPid, &resource};
+ ResourceRequestInfo requestInfoHigh { kHighPriorityPid, kHighPriorityClientId, &resource};
+ ResourceRequestInfo requestInfoMid { kMidPriorityPid, kMidPriorityClientId, &resource};
+ ResourceRequestInfo requestInfoLow { kLowPriorityPid, kLowPriorityClientId, &resource};
EXPECT_FALSE(mService->getAllClients_l(requestInfoLow, targetClients));
// some higher priority process (e.g. kTestPid2) owns the resource, so getAllClients_l
@@ -491,6 +491,81 @@
EXPECT_EQ(getId(mTestClient1), targetClients[1].mClientId);
}
+ // test set up
+ // ---------------------------------------------------------------------------
+ // pid/priority client/clientId type number
+ // ---------------------------------------------------------------------------
+ // kTestPid1(30) mTestClient1 secure codec 1
+ // graphic memory 200
+ // graphic memory 200
+ // ---------------------------------------------------------------------------
+ // kTestPid2(20) mTestClient2 non-secure codec 1
+ // graphic memory 300
+ // ---------------------------------------------------
+ // mTestClient3 secure codec 1
+ // graphic memory 100
+ // ---------------------------------------------------------------------------
+ // kHighPriorityPid(10) kHighPriorityClient secure codec 1
+ // ---------------------------------------------------------------------------
+ // The kHighPriorityClient tries to reclaim request (after adding self)
+ // This should pass (and shouldn't be considered as a new client trying to
+ // reclaim from an existing client from same/higher priority process).
+ void testSelfReclaimResourceSecure() {
+ std::vector<MediaResourceParcel> resources;
+ resources.push_back(MediaResource(MediaResource::Type::kSecureCodec, 1));
+ resources.push_back(MediaResource(MediaResource::Type::kGraphicMemory, 150));
+
+ ClientInfoParcel lowPriorityClient{.pid = static_cast<int32_t>(kLowPriorityPid),
+ .uid = static_cast<int32_t>(kTestUid2),
+ .id = kLowPriorityClientId,
+ .name = "none"};
+ ClientInfoParcel midPriorityClient{.pid = static_cast<int32_t>(kMidPriorityPid),
+ .uid = static_cast<int32_t>(kTestUid2),
+ .id = kMidPriorityClientId,
+ .name = "none"};
+ // HighPriority process with client id kHighPriorityClientId.
+ ClientInfoParcel highPriorityClient1{.pid = static_cast<int32_t>(kHighPriorityPid),
+ .uid = static_cast<int32_t>(kTestUid2),
+ .id = kHighPriorityClientId,
+ .name = "none"};
+ // HighPriority process with client id 0xABCD.
+ ClientInfoParcel highPriorityClient2{.pid = static_cast<int32_t>(kHighPriorityPid),
+ .uid = static_cast<int32_t>(kTestUid2),
+ .id = 0xABCD,
+ .name = "none"};
+
+ addResource();
+
+ // Add a secure codec resource for the highPriorityClient1.
+ std::shared_ptr<IResourceManagerClient> testClient4 =
+ createTestClient(kHighPriorityPid, kTestUid2);
+ std::vector<MediaResourceParcel> resources1;
+ resources1.push_back(MediaResource(MediaResource::Type::kSecureCodec, 1));
+ mService->addResource(highPriorityClient1, testClient4, resources1);
+
+ // secure codecs can't coexist and secure codec can't coexist with non-secure codec.
+ updateConfig(false, false);
+
+ // priority too low
+ CHECK_STATUS_FALSE(mService->reclaimResource(lowPriorityClient, resources, &result));
+ CHECK_STATUS_FALSE(mService->reclaimResource(midPriorityClient, resources, &result));
+
+ // highPriorityClient2 tries to reclaim SecureCodec with Graphic memory.
+ // This should fail as this process already has an instance of secure
+ // codec through testClient4.
+ CHECK_STATUS_FALSE(mService->reclaimResource(highPriorityClient2, resources, &result));
+
+ // highPriorityClient1 tries to reclaim SecureCodec with Graphic memory.
+ // This should reclaim all secure and non-secure codecs.
+ CHECK_STATUS_TRUE(mService->reclaimResource(highPriorityClient1, resources, &result));
+ EXPECT_TRUE(toTestClient(mTestClient1)->checkIfReclaimedAndReset());
+ EXPECT_TRUE(toTestClient(mTestClient2)->checkIfReclaimedAndReset());
+ EXPECT_TRUE(toTestClient(mTestClient3)->checkIfReclaimedAndReset());
+
+ // Make sure there is nothing left.
+ CHECK_STATUS_FALSE(mService->reclaimResource(highPriorityClient1, resources, &result));
+ }
+
void testReclaimResourceSecure() {
std::vector<MediaResourceParcel> resources;
resources.push_back(MediaResource(MediaResource::Type::kSecureCodec, 1));
@@ -498,15 +573,15 @@
ClientInfoParcel lowPriorityClient{.pid = static_cast<int32_t>(kLowPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kLowPriorityClientId,
.name = "none"};
ClientInfoParcel midPriorityClient{.pid = static_cast<int32_t>(kMidPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kMidPriorityClientId,
.name = "none"};
ClientInfoParcel highPriorityClient{.pid = static_cast<int32_t>(kHighPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kHighPriorityClientId,
.name = "none"};
// ### secure codec can't coexist and secure codec can coexist with non-secure codec ###
@@ -553,7 +628,6 @@
CHECK_STATUS_FALSE(mService->reclaimResource(highPriorityClient, resources, &result));
}
-
// ### secure codecs can coexist but secure codec can't coexist with non-secure codec ###
{
addResource();
@@ -650,15 +724,15 @@
ClientInfoParcel lowPriorityClient{.pid = static_cast<int32_t>(kLowPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kLowPriorityClientId,
.name = "none"};
ClientInfoParcel midPriorityClient{.pid = static_cast<int32_t>(kMidPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kMidPriorityClientId,
.name = "none"};
ClientInfoParcel highPriorityClient{.pid = static_cast<int32_t>(kHighPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kHighPriorityClientId,
.name = "none"};
// ### secure codec can't coexist with non-secure codec ###
@@ -751,8 +825,8 @@
MediaResource resource(MediaResource::Type::kGraphicMemory,
MediaResource::SubType::kUnspecifiedSubType,
1);
- ResourceRequestInfo requestInfoHigh { kHighPriorityPid, &resource};
- ResourceRequestInfo requestInfoLow { kLowPriorityPid, &resource};
+ ResourceRequestInfo requestInfoHigh { kHighPriorityPid, kHighPriorityClientId, &resource};
+ ResourceRequestInfo requestInfoLow { kLowPriorityPid, kLowPriorityClientId, &resource};
EXPECT_FALSE(mService->getLowestPriorityBiggestClient_l(requestInfoHigh, clientInfo));
addResource();
@@ -910,7 +984,7 @@
reclaimResources.push_back(createNonSecureVideoCodecResource());
ClientInfoParcel highPriorityClient{.pid = static_cast<int32_t>(kHighPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kHighPriorityClientId,
.name = "none"};
CHECK_STATUS_FALSE(mService->reclaimResource(highPriorityClient, reclaimResources, &result));
@@ -951,7 +1025,7 @@
reclaimResources.push_back(createNonSecureAudioCodecResource());
ClientInfoParcel highPriorityClient{.pid = static_cast<int32_t>(kHighPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kHighPriorityClientId,
.name = "none"};
CHECK_STATUS_FALSE(mService->reclaimResource(highPriorityClient, reclaimResources, &result));
@@ -992,7 +1066,7 @@
reclaimResources.push_back(createNonSecureImageCodecResource());
ClientInfoParcel highPriorityClient{.pid = static_cast<int32_t>(kHighPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kHighPriorityClientId,
.name = "none"};
CHECK_STATUS_FALSE(mService->reclaimResource(highPriorityClient, reclaimResources, &result));
@@ -1034,7 +1108,7 @@
reclaimResources.push_back(createGraphicMemoryResource(100));
ClientInfoParcel highPriorityClient{.pid = static_cast<int32_t>(kHighPriorityPid),
.uid = static_cast<int32_t>(kTestUid2),
- .id = 0,
+ .id = kHighPriorityClientId,
.name = "none"};
CHECK_STATUS_TRUE(mService->reclaimResource(highPriorityClient, reclaimResources, &result));
@@ -1786,6 +1860,10 @@
testRemoveClient();
}
+TEST_F(ResourceManagerServiceTest, selfReclaimResource) {
+ testSelfReclaimResourceSecure();
+}
+
TEST_F(ResourceManagerServiceTest, reclaimResource) {
testReclaimResourceSecure();
testReclaimResourceNonSecure();
@@ -1873,6 +1951,10 @@
testRemoveClient();
}
+TEST_F(ResourceManagerServiceNewTest, selfReclaimResource) {
+ testSelfReclaimResourceSecure();
+}
+
TEST_F(ResourceManagerServiceNewTest, reclaimResource) {
testReclaimResourceSecure();
testReclaimResourceNonSecure();