1 /*
2 * Copyright (C) 2019 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 "HalCamera.h"
18
19 #include "Enumerator.h"
20 #include "VirtualCamera.h"
21
22 #include <android-base/file.h>
23 #include <android-base/logging.h>
24 #include <android-base/strings.h>
25
26 namespace android::automotive::evs::V1_1::implementation {
27
28 // TODO(changyeon):
29 // We need to hook up death monitoring to detect stream death so we can attempt a reconnect
30
31 using ::android::base::StringAppendF;
32 using ::android::base::WriteStringToFd;
33 using ::android::hardware::Return;
34 using ::android::hardware::Void;
35 using ::android::hardware::automotive::evs::V1_1::EvsEventDesc;
36 using ::android::hardware::automotive::evs::V1_1::EvsEventType;
37
~HalCamera()38 HalCamera::~HalCamera() {
39 // Reports the usage statistics before the destruction
40 // EvsUsageStatsReported atom is defined in
41 // frameworks/proto_logging/stats/atoms.proto
42 mUsageStats->writeStats();
43 }
44
makeVirtualCamera()45 sp<VirtualCamera> HalCamera::makeVirtualCamera() {
46 // Create the client camera interface object
47 std::vector<sp<HalCamera>> sourceCameras;
48 sourceCameras.reserve(1);
49 sourceCameras.emplace_back(this);
50 sp<VirtualCamera> client = new VirtualCamera(sourceCameras);
51 if (client == nullptr) {
52 LOG(ERROR) << "Failed to create client camera object";
53 return nullptr;
54 }
55
56 if (!ownVirtualCamera(client)) {
57 LOG(ERROR) << "Failed to own a client camera object";
58 client = nullptr;
59 }
60
61 return client;
62 }
63
ownVirtualCamera(sp<VirtualCamera> virtualCamera)64 bool HalCamera::ownVirtualCamera(sp<VirtualCamera> virtualCamera) {
65 if (virtualCamera == nullptr) {
66 LOG(ERROR) << "Failed to create virtualCamera camera object";
67 return false;
68 }
69
70 // Make sure we have enough buffers available for all our clients
71 if (!changeFramesInFlight(virtualCamera->getAllowedBuffers())) {
72 // Gah! We couldn't get enough buffers, so we can't support this virtualCamera
73 // Null the pointer, dropping our reference, thus destroying the virtualCamera object
74 return false;
75 }
76
77 // Add this virtualCamera to our ownership list via weak pointer
78 mClients.emplace_back(virtualCamera);
79
80 // Update statistics
81 mUsageStats->updateNumClients(mClients.size());
82
83 return true;
84 }
85
disownVirtualCamera(sp<VirtualCamera> virtualCamera)86 void HalCamera::disownVirtualCamera(sp<VirtualCamera> virtualCamera) {
87 // Ignore calls with null pointers
88 if (virtualCamera == nullptr) {
89 LOG(WARNING) << "Ignoring disownVirtualCamera call with null pointer";
90 return;
91 }
92
93 // Remove the virtual camera from our client list
94 const auto clientCount = mClients.size();
95 mClients.remove(virtualCamera);
96 if (clientCount != mClients.size() + 1) {
97 LOG(WARNING) << "Couldn't find camera in our client list to remove it; "
98 << "this client may be removed already.";
99 }
100
101 // Recompute the number of buffers required with the target camera removed from the list
102 if (!changeFramesInFlight(0)) {
103 LOG(ERROR) << "Error when trying to reduce the in flight buffer count";
104 }
105
106 // Update statistics
107 mUsageStats->updateNumClients(mClients.size());
108 }
109
disownVirtualCamera(const VirtualCamera * clientToDisown)110 void HalCamera::disownVirtualCamera(const VirtualCamera* clientToDisown) {
111 // Ignore calls with null pointers
112 if (clientToDisown == nullptr) {
113 LOG(WARNING) << "Ignoring disownVirtualCamera call with null pointer";
114 return;
115 }
116
117 // Remove the virtual camera from our client list
118 const auto clientCount = mClients.size();
119 mClients.remove_if(
120 [&clientToDisown](wp<VirtualCamera>& client) { return client == clientToDisown; });
121 if (clientCount == mClients.size()) {
122 LOG(WARNING) << "Couldn't find camera in our client list to remove it; "
123 << "this client may be removed already.";
124 }
125
126 // Recompute the number of buffers required with the target camera removed from the list
127 if (!changeFramesInFlight(0)) {
128 LOG(ERROR) << "Error when trying to reduce the in flight buffer count";
129 }
130
131 // Update statistics
132 mUsageStats->updateNumClients(mClients.size());
133 }
134
changeFramesInFlight(int delta)135 bool HalCamera::changeFramesInFlight(int delta) {
136 // Walk all our clients and count their currently required frames
137 unsigned bufferCount = 0;
138 for (auto&& client : mClients) {
139 sp<VirtualCamera> virtCam = client.promote();
140 if (virtCam != nullptr) {
141 bufferCount += virtCam->getAllowedBuffers();
142 }
143 }
144
145 // Add the requested delta
146 bufferCount += delta;
147
148 // Never drop below 1 buffer -- even if all client cameras get closed
149 if (bufferCount < 1) {
150 bufferCount = 1;
151 }
152
153 // Ask the hardware for the resulting buffer count
154 Return<EvsResult> result = mHwCamera->setMaxFramesInFlight(bufferCount);
155 bool success = (result.isOk() && result == EvsResult::OK);
156
157 // Update the size of our array of outstanding frame records
158 if (success) {
159 std::vector<FrameRecord> newRecords;
160 newRecords.reserve(bufferCount);
161
162 // Copy and compact the old records that are still active
163 for (const auto& rec : mFrames) {
164 if (rec.refCount > 0) {
165 newRecords.emplace_back(rec);
166 }
167 }
168 if (newRecords.size() > (unsigned)bufferCount) {
169 LOG(WARNING) << "We found more frames in use than requested.";
170 }
171
172 mFrames.swap(newRecords);
173 }
174
175 return success;
176 }
177
changeFramesInFlight(const hidl_vec<BufferDesc_1_1> & buffers,int * delta)178 bool HalCamera::changeFramesInFlight(const hidl_vec<BufferDesc_1_1>& buffers, int* delta) {
179 // Return immediately if a list is empty.
180 if (buffers.size() < 1) {
181 LOG(DEBUG) << "No external buffers to add.";
182 return true;
183 }
184
185 // Walk all our clients and count their currently required frames
186 auto bufferCount = 0;
187 for (auto&& client : mClients) {
188 sp<VirtualCamera> virtCam = client.promote();
189 if (virtCam != nullptr) {
190 bufferCount += virtCam->getAllowedBuffers();
191 }
192 }
193
194 EvsResult status = EvsResult::OK;
195 // Ask the hardware for the resulting buffer count
196 mHwCamera->importExternalBuffers(buffers, [&](auto result, auto added) {
197 status = result;
198 *delta = added;
199 });
200 if (status != EvsResult::OK) {
201 LOG(ERROR) << "Failed to add external capture buffers.";
202 return false;
203 }
204
205 bufferCount += *delta;
206
207 // Update the size of our array of outstanding frame records
208 std::vector<FrameRecord> newRecords;
209 newRecords.reserve(bufferCount);
210
211 // Copy and compact the old records that are still active
212 for (const auto& rec : mFrames) {
213 if (rec.refCount > 0) {
214 newRecords.emplace_back(rec);
215 }
216 }
217
218 if (newRecords.size() > (unsigned)bufferCount) {
219 LOG(WARNING) << "We found more frames in use than requested.";
220 }
221
222 mFrames.swap(newRecords);
223
224 return true;
225 }
226
requestNewFrame(sp<VirtualCamera> client,const int64_t lastTimestamp)227 void HalCamera::requestNewFrame(sp<VirtualCamera> client, const int64_t lastTimestamp) {
228 FrameRequest req;
229 req.client = client;
230 req.timestamp = lastTimestamp;
231
232 std::lock_guard<std::mutex> lock(mFrameMutex);
233 mNextRequests->push_back(req);
234 }
235
clientStreamStarting()236 Return<EvsResult> HalCamera::clientStreamStarting() {
237 {
238 std::lock_guard lock(mFrameMutex);
239 if (mStreamState != STOPPED) {
240 return EvsResult::OK;
241 }
242
243 mStreamState = RUNNING;
244 }
245
246 return mHwCamera->startVideoStream(this);
247 }
248
cancelCaptureRequestFromClientLocked(std::deque<struct FrameRequest> * requests,const VirtualCamera * client)249 void HalCamera::cancelCaptureRequestFromClientLocked(std::deque<struct FrameRequest>* requests,
250 const VirtualCamera* client) {
251 auto it = requests->begin();
252 while (it != requests->end()) {
253 if (it->client == client) {
254 requests->erase(it);
255 return;
256 }
257 ++it;
258 }
259 }
260
clientStreamEnding(const VirtualCamera * client)261 void HalCamera::clientStreamEnding(const VirtualCamera* client) {
262 {
263 std::lock_guard<std::mutex> lock(mFrameMutex);
264 cancelCaptureRequestFromClientLocked(mNextRequests, client);
265 cancelCaptureRequestFromClientLocked(mCurrentRequests, client);
266
267 if (mStreamState != RUNNING) {
268 // We are being stopped or stopped already.
269 return;
270 }
271 }
272
273 // Do we still have a running client?
274 bool stillRunning = false;
275 for (auto&& client : mClients) {
276 sp<VirtualCamera> virtCam = client.promote();
277 if (virtCam != nullptr) {
278 stillRunning |= virtCam->isStreaming();
279 }
280 }
281
282 // If not, then stop the hardware stream
283 if (!stillRunning) {
284 {
285 std::lock_guard lock(mFrameMutex);
286 mStreamState = STOPPING;
287 }
288 mHwCamera->stopVideoStream();
289 }
290 }
291
doneWithFrame(const BufferDesc_1_0 & buffer)292 Return<void> HalCamera::doneWithFrame(const BufferDesc_1_0& buffer) {
293 // Find this frame in our list of outstanding frames
294 unsigned i;
295 for (i = 0; i < mFrames.size(); i++) {
296 if (mFrames[i].frameId == buffer.bufferId) {
297 break;
298 }
299 }
300 if (i == mFrames.size()) {
301 LOG(ERROR) << "We got a frame back with an ID we don't recognize!";
302 } else {
303 // Are there still clients using this buffer?
304 mFrames[i].refCount--;
305 if (mFrames[i].refCount <= 0) {
306 // Since all our clients are done with this buffer, return it to the device layer
307 mHwCamera->doneWithFrame(buffer);
308
309 // Counts a returned buffer
310 mUsageStats->framesReturned();
311 }
312 }
313
314 return Void();
315 }
316
doneWithFrame(const BufferDesc_1_1 & buffer)317 Return<void> HalCamera::doneWithFrame(const BufferDesc_1_1& buffer) {
318 // Find this frame in our list of outstanding frames
319 unsigned i;
320 for (i = 0; i < mFrames.size(); i++) {
321 if (mFrames[i].frameId == buffer.bufferId) {
322 break;
323 }
324 }
325 if (i == mFrames.size()) {
326 LOG(ERROR) << "We got a frame back with an ID we don't recognize!";
327 } else {
328 // Are there still clients using this buffer?
329 mFrames[i].refCount--;
330 if (mFrames[i].refCount <= 0) {
331 // Since all our clients are done with this buffer, return it to the device layer
332 hardware::hidl_vec<BufferDesc_1_1> returnedBuffers;
333 returnedBuffers.resize(1);
334 returnedBuffers[0] = buffer;
335 mHwCamera->doneWithFrame_1_1(returnedBuffers);
336
337 // Counts a returned buffer
338 mUsageStats->framesReturned(returnedBuffers);
339 }
340 }
341
342 return Void();
343 }
344
345 // Methods from ::android::hardware::automotive::evs::V1_0::IEvsCameraStream follow.
deliverFrame(const BufferDesc_1_0 & buffer)346 Return<void> HalCamera::deliverFrame(const BufferDesc_1_0& buffer) {
347 /* Frames are delivered via deliverFrame_1_1 callback for clients that implement
348 * IEvsCameraStream v1.1 interfaces and therefore this method must not be
349 * used.
350 */
351 LOG(INFO) << "A delivered frame from EVS v1.0 HW module is rejected.";
352 mHwCamera->doneWithFrame(buffer);
353
354 // Reports a received and returned buffer
355 mUsageStats->framesReceived();
356 mUsageStats->framesReturned();
357
358 return Void();
359 }
360
361 // Methods from ::android::hardware::automotive::evs::V1_1::IEvsCameraStream follow.
deliverFrame_1_1(const hardware::hidl_vec<BufferDesc_1_1> & buffer)362 Return<void> HalCamera::deliverFrame_1_1(const hardware::hidl_vec<BufferDesc_1_1>& buffer) {
363 LOG(VERBOSE) << "Received a frame";
364 // Frames are being forwarded to v1.1 clients only who requested new frame.
365 const auto timestamp = buffer[0].timestamp;
366 // TODO(b/145750636): For now, we are using a approximately half of 1 seconds / 30 frames = 33ms
367 // but this must be derived from current framerate.
368 constexpr int64_t kThreshold = 16 * 1e+3; // ms
369 unsigned frameDeliveriesV1 = 0;
370 {
371 // Handle frame requests from v1.1 clients
372 std::lock_guard<std::mutex> lock(mFrameMutex);
373 std::swap(mCurrentRequests, mNextRequests);
374 while (!mCurrentRequests->empty()) {
375 auto req = mCurrentRequests->front();
376 mCurrentRequests->pop_front();
377 sp<VirtualCamera> vCam = req.client.promote();
378 if (vCam == nullptr) {
379 // Ignore a client already dead.
380 continue;
381 } else if (timestamp - req.timestamp < kThreshold) {
382 // Skip current frame because it arrives too soon.
383 LOG(DEBUG) << "Skips a frame from " << getId();
384 mNextRequests->push_back(req);
385
386 // Reports a skipped frame
387 mUsageStats->framesSkippedToSync();
388 } else if (vCam != nullptr) {
389 if (!vCam->deliverFrame(buffer[0])) {
390 LOG(WARNING) << getId() << " failed to forward the buffer to " << vCam.get();
391 } else {
392 LOG(ERROR) << getId() << " forwarded the buffer #" << buffer[0].bufferId
393 << " to " << vCam.get() << " from " << this;
394 ++frameDeliveriesV1;
395 }
396 }
397 }
398 }
399
400 // Reports the number of received buffers
401 mUsageStats->framesReceived(buffer);
402
403 // Frames are being forwarded to active v1.0 clients and v1.1 clients if we
404 // failed to create a timeline.
405 unsigned frameDeliveries = 0;
406 for (auto&& client : mClients) {
407 sp<VirtualCamera> vCam = client.promote();
408 if (vCam == nullptr || vCam->getVersion() > 0) {
409 continue;
410 }
411
412 if (vCam->deliverFrame(buffer[0])) {
413 ++frameDeliveries;
414 }
415 }
416
417 frameDeliveries += frameDeliveriesV1;
418 if (frameDeliveries < 1) {
419 // If none of our clients could accept the frame, then return it
420 // right away.
421 LOG(INFO) << "Trivially rejecting frame (" << buffer[0].bufferId << ") from " << getId()
422 << " with no acceptance";
423 mHwCamera->doneWithFrame_1_1(buffer);
424
425 // Reports a returned buffer
426 mUsageStats->framesReturned(buffer);
427 } else {
428 // Add an entry for this frame in our tracking list.
429 unsigned i;
430 for (i = 0; i < mFrames.size(); ++i) {
431 if (mFrames[i].refCount == 0) {
432 break;
433 }
434 }
435
436 if (i == mFrames.size()) {
437 mFrames.emplace_back(buffer[0].bufferId);
438 } else {
439 mFrames[i].frameId = buffer[0].bufferId;
440 }
441 mFrames[i].refCount = frameDeliveries;
442 }
443
444 return Void();
445 }
446
notify(const EvsEventDesc & event)447 Return<void> HalCamera::notify(const EvsEventDesc& event) {
448 LOG(DEBUG) << "Received an event id: " << static_cast<int32_t>(event.aType);
449 if (event.aType == EvsEventType::STREAM_STOPPED) {
450 std::lock_guard lock(mFrameMutex);
451 // This event happens only when there is no more active client.
452 if (mStreamState != STOPPING) {
453 LOG(WARNING) << "Stream stopped unexpectedly";
454 }
455
456 mStreamState = STOPPED;
457 }
458
459 // Forward all other events to the clients
460 for (auto&& client : mClients) {
461 sp<VirtualCamera> vCam = client.promote();
462 if (vCam != nullptr) {
463 if (!vCam->notify(event)) {
464 LOG(INFO) << "Failed to forward an event";
465 }
466 }
467 }
468
469 return Void();
470 }
471
setMaster(sp<VirtualCamera> virtualCamera)472 Return<EvsResult> HalCamera::setMaster(sp<VirtualCamera> virtualCamera) {
473 if (mPrimaryClient == nullptr) {
474 LOG(DEBUG) << __FUNCTION__ << ": " << virtualCamera.get() << " becomes a primary client.";
475 mPrimaryClient = virtualCamera;
476 return EvsResult::OK;
477 } else {
478 LOG(INFO) << "This camera already has a primary client.";
479 return EvsResult::OWNERSHIP_LOST;
480 }
481 }
482
forceMaster(sp<VirtualCamera> virtualCamera)483 Return<EvsResult> HalCamera::forceMaster(sp<VirtualCamera> virtualCamera) {
484 sp<VirtualCamera> prevPrimary = mPrimaryClient.promote();
485 if (prevPrimary == virtualCamera) {
486 LOG(DEBUG) << "Client " << virtualCamera.get() << " is already a primary client";
487 } else {
488 mPrimaryClient = virtualCamera;
489 if (prevPrimary != nullptr) {
490 LOG(INFO) << "High priority client " << virtualCamera.get()
491 << " steals a primary role from " << prevPrimary.get();
492
493 /* Notify a previous primary client the loss of a primary role */
494 EvsEventDesc event;
495 event.aType = EvsEventType::MASTER_RELEASED;
496 if (!prevPrimary->notify(event)) {
497 LOG(ERROR) << "Fail to deliver a primary role lost notification";
498 }
499 }
500 }
501
502 return EvsResult::OK;
503 }
504
unsetMaster(const VirtualCamera * virtualCamera)505 Return<EvsResult> HalCamera::unsetMaster(const VirtualCamera* virtualCamera) {
506 if (mPrimaryClient.promote() != virtualCamera) {
507 return EvsResult::INVALID_ARG;
508 } else {
509 LOG(INFO) << "Unset a primary camera client";
510 mPrimaryClient = nullptr;
511
512 /* Notify other clients that a primary role becomes available. */
513 EvsEventDesc event;
514 event.aType = EvsEventType::MASTER_RELEASED;
515 auto cbResult = this->notify(event);
516 if (!cbResult.isOk()) {
517 LOG(ERROR) << "Fail to deliver a parameter change notification";
518 }
519
520 return EvsResult::OK;
521 }
522 }
523
setParameter(sp<VirtualCamera> virtualCamera,CameraParam id,int32_t * value)524 Return<EvsResult> HalCamera::setParameter(sp<VirtualCamera> virtualCamera, CameraParam id,
525 int32_t* value) {
526 EvsResult result = EvsResult::INVALID_ARG;
527 if (virtualCamera == mPrimaryClient.promote()) {
528 mHwCamera->setIntParameter(id, *value, [&result, value](auto status, auto readValue) {
529 result = status;
530 *value = readValue[0];
531 });
532
533 if (result == EvsResult::OK) {
534 /* Notify a parameter change */
535 EvsEventDesc event;
536 event.aType = EvsEventType::PARAMETER_CHANGED;
537 event.payload[0] = static_cast<uint32_t>(id);
538 event.payload[1] = static_cast<uint32_t>(*value);
539 auto cbResult = this->notify(event);
540 if (!cbResult.isOk()) {
541 LOG(ERROR) << "Fail to deliver a parameter change notification";
542 }
543 }
544 } else {
545 LOG(WARNING) << "A parameter change request from the non-primary client is declined.";
546
547 /* Read a current value of a requested camera parameter */
548 getParameter(id, value);
549 }
550
551 return result;
552 }
553
getParameter(CameraParam id,int32_t * value)554 Return<EvsResult> HalCamera::getParameter(CameraParam id, int32_t* value) {
555 EvsResult result = EvsResult::OK;
556 mHwCamera->getIntParameter(id, [&result, value](auto status, auto readValue) {
557 result = status;
558 if (result == EvsResult::OK) {
559 *value = readValue[0];
560 }
561 });
562
563 return result;
564 }
565
getStats() const566 CameraUsageStatsRecord HalCamera::getStats() const {
567 return mUsageStats->snapshot();
568 }
569
getStreamConfiguration() const570 Stream HalCamera::getStreamConfiguration() const {
571 return mStreamConfig;
572 }
573
toString(const char * indent) const574 std::string HalCamera::toString(const char* indent) const {
575 std::string buffer;
576
577 const auto timeElapsedMs = android::uptimeMillis() - mTimeCreatedMs;
578 StringAppendF(&buffer, "%sCreated: @%" PRId64 " (elapsed %" PRId64 " ms)\n", indent,
579 mTimeCreatedMs, timeElapsedMs);
580
581 std::string double_indent(indent);
582 double_indent += indent;
583 buffer += CameraUsageStats::toString(getStats(), double_indent.c_str());
584 for (auto&& client : mClients) {
585 auto handle = client.promote();
586 if (!handle) {
587 continue;
588 }
589
590 StringAppendF(&buffer, "%sClient %p\n", indent, handle.get());
591 buffer += handle->toString(double_indent.c_str());
592 }
593
594 StringAppendF(&buffer, "%sPrimary client: %p\n", indent, mPrimaryClient.promote().get());
595
596 buffer += HalCamera::toString(mStreamConfig, indent);
597
598 return buffer;
599 }
600
toString(Stream configuration,const char * indent)601 std::string HalCamera::toString(Stream configuration, const char* indent) {
602 std::string streamInfo;
603 std::string double_indent(indent);
604 double_indent += indent;
605 StringAppendF(&streamInfo,
606 "%sActive Stream Configuration\n"
607 "%sid: %d\n"
608 "%swidth: %d\n"
609 "%sheight: %d\n"
610 "%sformat: 0x%X\n"
611 "%susage: 0x%" PRIx64 "\n"
612 "%srotation: 0x%X\n\n",
613 indent, double_indent.c_str(), configuration.id, double_indent.c_str(),
614 configuration.width, double_indent.c_str(), configuration.height,
615 double_indent.c_str(), configuration.format, double_indent.c_str(),
616 configuration.usage, double_indent.c_str(), configuration.rotation);
617
618 return streamInfo;
619 }
620
621 } // namespace android::automotive::evs::V1_1::implementation
622