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 #include "EvsStateControl.h"
17
18 #include "FormatConvert.h"
19 #include "RenderDirectView.h"
20 #include "RenderPixelCopy.h"
21 #include "RenderTopView.h"
22
23 #include <android-base/logging.h>
24 #include <android/binder_manager.h>
25 #include <utils/SystemClock.h>
26
27 #include <inttypes.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 using ::android::hardware::automotive::evs::V1_0::EvsResult;
32 using EvsDisplayState = ::android::hardware::automotive::evs::V1_0::DisplayState;
33 using BufferDesc_1_0 = ::android::hardware::automotive::evs::V1_0::BufferDesc;
34 using BufferDesc_1_1 = ::android::hardware::automotive::evs::V1_1::BufferDesc;
35
isSfReady()36 static bool isSfReady() {
37 return ::ndk::SpAIBinder(::AServiceManager_getService("SurfaceFlinger")).get() != nullptr;
38 }
39
40 // TODO: Seems like it'd be nice if the Vehicle HAL provided such helpers (but how & where?)
getPropType(VehicleProperty prop)41 inline constexpr VehiclePropertyType getPropType(VehicleProperty prop) {
42 return static_cast<VehiclePropertyType>(
43 static_cast<int32_t>(prop)
44 & static_cast<int32_t>(VehiclePropertyType::MASK));
45 }
46
EvsStateControl(android::sp<IVehicle> pVnet,android::sp<IEvsEnumerator> pEvs,android::sp<IEvsDisplay> pDisplay,const ConfigManager & config)47 EvsStateControl::EvsStateControl(android::sp<IVehicle> pVnet, android::sp<IEvsEnumerator> pEvs,
48 android::sp<IEvsDisplay> pDisplay, const ConfigManager& config) :
49 mVehicle(pVnet),
50 mEvs(pEvs),
51 mDisplay(pDisplay),
52 mConfig(config),
53 mCurrentState(OFF),
54 mEvsStats(EvsStats::build()) {
55 // Initialize the property value containers we'll be updating (they'll be zeroed by default)
56 static_assert(getPropType(VehicleProperty::GEAR_SELECTION) == VehiclePropertyType::INT32,
57 "Unexpected type for GEAR_SELECTION property");
58 static_assert(getPropType(VehicleProperty::TURN_SIGNAL_STATE) == VehiclePropertyType::INT32,
59 "Unexpected type for TURN_SIGNAL_STATE property");
60
61 mGearValue.prop = static_cast<int32_t>(VehicleProperty::GEAR_SELECTION);
62 mTurnSignalValue.prop = static_cast<int32_t>(VehicleProperty::TURN_SIGNAL_STATE);
63
64 // This way we only ever deal with cameras which exist in the system
65 // Build our set of cameras for the states we support
66 LOG(DEBUG) << "Requesting camera list";
67 mEvs->getCameraList_1_1(
68 [this, &config](hidl_vec<CameraDesc> cameraList) {
69 LOG(INFO) << "Camera list callback received " << cameraList.size() << "cameras.";
70 for (auto&& cam: cameraList) {
71 LOG(DEBUG) << "Found camera " << cam.v1.cameraId;
72 bool cameraConfigFound = false;
73
74 // Check our configuration for information about this camera
75 // Note that a camera can have a compound function string
76 // such that a camera can be "right/reverse" and be used for both.
77 // If more than one camera is listed for a given function, we'll
78 // list all of them and let the UX/rendering logic use one, some
79 // or all of them as appropriate.
80 for (auto&& info: config.getCameras()) {
81 if (cam.v1.cameraId == info.cameraId) {
82 // We found a match!
83 if (info.function.find("reverse") != std::string::npos) {
84 mCameraList[State::REVERSE].emplace_back(info);
85 mCameraDescList[State::REVERSE].emplace_back(cam);
86 }
87 if (info.function.find("right") != std::string::npos) {
88 mCameraList[State::RIGHT].emplace_back(info);
89 mCameraDescList[State::RIGHT].emplace_back(cam);
90 }
91 if (info.function.find("left") != std::string::npos) {
92 mCameraList[State::LEFT].emplace_back(info);
93 mCameraDescList[State::LEFT].emplace_back(cam);
94 }
95 if (info.function.find("park") != std::string::npos) {
96 mCameraList[State::PARKING].emplace_back(info);
97 mCameraDescList[State::PARKING].emplace_back(cam);
98 }
99 cameraConfigFound = true;
100 break;
101 }
102 }
103 if (!cameraConfigFound) {
104 LOG(WARNING) << "No config information for hardware camera "
105 << cam.v1.cameraId;
106 }
107 }
108 }
109 );
110
111 LOG(DEBUG) << "State controller ready";
112 }
113
startUpdateLoop()114 bool EvsStateControl::startUpdateLoop() {
115 // Create the thread and report success if it gets started
116 mRenderThread = std::thread([this](){ updateLoop(); });
117 return mRenderThread.joinable();
118 }
119
120
terminateUpdateLoop()121 void EvsStateControl::terminateUpdateLoop() {
122 // Join a rendering thread
123 if (mRenderThread.joinable()) {
124 mRenderThread.join();
125 }
126 }
127
128
postCommand(const Command & cmd,bool clear)129 void EvsStateControl::postCommand(const Command& cmd, bool clear) {
130 // Push the command onto the queue watched by updateLoop
131 mLock.lock();
132 if (clear) {
133 std::queue<Command> emptyQueue;
134 std::swap(emptyQueue, mCommandQueue);
135 }
136
137 mCommandQueue.push(cmd);
138 mLock.unlock();
139
140 // Send a signal to wake updateLoop in case it is asleep
141 mWakeSignal.notify_all();
142 }
143
144
updateLoop()145 void EvsStateControl::updateLoop() {
146 LOG(DEBUG) << "Starting EvsStateControl update loop";
147
148 bool run = true;
149 while (run) {
150 // Process incoming commands
151 {
152 std::lock_guard <std::mutex> lock(mLock);
153 while (!mCommandQueue.empty()) {
154 const Command& cmd = mCommandQueue.front();
155 switch (cmd.operation) {
156 case Op::EXIT:
157 run = false;
158 break;
159 case Op::CHECK_VEHICLE_STATE:
160 // Just running selectStateForCurrentConditions below will take care of this
161 break;
162 case Op::TOUCH_EVENT:
163 // Implement this given the x/y location of the touch event
164 break;
165 }
166 mCommandQueue.pop();
167 }
168 }
169
170 // Review vehicle state and choose an appropriate renderer
171 if (!selectStateForCurrentConditions()) {
172 LOG(ERROR) << "selectStateForCurrentConditions failed so we're going to die";
173 break;
174 }
175
176 // If we have an active renderer, give it a chance to draw
177 if (mCurrentRenderer) {
178 // Get the output buffer we'll use to display the imagery
179 BufferDesc_1_0 tgtBuffer = {};
180 mDisplay->getTargetBuffer([&tgtBuffer](const BufferDesc_1_0& buff) {
181 tgtBuffer = buff;
182 }
183 );
184
185 if (tgtBuffer.memHandle == nullptr) {
186 LOG(ERROR) << "Didn't get requested output buffer -- skipping this frame.";
187 run = false;
188 } else {
189 // Generate our output image
190 if (!mCurrentRenderer->drawFrame(convertBufferDesc(tgtBuffer))) {
191 // If drawing failed, we want to exit quickly so an app restart can happen
192 run = false;
193 }
194
195 // Send the finished image back for display
196 mDisplay->returnTargetBufferForDisplay(tgtBuffer);
197
198 if (!mFirstFrameIsDisplayed) {
199 mFirstFrameIsDisplayed = true;
200 // returnTargetBufferForDisplay() is finished, the frame should be displayed
201 mEvsStats.finishComputingFirstFrameLatency(android::uptimeMillis());
202 }
203 }
204 } else if (run) {
205 // No active renderer, so sleep until somebody wakes us with another command
206 // or exit if we received EXIT command
207 std::unique_lock<std::mutex> lock(mLock);
208 mWakeSignal.wait(lock);
209 }
210 }
211
212 LOG(WARNING) << "EvsStateControl update loop ending";
213
214 if (mCurrentRenderer) {
215 // Deactive the renderer
216 mCurrentRenderer->deactivate();
217 }
218
219 // If `ICarTelemetry` service was not ready before, we need to try sending data again.
220 mEvsStats.sendCollectedDataBlocking();
221
222 printf("Shutting down app due to state control loop ending\n");
223 LOG(ERROR) << "Shutting down app due to state control loop ending";
224 }
225
226
selectStateForCurrentConditions()227 bool EvsStateControl::selectStateForCurrentConditions() {
228 static int32_t sMockGear = mConfig.getMockGearSignal();
229 static int32_t sMockSignal = int32_t(VehicleTurnSignal::NONE);
230
231 if (mVehicle != nullptr) {
232 // Query the car state
233 if (invokeGet(&mGearValue) != StatusCode::OK) {
234 LOG(ERROR) << "GEAR_SELECTION not available from vehicle. Exiting.";
235 return false;
236 }
237 if ((mTurnSignalValue.prop == 0) || (invokeGet(&mTurnSignalValue) != StatusCode::OK)) {
238 // Silently treat missing turn signal state as no turn signal active
239 mTurnSignalValue.value.int32Values.setToExternal(&sMockSignal, 1);
240 mTurnSignalValue.prop = 0;
241 }
242 } else {
243 // While testing without a vehicle, behave as if we're in reverse for the first 20 seconds
244 static const int kShowTime = 20; // seconds
245
246 // See if it's time to turn off the default reverse camera
247 static std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
248 std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
249 if (std::chrono::duration_cast<std::chrono::seconds>(now - start).count() > kShowTime) {
250 // Switch to drive (which should turn off the reverse camera)
251 sMockGear = int32_t(VehicleGear::GEAR_DRIVE);
252 }
253
254 // Build the placeholder vehicle state values (treating single values as 1 element vectors)
255 mGearValue.value.int32Values.setToExternal(&sMockGear, 1);
256 mTurnSignalValue.value.int32Values.setToExternal(&sMockSignal, 1);
257 }
258
259 // Choose our desired EVS state based on the current car state
260 // TODO: Update this logic, and consider user input when choosing if a view should be presented
261 State desiredState = OFF;
262 if (mGearValue.value.int32Values[0] == int32_t(VehicleGear::GEAR_REVERSE)) {
263 desiredState = REVERSE;
264 } else if (mTurnSignalValue.value.int32Values[0] == int32_t(VehicleTurnSignal::RIGHT)) {
265 desiredState = RIGHT;
266 } else if (mTurnSignalValue.value.int32Values[0] == int32_t(VehicleTurnSignal::LEFT)) {
267 desiredState = LEFT;
268 } else if (mGearValue.value.int32Values[0] == int32_t(VehicleGear::GEAR_PARK)) {
269 desiredState = PARKING;
270 }
271
272 // Apply the desire state
273 return configureEvsPipeline(desiredState);
274 }
275
276
invokeGet(VehiclePropValue * pRequestedPropValue)277 StatusCode EvsStateControl::invokeGet(VehiclePropValue *pRequestedPropValue) {
278 StatusCode status = StatusCode::TRY_AGAIN;
279
280 // Call the Vehicle HAL, which will block until the callback is complete
281 mVehicle->get(*pRequestedPropValue,
282 [pRequestedPropValue, &status]
283 (StatusCode s, const VehiclePropValue& v) {
284 status = s;
285 if (s == StatusCode::OK) {
286 *pRequestedPropValue = v;
287 }
288 }
289 );
290
291 return status;
292 }
293
294
configureEvsPipeline(State desiredState)295 bool EvsStateControl::configureEvsPipeline(State desiredState) {
296 static bool isGlReady = false;
297
298 if (mCurrentState == desiredState) {
299 // Nothing to do here...
300 return true;
301 }
302
303 // Used by CarStats to accurately compute stats, it needs to be close to the beginning.
304 auto desiredStateTimeMillis = android::uptimeMillis();
305
306 LOG(DEBUG) << "Switching to state " << desiredState;
307 LOG(DEBUG) << " Current state " << mCurrentState
308 << " has " << mCameraList[mCurrentState].size() << " cameras";
309 LOG(DEBUG) << " Desired state " << desiredState
310 << " has " << mCameraList[desiredState].size() << " cameras";
311
312 if (!isGlReady && !isSfReady()) {
313 // Graphics is not ready yet; using CPU renderer.
314 if (mCameraList[desiredState].size() >= 1) {
315 mDesiredRenderer = std::make_unique<RenderPixelCopy>(mEvs,
316 mCameraList[desiredState][0]);
317 if (!mDesiredRenderer) {
318 LOG(ERROR) << "Failed to construct Pixel Copy renderer. Skipping state change.";
319 return false;
320 }
321 } else {
322 LOG(DEBUG) << "Unsupported, desiredState " << desiredState
323 << " has " << mCameraList[desiredState].size() << " cameras.";
324 }
325 } else {
326 // Assumes that SurfaceFlinger is available always after being launched.
327
328 // Do we need a new direct view renderer?
329 if (mCameraList[desiredState].size() == 1) {
330 // We have a camera assigned to this state for direct view.
331 mDesiredRenderer = std::make_unique<RenderDirectView>(mEvs,
332 mCameraDescList[desiredState][0],
333 mConfig);
334 if (!mDesiredRenderer) {
335 LOG(ERROR) << "Failed to construct direct renderer. Skipping state change.";
336 return false;
337 }
338 } else if (mCameraList[desiredState].size() > 1 || desiredState == PARKING) {
339 //TODO(b/140668179): RenderTopView needs to be updated to use new
340 // ConfigManager.
341 mDesiredRenderer = std::make_unique<RenderTopView>(mEvs,
342 mCameraList[desiredState],
343 mConfig);
344 if (!mDesiredRenderer) {
345 LOG(ERROR) << "Failed to construct top view renderer. Skipping state change.";
346 return false;
347 }
348 } else {
349 LOG(DEBUG) << "Unsupported, desiredState " << desiredState
350 << " has " << mCameraList[desiredState].size() << " cameras.";
351 }
352
353 // GL renderer is now ready.
354 isGlReady = true;
355 }
356
357 // Since we're changing states, shut down the current renderer
358 if (mCurrentRenderer != nullptr) {
359 mCurrentRenderer->deactivate();
360 mCurrentRenderer = nullptr; // It's a smart pointer, so destructs on assignment to null
361 }
362
363 // Now set the display state based on whether we have a video feed to show
364 if (mDesiredRenderer == nullptr) {
365 LOG(DEBUG) << "Turning off the display";
366 mDisplay->setDisplayState(EvsDisplayState::NOT_VISIBLE);
367 } else {
368 mCurrentRenderer = std::move(mDesiredRenderer);
369
370 // Start the camera stream
371 LOG(DEBUG) << "EvsStartCameraStreamTiming start time: "
372 << android::elapsedRealtime() << " ms.";
373 if (!mCurrentRenderer->activate()) {
374 LOG(ERROR) << "New renderer failed to activate";
375 return false;
376 }
377
378 // Activate the display
379 LOG(DEBUG) << "EvsActivateDisplayTiming start time: "
380 << android::elapsedRealtime() << " ms.";
381 Return<EvsResult> result = mDisplay->setDisplayState(EvsDisplayState::VISIBLE_ON_NEXT_FRAME);
382 if (result != EvsResult::OK) {
383 LOG(ERROR) << "setDisplayState returned an error "
384 << result.description();
385 return false;
386 }
387 }
388
389 // Record our current state
390 LOG(INFO) << "Activated state " << desiredState;
391 mCurrentState = desiredState;
392
393 mFirstFrameIsDisplayed = false; // Got a new renderer, mark first frame is not displayed.
394
395 if (mCurrentRenderer != nullptr && desiredState == State::REVERSE) {
396 // Start computing the latency when the evs state changes.
397 mEvsStats.startComputingFirstFrameLatency(desiredStateTimeMillis);
398 }
399
400 return true;
401 }
402