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 #define LOG_TAG "GCH_HidlCameraDeviceSession"
18 //#define LOG_NDEBUG 0
19 #include <log/log.h>
20 
21 #include <cutils/properties.h>
22 
23 #include "hidl_camera_device_session.h"
24 #include "hidl_profiler.h"
25 #include "hidl_utils.h"
26 
27 namespace android {
28 namespace hardware {
29 namespace camera {
30 namespace device {
31 namespace V3_5 {
32 namespace implementation {
33 
34 namespace hidl_utils = ::android::hardware::camera::implementation::hidl_utils;
35 namespace hidl_profiler =
36     ::android::hardware::camera::implementation::hidl_profiler;
37 
38 using ::android::hardware::camera::device::V3_2::NotifyMsg;
39 using ::android::hardware::camera::device::V3_2::StreamBuffer;
40 using ::android::hardware::camera::device::V3_4::CaptureResult;
41 using ::android::hardware::camera::device::V3_4::HalStreamConfiguration;
42 using ::android::hardware::camera::device::V3_5::BufferRequestStatus;
43 using ::android::hardware::camera::device::V3_5::StreamBufferRet;
44 using ::android::hardware::thermal::V1_0::ThermalStatus;
45 using ::android::hardware::thermal::V1_0::ThermalStatusCode;
46 using ::android::hardware::thermal::V2_0::Temperature;
47 using ::android::hardware::thermal::V2_0::TemperatureType;
48 
Create(const sp<V3_2::ICameraDeviceCallback> & callback,std::unique_ptr<google_camera_hal::CameraDeviceSession> device_session)49 std::unique_ptr<HidlCameraDeviceSession> HidlCameraDeviceSession::Create(
50     const sp<V3_2::ICameraDeviceCallback>& callback,
51     std::unique_ptr<google_camera_hal::CameraDeviceSession> device_session) {
52   auto session =
53       std::unique_ptr<HidlCameraDeviceSession>(new HidlCameraDeviceSession());
54   if (session == nullptr) {
55     ALOGE("%s: Cannot create a HidlCameraDeviceSession.", __FUNCTION__);
56     return nullptr;
57   }
58 
59   status_t res = session->Initialize(callback, std::move(device_session));
60   if (res != OK) {
61     ALOGE("%s: Initializing HidlCameraDeviceSession failed: %s(%d)",
62           __FUNCTION__, strerror(-res), res);
63     return nullptr;
64   }
65 
66   return session;
67 }
68 
~HidlCameraDeviceSession()69 HidlCameraDeviceSession::~HidlCameraDeviceSession() {
70   close();
71 }
72 
ProcessCaptureResult(std::unique_ptr<google_camera_hal::CaptureResult> hal_result)73 void HidlCameraDeviceSession::ProcessCaptureResult(
74     std::unique_ptr<google_camera_hal::CaptureResult> hal_result) {
75   std::shared_lock lock(hidl_device_callback_lock_);
76   if (hidl_device_callback_ == nullptr) {
77     ALOGE("%s: hidl_device_callback_ is nullptr", __FUNCTION__);
78     return;
79   }
80 
81   {
82     std::lock_guard<std::mutex> pending_lock(pending_first_frame_buffers_mutex_);
83     if (!hal_result->output_buffers.empty() &&
84         num_pending_first_frame_buffers_ > 0) {
85       num_pending_first_frame_buffers_ -= hal_result->output_buffers.size();
86       if (num_pending_first_frame_buffers_ == 0) {
87         hidl_profiler::OnFirstFrameResult();
88       }
89     }
90   }
91 
92   hidl_vec<CaptureResult> hidl_results(1);
93   status_t res = hidl_utils::ConvertToHidlCaptureResult(
94       result_metadata_queue_.get(), std::move(hal_result), &hidl_results[0]);
95   if (res != OK) {
96     ALOGE("%s: Converting to HIDL result failed: %s(%d)", __FUNCTION__,
97           strerror(-res), res);
98     return;
99   }
100 
101   auto hidl_res = hidl_device_callback_->processCaptureResult_3_4(hidl_results);
102   if (!hidl_res.isOk()) {
103     ALOGE("%s: processCaptureResult transaction failed: %s.", __FUNCTION__,
104           hidl_res.description().c_str());
105     return;
106   }
107 }
108 
NotifyHalMessage(const google_camera_hal::NotifyMessage & hal_message)109 void HidlCameraDeviceSession::NotifyHalMessage(
110     const google_camera_hal::NotifyMessage& hal_message) {
111   std::shared_lock lock(hidl_device_callback_lock_);
112   if (hidl_device_callback_ == nullptr) {
113     ALOGE("%s: hidl_device_callback_ is nullptr", __FUNCTION__);
114     return;
115   }
116 
117   hidl_vec<NotifyMsg> hidl_messages(1);
118   status_t res =
119       hidl_utils::ConverToHidlNotifyMessage(hal_message, &hidl_messages[0]);
120   if (res != OK) {
121     ALOGE("%s: Converting to HIDL message failed: %s(%d)", __FUNCTION__,
122           strerror(-res), res);
123     return;
124   }
125 
126   auto hidl_res = hidl_device_callback_->notify(hidl_messages);
127   if (!hidl_res.isOk()) {
128     ALOGE("%s: notify transaction failed: %s.", __FUNCTION__,
129           hidl_res.description().c_str());
130     return;
131   }
132 }
133 
134 google_camera_hal::BufferRequestStatus
RequestStreamBuffers(const std::vector<google_camera_hal::BufferRequest> & hal_buffer_requests,std::vector<google_camera_hal::BufferReturn> * hal_buffer_returns)135 HidlCameraDeviceSession::RequestStreamBuffers(
136     const std::vector<google_camera_hal::BufferRequest>& hal_buffer_requests,
137     std::vector<google_camera_hal::BufferReturn>* hal_buffer_returns) {
138   std::shared_lock lock(hidl_device_callback_lock_);
139   if (hidl_device_callback_ == nullptr) {
140     ALOGE("%s: hidl_device_callback_ is nullptr", __FUNCTION__);
141     return google_camera_hal::BufferRequestStatus::kFailedUnknown;
142   }
143 
144   if (hal_buffer_returns == nullptr) {
145     ALOGE("%s: hal_buffer_returns is nullptr", __FUNCTION__);
146     return google_camera_hal::BufferRequestStatus::kFailedUnknown;
147   }
148 
149   hidl_vec<BufferRequest> hidl_buffer_requests;
150   status_t res = hidl_utils::ConvertToHidlBufferRequest(hal_buffer_requests,
151                                                         &hidl_buffer_requests);
152   if (res != OK) {
153     ALOGE("%s: Converting to Hidl buffer request failed: %s(%d)", __FUNCTION__,
154           strerror(-res), res);
155     return google_camera_hal::BufferRequestStatus::kFailedUnknown;
156   }
157 
158   BufferRequestStatus hidl_status;
159   hidl_vec<StreamBufferRet> stream_buffer_returns;
160   auto cb_status = hidl_device_callback_->requestStreamBuffers(
161       hidl_buffer_requests, [&hidl_status, &stream_buffer_returns](
162                                 BufferRequestStatus status_ret,
163                                 const hidl_vec<StreamBufferRet>& buffer_ret) {
164         hidl_status = status_ret;
165         stream_buffer_returns = std::move(buffer_ret);
166       });
167   if (!cb_status.isOk()) {
168     ALOGE("%s: Transaction request stream buffers error: %s", __FUNCTION__,
169           cb_status.description().c_str());
170     return google_camera_hal::BufferRequestStatus::kFailedUnknown;
171   }
172 
173   google_camera_hal::BufferRequestStatus hal_buffer_request_status;
174   res = hidl_utils::ConvertToHalBufferRequestStatus(hidl_status,
175                                                     &hal_buffer_request_status);
176   if (res != OK) {
177     ALOGE("%s: Converting to Hal buffer request status failed: %s(%d)",
178           __FUNCTION__, strerror(-res), res);
179     return google_camera_hal::BufferRequestStatus::kFailedUnknown;
180   }
181 
182   hal_buffer_returns->clear();
183   // Converting HIDL stream buffer returns to HAL stream buffer returns.
184   for (auto& stream_buffer_return : stream_buffer_returns) {
185     google_camera_hal::BufferReturn hal_buffer_return;
186     res = hidl_utils::ConvertToHalBufferReturnStatus(stream_buffer_return,
187                                                      &hal_buffer_return);
188     if (res != OK) {
189       ALOGE("%s: Converting to Hal buffer return status failed: %s(%d)",
190             __FUNCTION__, strerror(-res), res);
191       return google_camera_hal::BufferRequestStatus::kFailedUnknown;
192     }
193 
194     if (stream_buffer_return.val.getDiscriminator() ==
195         StreamBuffersVal::hidl_discriminator::buffers) {
196       const hidl_vec<StreamBuffer>& hidl_buffers =
197           stream_buffer_return.val.buffers();
198       for (auto& hidl_buffer : hidl_buffers) {
199         google_camera_hal::StreamBuffer hal_buffer = {};
200         hidl_utils::ConvertToHalStreamBuffer(hidl_buffer, &hal_buffer);
201         if (res != OK) {
202           ALOGE("%s: Converting to Hal stream buffer failed: %s(%d)",
203                 __FUNCTION__, strerror(-res), res);
204           return google_camera_hal::BufferRequestStatus::kFailedUnknown;
205         }
206 
207         if (hidl_buffer.acquireFence.getNativeHandle() != nullptr) {
208           hal_buffer.acquire_fence =
209               native_handle_clone(hidl_buffer.acquireFence.getNativeHandle());
210           if (hal_buffer.acquire_fence == nullptr) {
211             ALOGE("%s: Cloning Hal stream buffer acquire fence failed",
212                   __FUNCTION__);
213           }
214         }
215 
216         hal_buffer.release_fence = nullptr;
217         // If buffer handle is not null, we need to import buffer handle and
218         // return to the caller.
219         if (hidl_buffer.buffer.getNativeHandle() != nullptr) {
220           if (buffer_mapper_v4_ != nullptr) {
221             hal_buffer.buffer = ImportBufferHandle<
222                 android::hardware::graphics::mapper::V4_0::IMapper,
223                 android::hardware::graphics::mapper::V4_0::Error>(
224                 buffer_mapper_v4_, hidl_buffer.buffer);
225           } else if (buffer_mapper_v3_ != nullptr) {
226             hal_buffer.buffer = ImportBufferHandle<
227                 android::hardware::graphics::mapper::V3_0::IMapper,
228                 android::hardware::graphics::mapper::V3_0::Error>(
229                 buffer_mapper_v3_, hidl_buffer.buffer);
230           } else {
231             hal_buffer.buffer = ImportBufferHandle<
232                 android::hardware::graphics::mapper::V2_0::IMapper,
233                 android::hardware::graphics::mapper::V2_0::Error>(
234                 buffer_mapper_v2_, hidl_buffer.buffer);
235           }
236         }
237 
238         hal_buffer_return.val.buffers.push_back(hal_buffer);
239       }
240     }
241 
242     hal_buffer_returns->push_back(hal_buffer_return);
243   }
244 
245   return hal_buffer_request_status;
246 }
247 
248 template <class T, class U>
ImportBufferHandle(const sp<T> buffer_mapper_,const hidl_handle & buffer_hidl_handle)249 buffer_handle_t HidlCameraDeviceSession::ImportBufferHandle(
250     const sp<T> buffer_mapper_, const hidl_handle& buffer_hidl_handle) {
251   U mapper_error;
252   buffer_handle_t imported_buffer_handle;
253 
254   auto hidl_res = buffer_mapper_->importBuffer(
255       buffer_hidl_handle, [&](const auto& error, const auto& buffer_handle) {
256         mapper_error = error;
257         imported_buffer_handle = static_cast<buffer_handle_t>(buffer_handle);
258       });
259   if (!hidl_res.isOk() || mapper_error != U::NONE) {
260     ALOGE("%s: Importing buffer failed: %s, mapper error %u", __FUNCTION__,
261           hidl_res.description().c_str(), mapper_error);
262     return nullptr;
263   }
264 
265   return imported_buffer_handle;
266 }
267 
ReturnStreamBuffers(const std::vector<google_camera_hal::StreamBuffer> & return_hal_buffers)268 void HidlCameraDeviceSession::ReturnStreamBuffers(
269     const std::vector<google_camera_hal::StreamBuffer>& return_hal_buffers) {
270   std::shared_lock lock(hidl_device_callback_lock_);
271   if (hidl_device_callback_ == nullptr) {
272     ALOGE("%s: hidl_device_callback_ is nullptr", __FUNCTION__);
273     return;
274   }
275 
276   status_t res = OK;
277   hidl_vec<StreamBuffer> hidl_return_buffers;
278   hidl_return_buffers.resize(return_hal_buffers.size());
279   for (uint32_t i = 0; i < return_hal_buffers.size(); i++) {
280     res = hidl_utils::ConvertToHidlStreamBuffer(return_hal_buffers[i],
281                                                 &hidl_return_buffers[i]);
282     if (res != OK) {
283       ALOGE("%s: Converting to Hidl stream buffer failed: %s(%d)", __FUNCTION__,
284             strerror(-res), res);
285       return;
286     }
287   }
288 
289   hidl_device_callback_->returnStreamBuffers(hidl_return_buffers);
290 }
291 
InitializeBufferMapper()292 status_t HidlCameraDeviceSession::InitializeBufferMapper() {
293   buffer_mapper_v4_ =
294       android::hardware::graphics::mapper::V4_0::IMapper::getService();
295   if (buffer_mapper_v4_ != nullptr) {
296     return OK;
297   }
298 
299   buffer_mapper_v3_ =
300       android::hardware::graphics::mapper::V3_0::IMapper::getService();
301   if (buffer_mapper_v3_ != nullptr) {
302     return OK;
303   }
304 
305   buffer_mapper_v2_ =
306       android::hardware::graphics::mapper::V2_0::IMapper::getService();
307   if (buffer_mapper_v2_ != nullptr) {
308     return OK;
309   }
310 
311   ALOGE("%s: Getting buffer mapper failed.", __FUNCTION__);
312   return UNKNOWN_ERROR;
313 }
314 
Initialize(const sp<V3_2::ICameraDeviceCallback> & callback,std::unique_ptr<google_camera_hal::CameraDeviceSession> device_session)315 status_t HidlCameraDeviceSession::Initialize(
316     const sp<V3_2::ICameraDeviceCallback>& callback,
317     std::unique_ptr<google_camera_hal::CameraDeviceSession> device_session) {
318   if (device_session == nullptr) {
319     ALOGE("%s: device_session is nullptr.", __FUNCTION__);
320     return BAD_VALUE;
321   }
322 
323   status_t res = CreateMetadataQueue(&request_metadata_queue_,
324                                      kRequestMetadataQueueSizeBytes,
325                                      "ro.vendor.camera.req.fmq.size");
326   if (res != OK) {
327     ALOGE("%s: Creating request metadata queue failed: %s(%d)", __FUNCTION__,
328           strerror(-res), res);
329     return res;
330   }
331 
332   res = CreateMetadataQueue(&result_metadata_queue_,
333                             kResultMetadataQueueSizeBytes,
334                             "ro.vendor.camera.res.fmq.size");
335   if (res != OK) {
336     ALOGE("%s: Creating result metadata queue failed: %s(%d)", __FUNCTION__,
337           strerror(-res), res);
338     return res;
339   }
340 
341   // Cast V3.2 callback to V3.5
342   auto cast_res = ICameraDeviceCallback::castFrom(callback);
343   if (!cast_res.isOk()) {
344     ALOGE("%s: Cannot convert to V3.5 device callback.", __FUNCTION__);
345     return UNKNOWN_ERROR;
346   }
347 
348   // Initialize buffer mapper
349   res = InitializeBufferMapper();
350   if (res != OK) {
351     ALOGE("%s: Initialize buffer mapper failed: %s(%d)", __FUNCTION__,
352           strerror(-res), res);
353     return res;
354   }
355 
356   thermal_ = android::hardware::thermal::V2_0::IThermal::getService();
357   if (thermal_ == nullptr) {
358     ALOGE("%s: Getting thermal failed.", __FUNCTION__);
359     // Continue without getting thermal information.
360   }
361 
362   hidl_device_callback_ = cast_res;
363   device_session_ = std::move(device_session);
364 
365   SetSessionCallbacks();
366   return OK;
367 }
368 
SetSessionCallbacks()369 void HidlCameraDeviceSession::SetSessionCallbacks() {
370   google_camera_hal::CameraDeviceSessionCallback session_callback = {
371       .process_capture_result = google_camera_hal::ProcessCaptureResultFunc(
372           [this](std::unique_ptr<google_camera_hal::CaptureResult> result) {
373             ProcessCaptureResult(std::move(result));
374           }),
375       .notify = google_camera_hal::NotifyFunc(
376           [this](const google_camera_hal::NotifyMessage& message) {
377             NotifyHalMessage(message);
378           }),
379       .request_stream_buffers = google_camera_hal::RequestStreamBuffersFunc(
380           [this](
381               const std::vector<google_camera_hal::BufferRequest>&
382                   hal_buffer_requests,
383               std::vector<google_camera_hal::BufferReturn>* hal_buffer_returns) {
384             return RequestStreamBuffers(hal_buffer_requests, hal_buffer_returns);
385           }),
386       .return_stream_buffers = google_camera_hal::ReturnStreamBuffersFunc(
387           [this](const std::vector<google_camera_hal::StreamBuffer>&
388                      return_hal_buffers) {
389             ReturnStreamBuffers(return_hal_buffers);
390           }),
391   };
392 
393   google_camera_hal::ThermalCallback thermal_callback = {
394       .register_thermal_changed_callback =
395           google_camera_hal::RegisterThermalChangedCallbackFunc(
396               [this](google_camera_hal::NotifyThrottlingFunc notify_throttling,
397                      bool filter_type, google_camera_hal::TemperatureType type) {
398                 return RegisterThermalChangedCallback(notify_throttling,
399                                                       filter_type, type);
400               }),
401       .unregister_thermal_changed_callback =
402           google_camera_hal::UnregisterThermalChangedCallbackFunc(
403               [this]() { UnregisterThermalChangedCallback(); }),
404   };
405 
406   device_session_->SetSessionCallback(session_callback, thermal_callback);
407 }
408 
RegisterThermalChangedCallback(google_camera_hal::NotifyThrottlingFunc notify_throttling,bool filter_type,google_camera_hal::TemperatureType type)409 status_t HidlCameraDeviceSession::RegisterThermalChangedCallback(
410     google_camera_hal::NotifyThrottlingFunc notify_throttling, bool filter_type,
411     google_camera_hal::TemperatureType type) {
412   std::lock_guard<std::mutex> lock(hidl_thermal_mutex_);
413   if (thermal_ == nullptr) {
414     ALOGE("%s: thermal was not initialized.", __FUNCTION__);
415     return NO_INIT;
416   }
417 
418   if (thermal_changed_callback_ != nullptr) {
419     ALOGE("%s: thermal changed callback is already registered.", __FUNCTION__);
420     return ALREADY_EXISTS;
421   }
422 
423   TemperatureType hidl_type;
424   status_t res =
425       hidl_thermal_utils::ConvertToHidlTemperatureType(type, &hidl_type);
426   if (res != OK) {
427     ALOGE("%s: Converting to HIDL type failed: %s(%d)", __FUNCTION__,
428           strerror(-res), res);
429     return res;
430   }
431 
432   std::unique_ptr<hidl_thermal_utils::HidlThermalChangedCallback> callback =
433       hidl_thermal_utils::HidlThermalChangedCallback::Create(notify_throttling);
434   thermal_changed_callback_ = callback.release();
435   ThermalStatus thermal_status;
436   auto hidl_res = thermal_->registerThermalChangedCallback(
437       thermal_changed_callback_, filter_type, hidl_type,
438       [&](ThermalStatus status) { thermal_status = status; });
439   if (!hidl_res.isOk() || thermal_status.code != ThermalStatusCode::SUCCESS) {
440     thermal_changed_callback_ = nullptr;
441     return UNKNOWN_ERROR;
442   }
443 
444   return OK;
445 }
446 
UnregisterThermalChangedCallback()447 void HidlCameraDeviceSession::UnregisterThermalChangedCallback() {
448   std::lock_guard<std::mutex> lock(hidl_thermal_mutex_);
449   if (thermal_changed_callback_ == nullptr) {
450     // no-op if no thermal changed callback is registered.
451     return;
452   }
453 
454   if (thermal_ == nullptr) {
455     ALOGE("%s: thermal was not initialized.", __FUNCTION__);
456     return;
457   }
458 
459   ThermalStatus thermal_status;
460   auto hidl_res = thermal_->unregisterThermalChangedCallback(
461       thermal_changed_callback_,
462       [&](ThermalStatus status) { thermal_status = status; });
463   if (!hidl_res.isOk() || thermal_status.code != ThermalStatusCode::SUCCESS) {
464     ALOGW("%s: Unregstering thermal callback failed: %s", __FUNCTION__,
465           thermal_status.debugMessage.c_str());
466   }
467 
468   thermal_changed_callback_ = nullptr;
469 }
470 
CreateMetadataQueue(std::unique_ptr<MetadataQueue> * metadata_queue,uint32_t default_size_bytes,const char * override_size_property)471 status_t HidlCameraDeviceSession::CreateMetadataQueue(
472     std::unique_ptr<MetadataQueue>* metadata_queue, uint32_t default_size_bytes,
473     const char* override_size_property) {
474   if (metadata_queue == nullptr) {
475     ALOGE("%s: metadata_queue is nullptr", __FUNCTION__);
476     return BAD_VALUE;
477   }
478 
479   int32_t size = default_size_bytes;
480   if (override_size_property != nullptr) {
481     // Try to read the override size from the system property.
482     size = property_get_int32(override_size_property, default_size_bytes);
483     ALOGV("%s: request metadata queue size overridden to %d", __FUNCTION__,
484           size);
485   }
486 
487   *metadata_queue = std::make_unique<MetadataQueue>(
488       static_cast<size_t>(size), /*configureEventFlagWord=*/false);
489   if (!(*metadata_queue)->isValid()) {
490     ALOGE("%s: Creating metadata queue (size %d) failed.", __FUNCTION__, size);
491     return NO_INIT;
492   }
493 
494   return OK;
495 }
496 
constructDefaultRequestSettings(RequestTemplate type,ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb)497 Return<void> HidlCameraDeviceSession::constructDefaultRequestSettings(
498     RequestTemplate type,
499     ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
500   V3_2::CameraMetadata hidl_metadata;
501 
502   if (device_session_ == nullptr) {
503     _hidl_cb(Status::INTERNAL_ERROR, hidl_metadata);
504     return Void();
505   }
506 
507   google_camera_hal::RequestTemplate hal_type;
508   status_t res = hidl_utils::ConvertToHalTemplateType(type, &hal_type);
509   if (res != OK) {
510     _hidl_cb(Status::ILLEGAL_ARGUMENT, hidl_metadata);
511     return Void();
512   }
513 
514   std::unique_ptr<google_camera_hal::HalCameraMetadata> settings = nullptr;
515   res = device_session_->ConstructDefaultRequestSettings(hal_type, &settings);
516   if (res != OK) {
517     _hidl_cb(hidl_utils::ConvertToHidlStatus(res), hidl_metadata);
518     return Void();
519   }
520 
521   uint32_t metadata_size = settings->GetCameraMetadataSize();
522   hidl_metadata.setToExternal((uint8_t*)settings->ReleaseCameraMetadata(),
523                               metadata_size, /*shouldOwn=*/true);
524   _hidl_cb(Status::OK, hidl_metadata);
525 
526   return Void();
527 }
528 
configureStreams_3_5(const StreamConfiguration & requestedConfiguration,ICameraDeviceSession::configureStreams_3_5_cb _hidl_cb)529 Return<void> HidlCameraDeviceSession::configureStreams_3_5(
530     const StreamConfiguration& requestedConfiguration,
531     ICameraDeviceSession::configureStreams_3_5_cb _hidl_cb) {
532   HalStreamConfiguration hidl_hal_configs;
533   if (device_session_ == nullptr) {
534     _hidl_cb(Status::ILLEGAL_ARGUMENT, hidl_hal_configs);
535     return Void();
536   }
537 
538   auto profiler_item = hidl_profiler::OnCameraStreamConfigure();
539   first_frame_requested_ = false;
540   num_pending_first_frame_buffers_ = 0;
541 
542   google_camera_hal::StreamConfiguration hal_stream_config;
543   status_t res = hidl_utils::ConverToHalStreamConfig(requestedConfiguration,
544                                                      &hal_stream_config);
545   if (res != OK) {
546     _hidl_cb(Status::ILLEGAL_ARGUMENT, hidl_hal_configs);
547     return Void();
548   }
549 
550   std::vector<google_camera_hal::HalStream> hal_configured_streams;
551   res = device_session_->ConfigureStreams(hal_stream_config,
552                                           &hal_configured_streams);
553   if (res != OK) {
554     ALOGE("%s: Configuring streams failed: %s(%d)", __FUNCTION__,
555           strerror(-res), res);
556     _hidl_cb(hidl_utils::ConvertToHidlStatus(res), hidl_hal_configs);
557     return Void();
558   }
559 
560   res = hidl_utils::ConvertToHidlHalStreamConfig(hal_configured_streams,
561                                                  &hidl_hal_configs);
562   _hidl_cb(hidl_utils::ConvertToHidlStatus(res), hidl_hal_configs);
563 
564   return Void();
565 }
566 
getCaptureRequestMetadataQueue(ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb)567 Return<void> HidlCameraDeviceSession::getCaptureRequestMetadataQueue(
568     ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
569   _hidl_cb(*request_metadata_queue_->getDesc());
570   return Void();
571 }
572 
getCaptureResultMetadataQueue(ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb)573 Return<void> HidlCameraDeviceSession::getCaptureResultMetadataQueue(
574     ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
575   _hidl_cb(*result_metadata_queue_->getDesc());
576   return Void();
577 }
578 
processCaptureRequest_3_4(const hidl_vec<CaptureRequest> & requests,const hidl_vec<BufferCache> & cachesToRemove,processCaptureRequest_3_4_cb _hidl_cb)579 Return<void> HidlCameraDeviceSession::processCaptureRequest_3_4(
580     const hidl_vec<CaptureRequest>& requests,
581     const hidl_vec<BufferCache>& cachesToRemove,
582     processCaptureRequest_3_4_cb _hidl_cb) {
583   if (device_session_ == nullptr) {
584     _hidl_cb(Status::ILLEGAL_ARGUMENT, 0);
585     return Void();
586   }
587 
588   if (!first_frame_requested_) {
589     first_frame_requested_ = true;
590     num_pending_first_frame_buffers_ = requests[0].v3_2.outputBuffers.size();
591     hidl_profiler::OnFirstFrameRequest();
592   }
593 
594   std::vector<google_camera_hal::BufferCache> hal_buffer_caches;
595 
596   status_t res =
597       hidl_utils::ConvertToHalBufferCaches(cachesToRemove, &hal_buffer_caches);
598   if (res != OK) {
599     _hidl_cb(Status::ILLEGAL_ARGUMENT, 0);
600     return Void();
601   }
602 
603   device_session_->RemoveBufferCache(hal_buffer_caches);
604 
605   // Converting HIDL requests to HAL requests.
606   std::vector<google_camera_hal::CaptureRequest> hal_requests;
607   for (auto& request : requests) {
608     google_camera_hal::CaptureRequest hal_request = {};
609     res = hidl_utils::ConvertToHalCaptureRequest(
610         request, request_metadata_queue_.get(), &hal_request);
611     if (res != OK) {
612       ALOGE("%s: Converting to HAL capture request failed: %s(%d)",
613             __FUNCTION__, strerror(-res), res);
614       _hidl_cb(hidl_utils::ConvertToHidlStatus(res), 0);
615       return Void();
616     }
617 
618     hal_requests.push_back(std::move(hal_request));
619   }
620 
621   uint32_t num_processed_requests = 0;
622   res = device_session_->ProcessCaptureRequest(hal_requests,
623                                                &num_processed_requests);
624   if (res != OK) {
625     ALOGE(
626         "%s: Processing capture request failed: %s(%d). Only processed %u"
627         " out of %zu.",
628         __FUNCTION__, strerror(-res), res, num_processed_requests,
629         hal_requests.size());
630   }
631 
632   _hidl_cb(hidl_utils::ConvertToHidlStatus(res), num_processed_requests);
633   return Void();
634 }
635 
signalStreamFlush(const hidl_vec<int32_t> &,uint32_t)636 Return<void> HidlCameraDeviceSession::signalStreamFlush(
637     const hidl_vec<int32_t>& /*streamIds*/, uint32_t /*streamConfigCounter*/) {
638   // TODO(b/143902312): Implement this.
639   return Void();
640 }
641 
flush()642 Return<Status> HidlCameraDeviceSession::flush() {
643   if (device_session_ == nullptr) {
644     return Status::INTERNAL_ERROR;
645   }
646 
647   auto profiler_item = hidl_profiler::OnCameraFlush();
648 
649   status_t res = device_session_->Flush();
650   if (res != OK) {
651     ALOGE("%s: Flushing device failed: %s(%d).", __FUNCTION__, strerror(-res),
652           res);
653     return Status::INTERNAL_ERROR;
654   }
655 
656   return Status::OK;
657 }
658 
close()659 Return<void> HidlCameraDeviceSession::close() {
660   if (device_session_ != nullptr) {
661     auto profiler_item = hidl_profiler::OnCameraClose();
662     device_session_ = nullptr;
663   }
664 
665   return Void();
666 }
667 
isReconfigurationRequired(const V3_2::CameraMetadata & oldSessionParams,const V3_2::CameraMetadata & newSessionParams,ICameraDeviceSession::isReconfigurationRequired_cb _hidl_cb)668 Return<void> HidlCameraDeviceSession::isReconfigurationRequired(
669     const V3_2::CameraMetadata& oldSessionParams,
670     const V3_2::CameraMetadata& newSessionParams,
671     ICameraDeviceSession::isReconfigurationRequired_cb _hidl_cb) {
672   std::unique_ptr<google_camera_hal::HalCameraMetadata> old_hal_session_metadata;
673   status_t res = hidl_utils::ConvertToHalMetadata(0, nullptr, oldSessionParams,
674                                                   &old_hal_session_metadata);
675   if (res != OK) {
676     ALOGE("%s: Converting to old session metadata failed: %s(%d)", __FUNCTION__,
677           strerror(-res), res);
678     _hidl_cb(Status::INTERNAL_ERROR, true);
679     return Void();
680   }
681 
682   std::unique_ptr<google_camera_hal::HalCameraMetadata> new_hal_session_metadata;
683   res = hidl_utils::ConvertToHalMetadata(0, nullptr, newSessionParams,
684                                          &new_hal_session_metadata);
685   if (res != OK) {
686     ALOGE("%s: Converting to new session metadata failed: %s(%d)", __FUNCTION__,
687           strerror(-res), res);
688     _hidl_cb(Status::INTERNAL_ERROR, true);
689     return Void();
690   }
691 
692   bool reconfiguration_required = true;
693   res = device_session_->IsReconfigurationRequired(
694       old_hal_session_metadata.get(), new_hal_session_metadata.get(),
695       &reconfiguration_required);
696 
697   if (res != OK) {
698     ALOGE("%s: IsReconfigurationRequired failed: %s(%d)", __FUNCTION__,
699           strerror(-res), res);
700     _hidl_cb(Status::INTERNAL_ERROR, true);
701     return Void();
702   }
703 
704   _hidl_cb(Status::OK, reconfiguration_required);
705   return Void();
706 }
707 
configureStreams(const V3_2::StreamConfiguration &,configureStreams_cb _hidl_cb)708 Return<void> HidlCameraDeviceSession::configureStreams(
709     const V3_2::StreamConfiguration&, configureStreams_cb _hidl_cb) {
710   _hidl_cb(Status::ILLEGAL_ARGUMENT, V3_2::HalStreamConfiguration());
711   return Void();
712 }
configureStreams_3_3(const V3_2::StreamConfiguration &,configureStreams_3_3_cb _hidl_cb)713 Return<void> HidlCameraDeviceSession::configureStreams_3_3(
714     const V3_2::StreamConfiguration&, configureStreams_3_3_cb _hidl_cb) {
715   _hidl_cb(Status::ILLEGAL_ARGUMENT, V3_3::HalStreamConfiguration());
716   return Void();
717 }
configureStreams_3_4(const V3_4::StreamConfiguration &,configureStreams_3_4_cb _hidl_cb)718 Return<void> HidlCameraDeviceSession::configureStreams_3_4(
719     const V3_4::StreamConfiguration&, configureStreams_3_4_cb _hidl_cb) {
720   _hidl_cb(Status::ILLEGAL_ARGUMENT, V3_4::HalStreamConfiguration());
721   return Void();
722 }
processCaptureRequest(const hidl_vec<V3_2::CaptureRequest> & requests,const hidl_vec<BufferCache> & cachesToRemove,processCaptureRequest_cb _hidl_cb)723 Return<void> HidlCameraDeviceSession::processCaptureRequest(
724     const hidl_vec<V3_2::CaptureRequest>& requests,
725     const hidl_vec<BufferCache>& cachesToRemove,
726     processCaptureRequest_cb _hidl_cb) {
727   hidl_vec<CaptureRequest> requests_3_4;
728   requests_3_4.resize(requests.size());
729   for (uint32_t i = 0; i < requests_3_4.size(); i++) {
730     requests_3_4[i].v3_2 = requests[i];
731   }
732 
733   return processCaptureRequest_3_4(requests_3_4, cachesToRemove, _hidl_cb);
734 }
735 
736 }  // namespace implementation
737 }  // namespace V3_5
738 }  // namespace device
739 }  // namespace camera
740 }  // namespace hardware
741 }  // namespace android
742