liyujie
2025-08-28 867b8b7b729282c7e14e200ca277435329ebe747
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define LOG_TAG "ExtCamUtils@3.4"
//#define LOG_NDEBUG 0
#include <log/log.h>
 
#include <cmath>
#include <sys/mman.h>
#include <linux/videodev2.h>
#include "ExternalCameraUtils.h"
 
namespace android {
namespace hardware {
namespace camera {
namespace device {
namespace V3_4 {
namespace implementation {
 
V4L2Frame::V4L2Frame(
        uint32_t w, uint32_t h, uint32_t fourcc,
        int bufIdx, int fd, uint32_t dataSize, uint64_t offset) :
        mWidth(w), mHeight(h), mFourcc(fourcc),
        mBufferIndex(bufIdx), mFd(fd), mDataSize(dataSize), mOffset(offset) {}
 
int V4L2Frame::map(uint8_t** data, size_t* dataSize) {
    if (data == nullptr || dataSize == nullptr) {
        ALOGI("%s: V4L2 buffer map bad argument: data %p, dataSize %p",
                __FUNCTION__, data, dataSize);
        return -EINVAL;
    }
 
    std::lock_guard<std::mutex> lk(mLock);
    if (!mMapped) {
        void* addr = mmap(NULL, mDataSize, PROT_READ, MAP_SHARED, mFd, mOffset);
        if (addr == MAP_FAILED) {
            ALOGE("%s: V4L2 buffer map failed: %s", __FUNCTION__, strerror(errno));
            return -EINVAL;
        }
        mData = static_cast<uint8_t*>(addr);
        mMapped = true;
    }
    *data = mData;
    *dataSize = mDataSize;
    ALOGV("%s: V4L map FD %d, data %p size %zu", __FUNCTION__, mFd, mData, mDataSize);
    return 0;
}
 
int V4L2Frame::unmap() {
    std::lock_guard<std::mutex> lk(mLock);
    if (mMapped) {
        ALOGV("%s: V4L unmap data %p size %zu", __FUNCTION__, mData, mDataSize);
        if (munmap(mData, mDataSize) != 0) {
            ALOGE("%s: V4L2 buffer unmap failed: %s", __FUNCTION__, strerror(errno));
            return -EINVAL;
        }
        mMapped = false;
    }
    return 0;
}
 
V4L2Frame::~V4L2Frame() {
    unmap();
}
 
AllocatedFrame::AllocatedFrame(
        uint32_t w, uint32_t h) :
        mWidth(w), mHeight(h), mFourcc(V4L2_PIX_FMT_YUV420) {};
 
AllocatedFrame::~AllocatedFrame() {}
 
int AllocatedFrame::allocate(YCbCrLayout* out) {
    std::lock_guard<std::mutex> lk(mLock);
    if ((mWidth % 2) || (mHeight % 2)) {
        ALOGE("%s: bad dimension %dx%d (not multiple of 2)", __FUNCTION__, mWidth, mHeight);
        return -EINVAL;
    }
 
    uint32_t dataSize = mWidth * mHeight * 3 / 2; // YUV420
    if (mData.size() != dataSize) {
        mData.resize(dataSize);
    }
 
    if (out != nullptr) {
        out->y = mData.data();
        out->yStride = mWidth;
        uint8_t* cbStart = mData.data() + mWidth * mHeight;
        uint8_t* crStart = cbStart + mWidth * mHeight / 4;
        out->cb = cbStart;
        out->cr = crStart;
        out->cStride = mWidth / 2;
        out->chromaStep = 1;
    }
    return 0;
}
 
int AllocatedFrame::getLayout(YCbCrLayout* out) {
    IMapper::Rect noCrop = {0, 0,
            static_cast<int32_t>(mWidth),
            static_cast<int32_t>(mHeight)};
    return getCroppedLayout(noCrop, out);
}
 
int AllocatedFrame::getCroppedLayout(const IMapper::Rect& rect, YCbCrLayout* out) {
    if (out == nullptr) {
        ALOGE("%s: null out", __FUNCTION__);
        return -1;
    }
 
    std::lock_guard<std::mutex> lk(mLock);
    if ((rect.left + rect.width) > static_cast<int>(mWidth) ||
        (rect.top + rect.height) > static_cast<int>(mHeight) ||
            (rect.left % 2) || (rect.top % 2) || (rect.width % 2) || (rect.height % 2)) {
        ALOGE("%s: bad rect left %d top %d w %d h %d", __FUNCTION__,
                rect.left, rect.top, rect.width, rect.height);
        return -1;
    }
 
    out->y = mData.data() + mWidth * rect.top + rect.left;
    out->yStride = mWidth;
    uint8_t* cbStart = mData.data() + mWidth * mHeight;
    uint8_t* crStart = cbStart + mWidth * mHeight / 4;
    out->cb = cbStart + mWidth * rect.top / 4 + rect.left / 2;
    out->cr = crStart + mWidth * rect.top / 4 + rect.left / 2;
    out->cStride = mWidth / 2;
    out->chromaStep = 1;
    return 0;
}
 
bool isAspectRatioClose(float ar1, float ar2) {
    const float kAspectRatioMatchThres = 0.025f; // This threshold is good enough to distinguish
                                                // 4:3/16:9/20:9
                                                // 1.33 / 1.78 / 2
    return (std::abs(ar1 - ar2) < kAspectRatioMatchThres);
}
 
double SupportedV4L2Format::FrameRate::getDouble() const {
    return durationDenominator / static_cast<double>(durationNumerator);
}
 
}  // namespace implementation
}  // namespace V3_4
}  // namespace device
 
 
namespace external {
namespace common {
 
namespace {
    const int kDefaultJpegBufSize = 5 << 20; // 5MB
    const int kDefaultNumVideoBuffer = 4;
    const int kDefaultNumStillBuffer = 2;
    const int kDefaultOrientation = 0; // suitable for natural landscape displays like tablet/TV
                                       // For phone devices 270 is better
    const int kDefaultJpegOrientation = 0;
} // anonymous namespace
 
const char* ExternalCameraConfig::kDefaultCfgPath = "/vendor/etc/external_camera_config.xml";
 
ExternalCameraConfig ExternalCameraConfig::loadFromCfg(const char* cfgPath) {
    using namespace tinyxml2;
    ExternalCameraConfig ret;
 
    XMLDocument configXml;
    XMLError err = configXml.LoadFile(cfgPath);
    if (err != XML_SUCCESS) {
        ALOGE("%s: Unable to load external camera config file '%s'. Error: %s",
                __FUNCTION__, cfgPath, XMLDocument::ErrorIDToName(err));
        return ret;
    } else {
        ALOGI("%s: load external camera config succeed!", __FUNCTION__);
    }
 
    XMLElement *extCam = configXml.FirstChildElement("ExternalCamera");
    if (extCam == nullptr) {
        ALOGI("%s: no external camera config specified", __FUNCTION__);
        return ret;
    }
 
    XMLElement *providerCfg = extCam->FirstChildElement("Provider");
    if (providerCfg == nullptr) {
        ALOGI("%s: no external camera provider config specified", __FUNCTION__);
        return ret;
    }
 
    XMLElement *ignore = providerCfg->FirstChildElement("ignore");
    if (ignore == nullptr) {
        ALOGI("%s: no internal ignored device specified", __FUNCTION__);
        return ret;
    }
 
    XMLElement *id = ignore->FirstChildElement("id");
    while (id != nullptr) {
        const char* text = id->GetText();
        if (text != nullptr) {
            ret.mInternalDevices.insert(text);
            ALOGI("%s: device %s will be ignored by external camera provider",
                    __FUNCTION__, text);
        }
        id = id->NextSiblingElement("id");
    }
 
    XMLElement *deviceCfg = extCam->FirstChildElement("Device");
    if (deviceCfg == nullptr) {
        ALOGI("%s: no external camera device config specified", __FUNCTION__);
        return ret;
    }
 
    XMLElement *jpegBufSz = deviceCfg->FirstChildElement("MaxJpegBufferSize");
    if (jpegBufSz == nullptr) {
        ALOGI("%s: no max jpeg buffer size specified", __FUNCTION__);
    } else {
        ret.maxJpegBufSize = jpegBufSz->UnsignedAttribute("bytes", /*Default*/kDefaultJpegBufSize);
    }
 
    XMLElement *numVideoBuf = deviceCfg->FirstChildElement("NumVideoBuffers");
    if (numVideoBuf == nullptr) {
        ALOGI("%s: no num video buffers specified", __FUNCTION__);
    } else {
        ret.numVideoBuffers =
                numVideoBuf->UnsignedAttribute("count", /*Default*/kDefaultNumVideoBuffer);
    }
 
    XMLElement *numStillBuf = deviceCfg->FirstChildElement("NumStillBuffers");
    if (numStillBuf == nullptr) {
        ALOGI("%s: no num still buffers specified", __FUNCTION__);
    } else {
        ret.numStillBuffers =
                numStillBuf->UnsignedAttribute("count", /*Default*/kDefaultNumStillBuffer);
    }
 
    XMLElement *fpsList = deviceCfg->FirstChildElement("FpsList");
    if (fpsList == nullptr) {
        ALOGI("%s: no fps list specified", __FUNCTION__);
    } else {
        if (!updateFpsList(fpsList, ret.fpsLimits)) {
            return ret;
        }
    }
 
    XMLElement *depth = deviceCfg->FirstChildElement("Depth16Supported");
    if (depth == nullptr) {
        ret.depthEnabled = false;
        ALOGI("%s: depth output is not enabled", __FUNCTION__);
    } else {
        ret.depthEnabled = depth->BoolAttribute("enabled", false);
    }
 
    if(ret.depthEnabled) {
        XMLElement *depthFpsList = deviceCfg->FirstChildElement("DepthFpsList");
        if (depthFpsList == nullptr) {
            ALOGW("%s: no depth fps list specified", __FUNCTION__);
        } else {
            if(!updateFpsList(depthFpsList, ret.depthFpsLimits)) {
                return ret;
            }
        }
    }
 
    XMLElement *minStreamSize = deviceCfg->FirstChildElement("MinimumStreamSize");
    if (minStreamSize == nullptr) {
       ALOGI("%s: no minimum stream size specified", __FUNCTION__);
    } else {
        ret.minStreamSize = {
                minStreamSize->UnsignedAttribute("width", /*Default*/0),
                minStreamSize->UnsignedAttribute("height", /*Default*/0)};
    }
 
    XMLElement *orientation = deviceCfg->FirstChildElement("Orientation");
    if (orientation == nullptr) {
        ALOGI("%s: no sensor orientation specified", __FUNCTION__);
    } else {
        ret.orientation = orientation->IntAttribute("degree", /*Default*/kDefaultOrientation);
    }
 
    XMLElement *jpegOrientation = deviceCfg->FirstChildElement("JpegOrientation");
    if (jpegOrientation == nullptr) {
        ALOGI("%s: no jpeg orientation specified", __FUNCTION__);
    } else {
        ret.jpegOrientation = jpegOrientation->IntAttribute("degree",
            /*Default*/kDefaultJpegOrientation);
    }
 
    ALOGI("%s: external camera cfg loaded: maxJpgBufSize %d,"
            " num video buffers %d, num still buffers %d, orientation %d jpeg orientation %d",
            __FUNCTION__, ret.maxJpegBufSize,
            ret.numVideoBuffers, ret.numStillBuffers,
            ret.orientation, ret.jpegOrientation);
    for (const auto& limit : ret.fpsLimits) {
        ALOGI("%s: fpsLimitList: %dx%d@%f", __FUNCTION__,
                limit.size.width, limit.size.height, limit.fpsUpperBound);
    }
    for (const auto& limit : ret.depthFpsLimits) {
        ALOGI("%s: depthFpsLimitList: %dx%d@%f", __FUNCTION__, limit.size.width, limit.size.height,
              limit.fpsUpperBound);
    }
    ALOGI("%s: minStreamSize: %dx%d" , __FUNCTION__,
         ret.minStreamSize.width, ret.minStreamSize.height);
    return ret;
}
 
bool ExternalCameraConfig::updateFpsList(tinyxml2::XMLElement* fpsList,
        std::vector<FpsLimitation>& fpsLimits) {
    using namespace tinyxml2;
    std::vector<FpsLimitation> limits;
    XMLElement* row = fpsList->FirstChildElement("Limit");
    while (row != nullptr) {
        FpsLimitation prevLimit{{0, 0}, 1000.0};
        FpsLimitation limit;
        limit.size = {row->UnsignedAttribute("width", /*Default*/ 0),
                      row->UnsignedAttribute("height", /*Default*/ 0)};
        limit.fpsUpperBound = row->DoubleAttribute("fpsBound", /*Default*/ 1000.0);
        if (limit.size.width <= prevLimit.size.width ||
            limit.size.height <= prevLimit.size.height ||
            limit.fpsUpperBound >= prevLimit.fpsUpperBound) {
            ALOGE(
                "%s: FPS limit list must have increasing size and decreasing fps!"
                " Prev %dx%d@%f, Current %dx%d@%f",
                __FUNCTION__, prevLimit.size.width, prevLimit.size.height, prevLimit.fpsUpperBound,
                limit.size.width, limit.size.height, limit.fpsUpperBound);
            return false;
        }
        limits.push_back(limit);
        row = row->NextSiblingElement("Limit");
    }
    fpsLimits = limits;
    return true;
}
 
ExternalCameraConfig::ExternalCameraConfig() :
        maxJpegBufSize(kDefaultJpegBufSize),
        numVideoBuffers(kDefaultNumVideoBuffer),
        numStillBuffers(kDefaultNumStillBuffer),
        depthEnabled(false),
        orientation(kDefaultOrientation) {
    fpsLimits.push_back({/*Size*/{ 640,  480}, /*FPS upper bound*/30.0});
    fpsLimits.push_back({/*Size*/{1280,  720}, /*FPS upper bound*/7.5});
    fpsLimits.push_back({/*Size*/{1920, 1080}, /*FPS upper bound*/5.0});
    minStreamSize = {0, 0};
}
 
 
}  // namespace common
}  // namespace external
}  // namespace camera
}  // namespace hardware
}  // namespace android