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 #include "ConfigManager.h"
18 #include "EvsStateControl.h"
19 #include "EvsVehicleListener.h"
20 
21 #include <signal.h>
22 #include <stdio.h>
23 
24 #include <android/hardware/automotive/evs/1.1/IEvsDisplay.h>
25 #include <android/hardware/automotive/evs/1.1/IEvsEnumerator.h>
26 #include <android-base/logging.h>
27 #include <android-base/macros.h>    // arraysize
28 #include <android-base/strings.h>
29 #include <hidl/HidlTransportSupport.h>
30 #include <hwbinder/IPCThreadState.h>
31 #include <hwbinder/ProcessState.h>
32 #include <utils/Errors.h>
33 #include <utils/StrongPointer.h>
34 #include <utils/Log.h>
35 
36 
37 using android::base::EqualsIgnoreCase;
38 
39 // libhidl:
40 using android::hardware::configureRpcThreadpool;
41 using android::hardware::joinRpcThreadpool;
42 
43 namespace {
44 
45 android::sp<IEvsEnumerator> pEvs;
46 android::sp<IEvsDisplay> pDisplay;
47 EvsStateControl *pStateController;
48 
sigHandler(int sig)49 void sigHandler(int sig) {
50     LOG(ERROR) << "evs_app is being terminated on receiving a signal " << sig;
51     if (pEvs != nullptr) {
52         // Attempt to clean up the resources
53         pStateController->postCommand({EvsStateControl::Op::EXIT, 0, 0}, true);
54         pStateController->terminateUpdateLoop();
55         pEvs->closeDisplay(pDisplay);
56     }
57 
58     android::hardware::IPCThreadState::self()->stopProcess();
59     exit(EXIT_FAILURE);
60 }
61 
registerSigHandler()62 void registerSigHandler() {
63     struct sigaction sa;
64     sigemptyset(&sa.sa_mask);
65     sa.sa_flags = 0;
66     sa.sa_handler = sigHandler;
67     sigaction(SIGABRT, &sa, nullptr);
68     sigaction(SIGTERM, &sa, nullptr);
69     sigaction(SIGINT,  &sa, nullptr);
70 }
71 
72 } // namespace
73 
74 
75 // Helper to subscribe to VHal notifications
subscribeToVHal(sp<IVehicle> pVnet,sp<IVehicleCallback> listener,VehicleProperty propertyId)76 static bool subscribeToVHal(sp<IVehicle> pVnet,
77                             sp<IVehicleCallback> listener,
78                             VehicleProperty propertyId) {
79     assert(pVnet != nullptr);
80     assert(listener != nullptr);
81 
82     // Register for vehicle state change callbacks we care about
83     // Changes in these values are what will trigger a reconfiguration of the EVS pipeline
84     SubscribeOptions optionsData[] = {
85         {
86             .propId = static_cast<int32_t>(propertyId),
87             .flags  = SubscribeFlags::EVENTS_FROM_CAR
88         },
89     };
90     hidl_vec <SubscribeOptions> options;
91     options.setToExternal(optionsData, arraysize(optionsData));
92     StatusCode status = pVnet->subscribe(listener, options);
93     if (status != StatusCode::OK) {
94         LOG(WARNING) << "VHAL subscription for property " << static_cast<int32_t>(propertyId)
95                      << " failed with code " << static_cast<int32_t>(status);
96         return false;
97     }
98 
99     return true;
100 }
101 
102 
convertStringToFormat(const char * str,android_pixel_format_t * output)103 static bool convertStringToFormat(const char* str, android_pixel_format_t* output) {
104     bool result = true;
105     if (EqualsIgnoreCase(str, "RGBA8888")) {
106         *output = HAL_PIXEL_FORMAT_RGBA_8888;
107     } else if (EqualsIgnoreCase(str, "YV12")) {
108         *output = HAL_PIXEL_FORMAT_YV12;
109     } else if (EqualsIgnoreCase(str, "NV21")) {
110         *output = HAL_PIXEL_FORMAT_YCrCb_420_SP;
111     } else if (EqualsIgnoreCase(str, "YUYV")) {
112         *output = HAL_PIXEL_FORMAT_YCBCR_422_I;
113     } else {
114         result = false;
115     }
116 
117     return result;
118 }
119 
120 
121 // Main entry point
main(int argc,char ** argv)122 int main(int argc, char** argv)
123 {
124     LOG(INFO) << "EVS app starting";
125 
126     // Register a signal handler
127     registerSigHandler();
128 
129     // Set up default behavior, then check for command line options
130     bool useVehicleHal = true;
131     bool printHelp = false;
132     const char* evsServiceName = "default";
133     int displayId = -1;
134     bool useExternalMemory = false;
135     android_pixel_format_t extMemoryFormat = HAL_PIXEL_FORMAT_RGBA_8888;
136     for (int i=1; i< argc; i++) {
137         if (strcmp(argv[i], "--test") == 0) {
138             useVehicleHal = false;
139         } else if (strcmp(argv[i], "--hw") == 0) {
140             evsServiceName = "EvsEnumeratorHw";
141         } else if (strcmp(argv[i], "--mock") == 0) {
142             evsServiceName = "EvsEnumeratorHw-Mock";
143         } else if (strcmp(argv[i], "--help") == 0) {
144             printHelp = true;
145         } else if (strcmp(argv[i], "--display") == 0) {
146             displayId = std::stoi(argv[++i]);
147         } else if (strcmp(argv[i], "--extmem") == 0) {
148             useExternalMemory = true;
149             if (i + 1 >= argc) {
150                 // use RGBA8888 by default
151                 LOG(INFO) << "External buffer format is not set.  "
152                           << "RGBA8888 will be used.";
153             } else {
154                 if (!convertStringToFormat(argv[i + 1], &extMemoryFormat)) {
155                     LOG(WARNING) << "Color format string " << argv[i + 1]
156                                  << " is unknown or not supported.  RGBA8888 will be used.";
157                 } else {
158                     // move the index
159                     ++i;
160                 }
161             }
162         } else {
163             printf("Ignoring unrecognized command line arg '%s'\n", argv[i]);
164             printHelp = true;
165         }
166     }
167     if (printHelp) {
168         printf("Options include:\n");
169         printf("  --test\n\tDo not talk to Vehicle Hal, but simulate 'reverse' instead\n");
170         printf("  --hw\n\tBypass EvsManager by connecting directly to EvsEnumeratorHw\n");
171         printf("  --mock\n\tConnect directly to EvsEnumeratorHw-Mock\n");
172         printf("  --display\n\tSpecify the display to use.  If this is not set, the first"
173                               "display in config.json's list will be used.\n");
174         printf("  --extmem  <format>\n\t"
175                "Application allocates buffers to capture camera frames.  "
176                "Available format strings are (case insensitive):\n");
177         printf("\t\tRGBA8888: 4x8-bit RGBA format.  This is the default format to be used "
178                "when no format is specified.\n");
179         printf("\t\tYV12: YUV420 planar format with a full resolution Y plane "
180                "followed by a V values, with U values last.\n");
181         printf("\t\tNV21: A biplanar format with a full resolution Y plane "
182                "followed by a single chrome plane with weaved V and U values.\n");
183         printf("\t\tYUYV: Packed format with a half horizontal chrome resolution.  "
184                "Known as YUV4:2:2.\n");
185 
186         return EXIT_FAILURE;
187     }
188 
189     // Load our configuration information
190     ConfigManager config;
191     if (!config.initialize("/system/etc/automotive/evs/config.json")) {
192         LOG(ERROR) << "Missing or improper configuration for the EVS application.  Exiting.";
193         return EXIT_FAILURE;
194     }
195 
196     // Set thread pool size to one to avoid concurrent events from the HAL.
197     // This pool will handle the EvsCameraStream callbacks.
198     // Note:  This _will_ run in parallel with the EvsListener run() loop below which
199     // runs the application logic that reacts to the async events.
200     configureRpcThreadpool(1, false /* callerWillJoin */);
201 
202     // Construct our async helper object
203     sp<EvsVehicleListener> pEvsListener = new EvsVehicleListener();
204 
205     // Get the EVS manager service
206     LOG(INFO) << "Acquiring EVS Enumerator";
207     pEvs = IEvsEnumerator::getService(evsServiceName);
208     if (pEvs.get() == nullptr) {
209         LOG(ERROR) << "getService(" << evsServiceName
210                    << ") returned NULL.  Exiting.";
211         return EXIT_FAILURE;
212     }
213 
214     // Request exclusive access to the EVS display
215     LOG(INFO) << "Acquiring EVS Display";
216 
217     // We'll use an available display device.
218     displayId = config.setActiveDisplayId(displayId);
219     if (displayId < 0) {
220         PLOG(ERROR) << "EVS Display is unknown.  Exiting.";
221         return EXIT_FAILURE;
222     }
223 
224     pDisplay = pEvs->openDisplay_1_1(displayId);
225     if (pDisplay.get() == nullptr) {
226         LOG(ERROR) << "EVS Display unavailable.  Exiting.";
227         return EXIT_FAILURE;
228     }
229 
230     config.useExternalMemory(useExternalMemory);
231     config.setExternalMemoryFormat(extMemoryFormat);
232 
233     // Connect to the Vehicle HAL so we can monitor state
234     sp<IVehicle> pVnet;
235     if (useVehicleHal) {
236         LOG(INFO) << "Connecting to Vehicle HAL";
237         pVnet = IVehicle::getService();
238         if (pVnet.get() == nullptr) {
239             LOG(ERROR) << "Vehicle HAL getService returned NULL.  Exiting.";
240             return EXIT_FAILURE;
241         } else {
242             // Register for vehicle state change callbacks we care about
243             // Changes in these values are what will trigger a reconfiguration of the EVS pipeline
244             if (!subscribeToVHal(pVnet, pEvsListener, VehicleProperty::GEAR_SELECTION)) {
245                 LOG(ERROR) << "Without gear notification, we can't support EVS.  Exiting.";
246                 return EXIT_FAILURE;
247             }
248             if (!subscribeToVHal(pVnet, pEvsListener, VehicleProperty::TURN_SIGNAL_STATE)) {
249                 LOG(WARNING) << "Didn't get turn signal notifications, so we'll ignore those.";
250             }
251         }
252     } else {
253         LOG(WARNING) << "Test mode selected, so not talking to Vehicle HAL";
254     }
255 
256     // Configure ourselves for the current vehicle state at startup
257     LOG(INFO) << "Constructing state controller";
258     pStateController = new EvsStateControl(pVnet, pEvs, pDisplay, config);
259     if (!pStateController->startUpdateLoop()) {
260         LOG(ERROR) << "Initial configuration failed.  Exiting.";
261         return EXIT_FAILURE;
262     }
263 
264     // Run forever, reacting to events as necessary
265     LOG(INFO) << "Entering running state";
266     pEvsListener->run(pStateController);
267 
268     // In normal operation, we expect to run forever, but in some error conditions we'll quit.
269     // One known example is if another process preempts our registration for our service name.
270     LOG(ERROR) << "EVS Listener stopped.  Exiting.";
271 
272     return EXIT_SUCCESS;
273 }
274