1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "APM::AudioPolicyEngine/PFWWrapper"
18 //#define LOG_NDEBUG 0
19 
20 #include "ParameterManagerWrapper.h"
21 #include <ParameterMgrFullConnector.h>
22 #include <ParameterMgrPlatformConnector.h>
23 #include <SelectionCriterionTypeInterface.h>
24 #include <SelectionCriterionInterface.h>
25 #include <media/convert.h>
26 #include <algorithm>
27 #include <cutils/bitops.h>
28 #include <cutils/misc.h>
29 #include <fstream>
30 #include <limits>
31 #include <sstream>
32 #include <string>
33 #include <vector>
34 #include <stdint.h>
35 #include <cinttypes>
36 #include <cmath>
37 #include <utils/Log.h>
38 
39 using std::string;
40 using std::map;
41 using std::vector;
42 
43 /// PFW related definitions
44 // Logger
45 class ParameterMgrPlatformConnectorLogger : public CParameterMgrPlatformConnector::ILogger
46 {
47 public:
ParameterMgrPlatformConnectorLogger()48     ParameterMgrPlatformConnectorLogger() {}
49 
info(const string & log)50     virtual void info(const string &log)
51     {
52         ALOGV("policy-parameter-manager: %s", log.c_str());
53     }
warning(const string & log)54     virtual void warning(const string &log)
55     {
56         ALOGW("policy-parameter-manager: %s", log.c_str());
57     }
58 };
59 
60 namespace android {
61 
62 using utilities::convertTo;
63 
64 namespace audio_policy {
65 
66 const char *const ParameterManagerWrapper::mPolicyPfwDefaultConfFileName =
67     "/etc/parameter-framework/ParameterFrameworkConfigurationCap.xml";
68 const char *const ParameterManagerWrapper::mPolicyPfwVendorConfFileName =
69     "/vendor/etc/parameter-framework/ParameterFrameworkConfigurationPolicy.xml";
70 
71 template <>
72 struct ParameterManagerWrapper::parameterManagerElementSupported<ISelectionCriterionInterface> {};
73 template <>
74 struct ParameterManagerWrapper::parameterManagerElementSupported<ISelectionCriterionTypeInterface> {};
75 
ParameterManagerWrapper(bool enableSchemaVerification,const std::string & schemaUri)76 ParameterManagerWrapper::ParameterManagerWrapper(bool enableSchemaVerification,
77                                                  const std::string &schemaUri)
78     : mPfwConnectorLogger(new ParameterMgrPlatformConnectorLogger)
79 {
80     // Connector
81     if (access(mPolicyPfwVendorConfFileName, R_OK) == 0) {
82         mPfwConnector = new CParameterMgrFullConnector(mPolicyPfwVendorConfFileName);
83     } else {
84         mPfwConnector = new CParameterMgrFullConnector(mPolicyPfwDefaultConfFileName);
85     }
86 
87     // Logger
88     mPfwConnector->setLogger(mPfwConnectorLogger);
89 
90     // Schema validation
91     std::string error;
92     bool ret = mPfwConnector->setValidateSchemasOnStart(enableSchemaVerification, error);
93     ALOGE_IF(!ret, "Failed to activate schema validation: %s", error.c_str());
94     if (enableSchemaVerification && ret && !schemaUri.empty()) {
95         ALOGE("Schema verification activated with schema URI: %s", schemaUri.c_str());
96         mPfwConnector->setSchemaUri(schemaUri);
97     }
98 }
99 
addCriterion(const std::string & name,bool isInclusive,ValuePairs pairs,const std::string & defaultValue)100 status_t ParameterManagerWrapper::addCriterion(const std::string &name, bool isInclusive,
101                                                ValuePairs pairs, const std::string &defaultValue)
102 {
103     ALOG_ASSERT(not isStarted(), "Cannot add a criterion if PFW is already started");
104     auto criterionType = mPfwConnector->createSelectionCriterionType(isInclusive);
105 
106     for (auto pair : pairs) {
107         std::string error;
108         ALOGV("%s: Adding pair %" PRIu64", %s for criterionType %s", __func__, std::get<0>(pair),
109               std::get<2>(pair).c_str(), name.c_str());
110         criterionType->addValuePair(std::get<0>(pair), std::get<2>(pair), error);
111 
112         if (name == capEngineConfig::gOutputDeviceCriterionName) {
113             ALOGV("%s: Adding mOutputDeviceToCriterionTypeMap %d %" PRIu64" for criterionType %s",
114                   __func__, std::get<1>(pair), std::get<0>(pair), name.c_str());
115             audio_devices_t androidType = static_cast<audio_devices_t>(std::get<1>(pair));
116             mOutputDeviceToCriterionTypeMap[androidType] = std::get<0>(pair);
117         }
118         if (name == capEngineConfig::gInputDeviceCriterionName) {
119             ALOGV("%s: Adding mInputDeviceToCriterionTypeMap %d %" PRIu64" for criterionType %s",
120                   __func__, std::get<1>(pair), std::get<0>(pair), name.c_str());
121             audio_devices_t androidType = static_cast<audio_devices_t>(std::get<1>(pair));
122             mInputDeviceToCriterionTypeMap[androidType] = std::get<0>(pair);
123         }
124     }
125     ALOG_ASSERT(mPolicyCriteria.find(name) == mPolicyCriteria.end(),
126                 "%s: Criterion %s already added", __FUNCTION__, name.c_str());
127 
128     auto criterion = mPfwConnector->createSelectionCriterion(name, criterionType);
129     mPolicyCriteria[name] = criterion;
130 
131     if (not defaultValue.empty()) {
132         uint64_t numericalValue = 0;
133         if (not criterionType->getNumericalValue(defaultValue.c_str(), numericalValue)) {
134             ALOGE("%s; trying to apply invalid default literal value (%s)", __FUNCTION__,
135                   defaultValue.c_str());
136         }
137         criterion->setCriterionState(numericalValue);
138     }
139     return NO_ERROR;
140 }
141 
~ParameterManagerWrapper()142 ParameterManagerWrapper::~ParameterManagerWrapper()
143 {
144     // Unset logger
145     mPfwConnector->setLogger(NULL);
146     // Remove logger
147     delete mPfwConnectorLogger;
148     // Remove connector
149     delete mPfwConnector;
150 }
151 
start(std::string & error)152 status_t ParameterManagerWrapper::start(std::string &error)
153 {
154     ALOGD("%s: in", __FUNCTION__);
155     /// Start PFW
156     if (!mPfwConnector->start(error)) {
157         ALOGE("%s: Policy PFW start error: %s", __FUNCTION__, error.c_str());
158         return NO_INIT;
159     }
160     ALOGD("%s: Policy PFW successfully started!", __FUNCTION__);
161     return NO_ERROR;
162 }
163 
164 template <typename T>
getElement(const string & name,std::map<string,T * > & elementsMap)165 T *ParameterManagerWrapper::getElement(const string &name, std::map<string, T *> &elementsMap)
166 {
167     parameterManagerElementSupported<T>();
168     typename std::map<string, T *>::iterator it = elementsMap.find(name);
169     ALOG_ASSERT(it != elementsMap.end(), "Element %s not found", name.c_str());
170     return it != elementsMap.end() ? it->second : NULL;
171 }
172 
173 template <typename T>
getElement(const string & name,const std::map<string,T * > & elementsMap) const174 const T *ParameterManagerWrapper::getElement(const string &name, const std::map<string, T *> &elementsMap) const
175 {
176     parameterManagerElementSupported<T>();
177     typename std::map<string, T *>::const_iterator it = elementsMap.find(name);
178     ALOG_ASSERT(it != elementsMap.end(), "Element %s not found", name.c_str());
179     return it != elementsMap.end() ? it->second : NULL;
180 }
181 
isStarted()182 bool ParameterManagerWrapper::isStarted()
183 {
184     return mPfwConnector && mPfwConnector->isStarted();
185 }
186 
setPhoneState(audio_mode_t mode)187 status_t ParameterManagerWrapper::setPhoneState(audio_mode_t mode)
188 {
189     ISelectionCriterionInterface *criterion = getElement<ISelectionCriterionInterface>(
190             capEngineConfig::gPhoneStateCriterionName, mPolicyCriteria);
191     if (criterion == NULL) {
192         ALOGE("%s: no criterion found for %s", __FUNCTION__,
193               capEngineConfig::gPhoneStateCriterionName);
194         return BAD_VALUE;
195     }
196     if (!isValueValidForCriterion(criterion, static_cast<int>(mode))) {
197         return BAD_VALUE;
198     }
199     criterion->setCriterionState((int)(mode));
200     applyPlatformConfiguration();
201     return NO_ERROR;
202 }
203 
getPhoneState() const204 audio_mode_t ParameterManagerWrapper::getPhoneState() const
205 {
206     const ISelectionCriterionInterface *criterion = getElement<ISelectionCriterionInterface>(
207             capEngineConfig::gPhoneStateCriterionName, mPolicyCriteria);
208     if (criterion == NULL) {
209         ALOGE("%s: no criterion found for %s", __FUNCTION__,
210               capEngineConfig::gPhoneStateCriterionName);
211         return AUDIO_MODE_NORMAL;
212     }
213     return static_cast<audio_mode_t>(criterion->getCriterionState());
214 }
215 
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)216 status_t ParameterManagerWrapper::setForceUse(audio_policy_force_use_t usage,
217                                               audio_policy_forced_cfg_t config)
218 {
219     // @todo: return an error on a unsupported value
220     if (usage > AUDIO_POLICY_FORCE_USE_CNT) {
221         return BAD_VALUE;
222     }
223 
224     ISelectionCriterionInterface *criterion = getElement<ISelectionCriterionInterface>(
225             capEngineConfig::gForceUseCriterionTag[usage], mPolicyCriteria);
226     if (criterion == NULL) {
227         ALOGE("%s: no criterion found for %s", __FUNCTION__,
228               capEngineConfig::gForceUseCriterionTag[usage]);
229         return BAD_VALUE;
230     }
231     if (!isValueValidForCriterion(criterion, static_cast<int>(config))) {
232         return BAD_VALUE;
233     }
234     criterion->setCriterionState((int)config);
235     applyPlatformConfiguration();
236     return NO_ERROR;
237 }
238 
getForceUse(audio_policy_force_use_t usage) const239 audio_policy_forced_cfg_t ParameterManagerWrapper::getForceUse(audio_policy_force_use_t usage) const
240 {
241     // @todo: return an error on a unsupported value
242     if (usage > AUDIO_POLICY_FORCE_USE_CNT) {
243         return AUDIO_POLICY_FORCE_NONE;
244     }
245     const ISelectionCriterionInterface *criterion = getElement<ISelectionCriterionInterface>(
246             capEngineConfig::gForceUseCriterionTag[usage], mPolicyCriteria);
247     if (criterion == NULL) {
248         ALOGE("%s: no criterion found for %s", __FUNCTION__,
249               capEngineConfig::gForceUseCriterionTag[usage]);
250         return AUDIO_POLICY_FORCE_NONE;
251     }
252     return static_cast<audio_policy_forced_cfg_t>(criterion->getCriterionState());
253 }
254 
isValueValidForCriterion(ISelectionCriterionInterface * criterion,int valueToCheck)255 bool ParameterManagerWrapper::isValueValidForCriterion(ISelectionCriterionInterface *criterion,
256                                                        int valueToCheck)
257 {
258     const ISelectionCriterionTypeInterface *interface = criterion->getCriterionType();
259     string literalValue;
260     return interface->getLiteralValue(valueToCheck, literalValue);
261 }
262 
setDeviceConnectionState(audio_devices_t type,const std::string & address,audio_policy_dev_state_t state)263 status_t ParameterManagerWrapper::setDeviceConnectionState(
264         audio_devices_t type, const std::string &address, audio_policy_dev_state_t state)
265 {
266     std::string criterionName = audio_is_output_device(type) ?
267             capEngineConfig::gOutputDeviceAddressCriterionName :
268             capEngineConfig::gInputDeviceAddressCriterionName;
269     ALOGV("%s: device with address %s %s", __FUNCTION__, address.c_str(),
270           state != AUDIO_POLICY_DEVICE_STATE_AVAILABLE? "disconnected" : "connected");
271     ISelectionCriterionInterface *criterion =
272             getElement<ISelectionCriterionInterface>(criterionName, mPolicyCriteria);
273 
274     if (criterion == NULL) {
275         ALOGE("%s: no criterion found for %s", __FUNCTION__, criterionName.c_str());
276         return DEAD_OBJECT;
277     }
278 
279     auto criterionType = criterion->getCriterionType();
280     uint64_t deviceAddressId;
281     if (not criterionType->getNumericalValue(address.c_str(), deviceAddressId)) {
282         ALOGW("%s: unknown device address reported (%s) for criterion %s", __FUNCTION__,
283               address.c_str(), criterionName.c_str());
284         return BAD_TYPE;
285     }
286     int currentValueMask = criterion->getCriterionState();
287     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
288         currentValueMask |= deviceAddressId;
289     }
290     else {
291         currentValueMask &= ~deviceAddressId;
292     }
293     criterion->setCriterionState(currentValueMask);
294     return NO_ERROR;
295 }
296 
setAvailableInputDevices(const DeviceTypeSet & types)297 status_t ParameterManagerWrapper::setAvailableInputDevices(const DeviceTypeSet &types) {
298     ISelectionCriterionInterface *criterion = getElement<ISelectionCriterionInterface>(
299             capEngineConfig::gInputDeviceCriterionName, mPolicyCriteria);
300     if (criterion == NULL) {
301         ALOGE("%s: no criterion found for %s", __func__,
302               capEngineConfig::gInputDeviceCriterionName);
303         return DEAD_OBJECT;
304     }
305     criterion->setCriterionState(convertDeviceTypesToCriterionValue(types));
306     applyPlatformConfiguration();
307     return NO_ERROR;
308 }
309 
setAvailableOutputDevices(const DeviceTypeSet & types)310 status_t ParameterManagerWrapper::setAvailableOutputDevices(const DeviceTypeSet &types) {
311     ISelectionCriterionInterface *criterion = getElement<ISelectionCriterionInterface>(
312             capEngineConfig::gOutputDeviceCriterionName, mPolicyCriteria);
313     if (criterion == NULL) {
314         ALOGE("%s: no criterion found for %s", __func__,
315               capEngineConfig::gOutputDeviceCriterionName);
316         return DEAD_OBJECT;
317     }
318     criterion->setCriterionState(convertDeviceTypesToCriterionValue(types));
319     applyPlatformConfiguration();
320     return NO_ERROR;
321 }
322 
applyPlatformConfiguration()323 void ParameterManagerWrapper::applyPlatformConfiguration()
324 {
325     mPfwConnector->applyConfigurations();
326 }
327 
convertDeviceTypeToCriterionValue(audio_devices_t type) const328 uint64_t ParameterManagerWrapper::convertDeviceTypeToCriterionValue(audio_devices_t type) const {
329     bool isOut = audio_is_output_devices(type);
330     const auto &adapters = isOut ? mOutputDeviceToCriterionTypeMap : mInputDeviceToCriterionTypeMap;
331     const auto &adapter = adapters.find(type);
332     if (adapter != adapters.end()) {
333         ALOGV("%s: multibit device %d converted to criterion %" PRIu64, __func__, type,
334               adapter->second);
335         return adapter->second;
336     }
337     ALOGE("%s: failed to find map for multibit device %d", __func__, type);
338     return 0;
339 }
340 
convertDeviceTypesToCriterionValue(const DeviceTypeSet & types) const341 uint64_t ParameterManagerWrapper::convertDeviceTypesToCriterionValue(
342         const DeviceTypeSet &types) const {
343     uint64_t criterionValue = 0;
344     for (const auto &type : types) {
345         criterionValue += convertDeviceTypeToCriterionValue(type);
346     }
347     return criterionValue;
348 }
349 
convertDeviceCriterionValueToDeviceTypes(uint64_t criterionValue,bool isOut) const350 DeviceTypeSet ParameterManagerWrapper::convertDeviceCriterionValueToDeviceTypes(
351         uint64_t criterionValue, bool isOut) const {
352     DeviceTypeSet deviceTypes;
353     const auto &adapters = isOut ? mOutputDeviceToCriterionTypeMap : mInputDeviceToCriterionTypeMap;
354     for (const auto &adapter : adapters) {
355         if ((adapter.second & criterionValue) == adapter.second) {
356             deviceTypes.insert(adapter.first);
357         }
358     }
359     return deviceTypes;
360 }
361 
createDomain(const std::string & domain)362 void ParameterManagerWrapper::createDomain(const std::string &domain)
363 {
364     std::string error;
365     bool ret = mPfwConnector->createDomain(domain, error);
366     if (!ret) {
367         ALOGD("%s: failed to create domain %s (error=%s)", __func__, domain.c_str(),
368         error.c_str());
369     }
370 }
371 
addConfigurableElementToDomain(const std::string & domain,const std::string & elementPath)372 void ParameterManagerWrapper::addConfigurableElementToDomain(const std::string &domain,
373         const std::string &elementPath)
374 {
375     std::string error;
376     bool ret = mPfwConnector->addConfigurableElementToDomain(domain, elementPath, error);
377     ALOGE_IF(!ret, "%s: failed to add parameter %s for domain %s (error=%s)",
378               __func__, elementPath.c_str(), domain.c_str(), error.c_str());
379 }
380 
createConfiguration(const std::string & domain,const std::string & configurationName)381 void ParameterManagerWrapper::createConfiguration(const std::string &domain,
382         const std::string &configurationName)
383 {
384     std::string error;
385     bool ret = mPfwConnector->createConfiguration(domain, configurationName, error);
386     ALOGE_IF(!ret, "%s: failed to create configuration %s for domain %s (error=%s)",
387               __func__, configurationName.c_str(), domain.c_str(), error.c_str());
388 }
389 
setApplicationRule(const std::string & domain,const std::string & configurationName,const std::string & rule)390 void ParameterManagerWrapper::setApplicationRule(
391         const std::string &domain, const std::string &configurationName, const std::string &rule)
392 {
393     std::string error;
394     bool ret = mPfwConnector->setApplicationRule(domain, configurationName, rule, error);
395     ALOGE_IF(!ret, "%s: failed to set rule %s for domain %s and configuration %s (error=%s)",
396               __func__, rule.c_str(), domain.c_str(), configurationName.c_str(), error.c_str());
397 }
398 
accessConfigurationValue(const std::string & domain,const std::string & configurationName,const std::string & elementPath,std::string & value)399 void ParameterManagerWrapper::accessConfigurationValue(const std::string &domain,
400         const std::string &configurationName, const std::string &elementPath,
401         std::string &value)
402 {
403     std::string error;
404     bool ret = mPfwConnector->accessConfigurationValue(domain, configurationName, elementPath,
405             value, /*set=*/ true, error);
406     ALOGE_IF(!ret, "%s: failed to set value %s for parameter %s on domain %s and configuration %s "
407           "(error=%s)", __func__, value.c_str(), elementPath.c_str(),  domain.c_str(),
408           configurationName.c_str(), error.c_str());
409 }
410 
setConfiguration(const android::capEngineConfig::ParsingResult & capSettings)411 status_t ParameterManagerWrapper::setConfiguration(
412         const android::capEngineConfig::ParsingResult& capSettings)
413 {
414     if (!isStarted()) {
415         return NO_INIT;
416     }
417     std::string error;
418     if (!mPfwConnector->setTuningMode(/* bOn= */ true, error)) {
419         ALOGD("%s: failed to set Tuning Mode error=%s", __FUNCTION__, error.c_str());
420         return DEAD_OBJECT;
421     }
422     for (auto &domain: capSettings.parsedConfig->capConfigurableDomains) {
423         createDomain(domain.name);
424         for (const auto &configurableElementValue : domain.settings[0].configurableElementValues) {
425             addConfigurableElementToDomain(domain.name,
426                     configurableElementValue.configurableElement.path);
427         }
428         for (const auto &configuration : domain.configurations) {
429             createConfiguration(domain.name, configuration.name);
430             setApplicationRule(domain.name, configuration.name, configuration.rule);
431         }
432         for (const auto &setting : domain.settings) {
433             for (const auto &configurableElementValue : setting.configurableElementValues) {
434                 std::string value = configurableElementValue.value;
435                 accessConfigurationValue(domain.name, setting.configurationName,
436                         configurableElementValue.configurableElement.path, value);
437             }
438 
439         }
440     }
441     mPfwConnector->setTuningMode(/* bOn= */ false, error);
442     return OK;
443 }
444 
445 } // namespace audio_policy
446 } // namespace android
447