1 /*
2  * Copyright (C) 2016 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_NDEBUG 0
18 #define LOG_TAG "EnumConverter"
19 
20 #include "enum_converter.h"
21 
22 #include <cerrno>
23 
24 #include "common.h"
25 
26 namespace v4l2_camera_hal {
27 
EnumConverter(const std::multimap<int32_t,uint8_t> & v4l2_to_metadata)28 EnumConverter::EnumConverter(
29     const std::multimap<int32_t, uint8_t>& v4l2_to_metadata)
30     : v4l2_to_metadata_(v4l2_to_metadata) {
31   HAL_LOG_ENTER();
32 }
33 
MetadataToV4L2(uint8_t value,int32_t * conversion)34 int EnumConverter::MetadataToV4L2(uint8_t value, int32_t* conversion) {
35   // Unfortunately no bi-directional map lookup in C++.
36   // Breaking on second, not first found so that a warning
37   // can be given if there are multiple values.
38   size_t count = 0;
39   for (auto kv : v4l2_to_metadata_) {
40     if (kv.second == value) {
41       ++count;
42       if (count == 1) {
43         // First match.
44         *conversion = kv.first;
45       } else {
46         // second match.
47         break;
48       }
49     }
50   }
51 
52   if (count == 0) {
53     HAL_LOGV("Couldn't find V4L2 conversion of metadata value %d.", value);
54     return -EINVAL;
55   } else if (count > 1) {
56     HAL_LOGV(
57         "Multiple V4L2 conversions found for metadata value %d, using first.",
58         value);
59   }
60   return 0;
61 }
62 
V4L2ToMetadata(int32_t value,uint8_t * conversion)63 int EnumConverter::V4L2ToMetadata(int32_t value, uint8_t* conversion) {
64   auto element_range = v4l2_to_metadata_.equal_range(value);
65   if (element_range.first == element_range.second) {
66     HAL_LOGV("Couldn't find metadata conversion of V4L2 value %d.", value);
67     return -EINVAL;
68   }
69 
70   auto element = element_range.first;
71   *conversion = element->second;
72 
73   if (++element != element_range.second) {
74     HAL_LOGV(
75         "Multiple metadata conversions found for V4L2 value %d, using first.",
76         value);
77   }
78   return 0;
79 }
80 
81 }  // namespace v4l2_camera_hal
82