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_NDEBUG 0
18 #define LOG_TAG "GCH_CameraDeviceSession"
19 #define ATRACE_TAG ATRACE_TAG_CAMERA
20 #include "camera_device_session.h"
21 
22 #include <inttypes.h>
23 #include <log/log.h>
24 #include <system/graphics-base-v1.0.h>
25 #include <utils/Trace.h>
26 
27 #include "basic_capture_session.h"
28 #include "capture_session_utils.h"
29 #include "hal_types.h"
30 #include "hal_utils.h"
31 #include "system/camera_metadata.h"
32 #include "ui/GraphicBufferMapper.h"
33 #include "vendor_tag_defs.h"
34 #include "vendor_tag_types.h"
35 #include "vendor_tags.h"
36 #include "zsl_snapshot_capture_session.h"
37 
38 namespace android {
39 namespace google_camera_hal {
40 
41 constexpr char kMeasureBufferAllocationProp[] =
42     "persist.vendor.camera.measure_buffer_allocation";
43 
44 static constexpr int64_t kNsPerSec = 1000000000;
45 static constexpr int64_t kAllocationThreshold = 33000000;  // 33ms
46 
47 std::vector<CaptureSessionEntryFuncs>
48     CameraDeviceSession::kCaptureSessionEntries = {
49         {.IsStreamConfigurationSupported =
50              BasicCaptureSession::IsStreamConfigurationSupported,
51          .CreateSession = BasicCaptureSession::Create}};
52 
53 std::vector<WrapperCaptureSessionEntryFuncs>
54     CameraDeviceSession::kWrapperCaptureSessionEntries = {
55         {.IsStreamConfigurationSupported =
56              ZslSnapshotCaptureSession::IsStreamConfigurationSupported,
57          .CreateSession = ZslSnapshotCaptureSession::Create}};
58 
Create(std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries,CameraBufferAllocatorHwl * camera_allocator_hwl)59 std::unique_ptr<CameraDeviceSession> CameraDeviceSession::Create(
60     std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,
61     std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries,
62     CameraBufferAllocatorHwl* camera_allocator_hwl) {
63   ATRACE_CALL();
64   if (device_session_hwl == nullptr) {
65     ALOGE("%s: device_session_hwl is nullptr", __FUNCTION__);
66     return nullptr;
67   }
68 
69   uint32_t camera_id = device_session_hwl->GetCameraId();
70   std::vector<uint32_t> physical_camera_ids =
71       device_session_hwl->GetPhysicalCameraIds();
72 
73   auto session = std::unique_ptr<CameraDeviceSession>(new CameraDeviceSession());
74   if (session == nullptr) {
75     ALOGE("%s: Creating CameraDeviceSession failed.", __FUNCTION__);
76     return nullptr;
77   }
78 
79   status_t res =
80       session->Initialize(std::move(device_session_hwl), camera_allocator_hwl,
81                           external_session_factory_entries);
82   if (res != OK) {
83     ALOGE("%s: Initializing CameraDeviceSession failed: %s (%d).", __FUNCTION__,
84           strerror(-res), res);
85     return nullptr;
86   }
87 
88   // Construct a string of physical camera IDs.
89   std::string physical_camera_ids_string;
90   if (physical_camera_ids.size() > 0) {
91     physical_camera_ids_string += ": ";
92 
93     for (auto& id : physical_camera_ids) {
94       physical_camera_ids_string += std::to_string(id) + " ";
95     }
96   }
97 
98   ALOGI(
99       "%s: Created a device session for camera %d with %zu physical cameras%s",
100       __FUNCTION__, camera_id, physical_camera_ids.size(),
101       physical_camera_ids_string.c_str());
102 
103   return session;
104 }
105 
UpdatePendingRequest(CaptureResult * result)106 status_t CameraDeviceSession::UpdatePendingRequest(CaptureResult* result) {
107   std::lock_guard<std::mutex> lock(request_record_lock_);
108   if (result == nullptr) {
109     ALOGE("%s: result is nullptr.", __FUNCTION__);
110     return BAD_VALUE;
111   }
112 
113   if (result->output_buffers.empty()) {
114     // Nothing to do if the result doesn't contain any output buffers.
115     return OK;
116   }
117   bool frame_has_hal_buffer_managed_buffer = false;
118   for (const auto& buffer : result->output_buffers) {
119     if (hal_buffer_managed_stream_ids_.find(buffer.stream_id) !=
120         hal_buffer_managed_stream_ids_.end()) {
121       frame_has_hal_buffer_managed_buffer = true;
122       break;
123     }
124   }
125 
126   // There's no HAL buffer managed buffer in the frame, we don't need to track
127   // it through pending_request_streams_.
128   if (!frame_has_hal_buffer_managed_buffer) {
129     return OK;
130   }
131 
132   // Update inflight request records and notify SBC for flushing if needed
133   uint32_t frame_number = result->frame_number;
134 
135   if (pending_request_streams_.find(frame_number) ==
136       pending_request_streams_.end()) {
137     ALOGE("%s: Can't find frame %u in result holder.", __FUNCTION__,
138           frame_number);
139     return UNKNOWN_ERROR;
140   }
141 
142   // Remove streams from pending request streams for buffers in the result.
143   auto& streams = pending_request_streams_.at(frame_number);
144   for (auto& stream_buffer : result->output_buffers) {
145     int32_t stream_id = stream_buffer.stream_id;
146     if (streams.find(stream_id) == streams.end()) {
147       // If stream_id belongs to a stream group, the HWL may choose to output
148       // buffers to a different stream in the same group.
149       if (grouped_stream_id_map_.count(stream_id) == 1) {
150         int32_t stream_id_for_group = grouped_stream_id_map_.at(stream_id);
151         if (streams.find(stream_id_for_group) != streams.end()) {
152           streams.erase(stream_id_for_group);
153         } else {
154           ALOGE(
155               "%s: Can't find stream_id_for_group %d for stream %d in frame %u "
156               "result holder. It may have been returned or have not been "
157               "requested.",
158               __FUNCTION__, stream_id_for_group, stream_id, frame_number);
159         }
160       } else {
161         ALOGE(
162             "%s: Can't find stream %d in frame %u result holder. It may"
163             " have been returned or have not been requested.",
164             __FUNCTION__, stream_id, frame_number);
165       }
166       // Ignore this buffer and continue handling other buffers in the
167       // result.
168     } else {
169       streams.erase(stream_id);
170     }
171   }
172 
173   if (streams.empty()) {
174     pending_request_streams_.erase(frame_number);
175   }
176 
177   if (pending_request_streams_.empty()) {
178     status_t res = stream_buffer_cache_manager_->NotifyFlushingAll();
179     if (res != OK) {
180       ALOGE("%s: Failed to notify SBC manager to flush all streams.",
181             __FUNCTION__);
182     }
183     ALOGI(
184         "%s: [sbc] All inflight requests/streams cleared. Notified SBC for "
185         "flushing.",
186         __FUNCTION__);
187   }
188   return OK;
189 }
190 
ProcessCaptureResult(std::unique_ptr<CaptureResult> result)191 void CameraDeviceSession::ProcessCaptureResult(
192     std::unique_ptr<CaptureResult> result) {
193   if (TryHandleCaptureResult(result)) return;
194 
195   // Update pending request tracker with returned buffers.
196   std::vector<StreamBuffer> buffers;
197   buffers.insert(buffers.end(), result->output_buffers.begin(),
198                  result->output_buffers.end());
199 
200   if (result->result_metadata) {
201     std::lock_guard<std::mutex> lock(request_record_lock_);
202     pending_results_.erase(result->frame_number);
203   }
204 
205   {
206     std::shared_lock lock(session_callback_lock_);
207     session_callback_.process_capture_result(std::move(result));
208   }
209 
210   TrackReturnedBuffers(buffers);
211 }
212 
ProcessBatchCaptureResult(std::vector<std::unique_ptr<CaptureResult>> results)213 void CameraDeviceSession::ProcessBatchCaptureResult(
214     std::vector<std::unique_ptr<CaptureResult>> results) {
215   std::vector<std::unique_ptr<CaptureResult>> results_to_callback;
216   results_to_callback.reserve(results.size());
217   std::vector<StreamBuffer> buffers;
218   for (auto& result : results) {
219     if (TryHandleCaptureResult(result)) continue;
220 
221     // Update pending request tracker with returned buffers.
222     buffers.insert(buffers.end(), result->output_buffers.begin(),
223                    result->output_buffers.end());
224 
225     if (result->result_metadata) {
226       std::lock_guard<std::mutex> lock(request_record_lock_);
227       pending_results_.erase(result->frame_number);
228     }
229 
230     results_to_callback.push_back(std::move(result));
231   }
232 
233   {
234     std::shared_lock lock(session_callback_lock_);
235     session_callback_.process_batch_capture_result(
236         std::move(results_to_callback));
237   }
238 
239   TrackReturnedBuffers(buffers);
240 }
241 
Notify(const NotifyMessage & result)242 void CameraDeviceSession::Notify(const NotifyMessage& result) {
243   {
244     uint32_t frame_number = 0;
245     if (result.type == MessageType::kError) {
246       frame_number = result.message.error.frame_number;
247     } else if (result.type == MessageType::kShutter) {
248       frame_number = result.message.shutter.frame_number;
249     }
250     std::lock_guard<std::mutex> lock(request_record_lock_);
251     // Strip out results for frame number that has been notified
252     // ErrorCode::kErrorResult and ErrorCode::kErrorBuffer
253     if ((error_notified_requests_.find(frame_number) !=
254          error_notified_requests_.end()) &&
255         (result.type != MessageType::kShutter)) {
256       return;
257     }
258 
259     if (result.type == MessageType::kError &&
260         result.message.error.error_code == ErrorCode::kErrorResult) {
261       pending_results_.erase(frame_number);
262 
263       if (ignore_shutters_.find(frame_number) == ignore_shutters_.end()) {
264         ignore_shutters_.insert(frame_number);
265       }
266     }
267 
268     if (result.type == MessageType::kShutter) {
269       if (ignore_shutters_.find(frame_number) != ignore_shutters_.end()) {
270         ignore_shutters_.erase(frame_number);
271         return;
272       }
273     }
274   }
275 
276   if (ATRACE_ENABLED() && result.type == MessageType::kShutter) {
277     int64_t timestamp_ns_diff = 0;
278     int64_t current_timestamp_ns = result.message.shutter.timestamp_ns;
279     if (last_timestamp_ns_for_trace_ != 0) {
280       timestamp_ns_diff = current_timestamp_ns - last_timestamp_ns_for_trace_;
281     }
282 
283     last_timestamp_ns_for_trace_ = current_timestamp_ns;
284 
285     ATRACE_INT64("sensor_timestamp_diff", timestamp_ns_diff);
286     ATRACE_INT("timestamp_frame_number", result.message.shutter.frame_number);
287   }
288 
289   std::shared_lock lock(session_callback_lock_);
290   session_callback_.notify(result);
291 }
292 
InitializeCallbacks()293 void CameraDeviceSession::InitializeCallbacks() {
294   std::lock_guard lock(session_callback_lock_);
295 
296   // Initialize callback to
297   session_callback_.process_capture_result =
298       ProcessCaptureResultFunc([](std::unique_ptr<CaptureResult> /*result*/) {
299         ALOGW("%s: No session callback was set.", __FUNCTION__);
300       });
301 
302   session_callback_.notify = NotifyFunc([](const NotifyMessage& /*message*/) {
303     ALOGW("%s: No session callback was set.", __FUNCTION__);
304   });
305 
306   session_callback_.request_stream_buffers = RequestStreamBuffersFunc(
307       [](const std::vector<BufferRequest>& /*hal_buffer_requests*/,
308          std::vector<BufferReturn>* /*hal_buffer_returns*/) {
309         ALOGW("%s: No session callback was set.", __FUNCTION__);
310         return google_camera_hal::BufferRequestStatus::kFailedUnknown;
311       });
312 
313   session_callback_.return_stream_buffers = ReturnStreamBuffersFunc(
314       [](const std::vector<StreamBuffer>& /*return_hal_buffers*/) {
315         ALOGW("%s: No session callback was set.", __FUNCTION__);
316         return google_camera_hal::BufferRequestStatus::kFailedUnknown;
317       });
318 
319   camera_device_session_callback_.process_capture_result =
320       ProcessCaptureResultFunc([this](std::unique_ptr<CaptureResult> result) {
321         ProcessCaptureResult(std::move(result));
322       });
323 
324   camera_device_session_callback_.process_batch_capture_result =
325       ProcessBatchCaptureResultFunc(
326           [this](std::vector<std::unique_ptr<CaptureResult>> results) {
327             ProcessBatchCaptureResult(std::move(results));
328           });
329 
330   camera_device_session_callback_.notify =
331       NotifyFunc([this](const NotifyMessage& result) { Notify(result); });
332 
333   hwl_session_callback_.request_stream_buffers = HwlRequestBuffersFunc(
334       [this](int32_t stream_id, uint32_t num_buffers,
335              std::vector<StreamBuffer>* buffers, uint32_t frame_number) {
336         return RequestBuffersFromStreamBufferCacheManager(
337             stream_id, num_buffers, buffers, frame_number);
338       });
339 
340   hwl_session_callback_.return_stream_buffers =
341       HwlReturnBuffersFunc([this](const std::vector<StreamBuffer>& buffers) {
342         return ReturnStreamBuffers(buffers);
343       });
344 
345   device_session_hwl_->SetSessionCallback(hwl_session_callback_);
346 }
347 
InitializeBufferManagement(HalCameraMetadata * characteristics)348 status_t CameraDeviceSession::InitializeBufferManagement(
349     HalCameraMetadata* characteristics) {
350   ATRACE_CALL();
351 
352   if (characteristics == nullptr) {
353     ALOGE("%s: characteristics cannot be nullptr.", __FUNCTION__);
354     return BAD_VALUE;
355   }
356 
357   camera_metadata_ro_entry entry = {};
358   status_t res = characteristics->Get(
359       ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION, &entry);
360   if (res == OK && entry.count > 0) {
361     buffer_management_used_ =
362         (entry.data.u8[0] ==
363          ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
364     session_buffer_management_supported_ =
365         (entry.data.u8[0] ==
366          ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_SESSION_CONFIGURABLE);
367   }
368 
369   return OK;
370 }
371 
Initialize(std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,CameraBufferAllocatorHwl * camera_allocator_hwl,std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries)372 status_t CameraDeviceSession::Initialize(
373     std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,
374     CameraBufferAllocatorHwl* camera_allocator_hwl,
375     std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries) {
376   ATRACE_CALL();
377   if (device_session_hwl == nullptr) {
378     ALOGE("%s: device_session_hwl cannot be nullptr.", __FUNCTION__);
379     return BAD_VALUE;
380   }
381   measure_buffer_allocation_time_ =
382       property_get_bool(kMeasureBufferAllocationProp, false);
383   ALOGI("%s: measure buffer allocation time: %d ", __FUNCTION__,
384         measure_buffer_allocation_time_);
385 
386   camera_id_ = device_session_hwl->GetCameraId();
387   device_session_hwl_ = std::move(device_session_hwl);
388   camera_allocator_hwl_ = camera_allocator_hwl;
389 
390   GraphicBufferMapper::preloadHal();
391   InitializeCallbacks();
392 
393   std::unique_ptr<google_camera_hal::HalCameraMetadata> characteristics;
394   status_t res = device_session_hwl_->GetCameraCharacteristics(&characteristics);
395   if (res != OK) {
396     ALOGE("%s: Get camera characteristics failed: %s(%d)", __FUNCTION__,
397           strerror(-res), res);
398     return res;
399   }
400 
401   res = utils::GetStreamUseCases(
402       characteristics.get(),
403       &camera_id_to_stream_use_cases_[device_session_hwl_->GetCameraId()]);
404   if (res != OK) {
405     ALOGE("%s: Initializing stream use case failed: %s(%d) for camera id %u",
406           __FUNCTION__, strerror(-res), res, device_session_hwl_->GetCameraId());
407     return res;
408   }
409 
410   res = utils::GetPhysicalCameraStreamUseCases(device_session_hwl_.get(),
411                                                &camera_id_to_stream_use_cases_);
412   if (res != OK) {
413     ALOGE(
414         "%s: Initializing physical stream use cases failed: %s(%d) for camera "
415         "id %u",
416         __FUNCTION__, strerror(-res), res, device_session_hwl_->GetCameraId());
417     return res;
418   }
419   res = InitializeBufferManagement(characteristics.get());
420   if (res != OK) {
421     ALOGE("%s: Initialize buffer management failed: %s(%d)", __FUNCTION__,
422           strerror(-res), res);
423     return res;
424   }
425 
426   res = LoadExternalCaptureSession(external_session_factory_entries);
427   if (res != OK) {
428     ALOGE("%s: Loading external capture sessions failed: %s(%d)", __FUNCTION__,
429           strerror(-res), res);
430     return res;
431   }
432 
433   InitializeZoomRatioMapper(characteristics.get());
434 
435   return OK;
436 }
437 
GetMaxResDimension(const HalCameraMetadata * characteristics,Dimension & max_res_dimension)438 status_t GetMaxResDimension(const HalCameraMetadata* characteristics,
439                             Dimension& max_res_dimension) {
440   Rect active_array_maximum_resolution_size;
441   status_t max_res_status = utils::GetSensorActiveArraySize(
442       characteristics, &active_array_maximum_resolution_size,
443       /*maximum_resolution*/ true);
444   if (max_res_status == OK) {
445     max_res_dimension = {active_array_maximum_resolution_size.right -
446                              active_array_maximum_resolution_size.left + 1,
447                          active_array_maximum_resolution_size.bottom -
448                              active_array_maximum_resolution_size.top + 1};
449   }
450   return max_res_status;
451 }
452 
InitializeZoomRatioMapper(HalCameraMetadata * characteristics)453 void CameraDeviceSession::InitializeZoomRatioMapper(
454     HalCameraMetadata* characteristics) {
455   if (characteristics == nullptr) {
456     ALOGE("%s: characteristics cannot be nullptr.", __FUNCTION__);
457     return;
458   }
459 
460   Rect active_array_size;
461   status_t res =
462       utils::GetSensorActiveArraySize(characteristics, &active_array_size,
463                                       /*maximum_resolution*/ false);
464   if (res != OK) {
465     ALOGE("%s: Failed to get the active array size: %s(%d)", __FUNCTION__,
466           strerror(-res), res);
467     return;
468   }
469 
470   ZoomRatioMapper::InitParams params;
471   params.camera_id = camera_id_;
472   params.active_array_dimension = {
473       active_array_size.right - active_array_size.left + 1,
474       active_array_size.bottom - active_array_size.top + 1};
475 
476   // Populate max-res dimension only if the logical camera have max-res resolution
477   (void)GetMaxResDimension(characteristics,
478                            params.active_array_maximum_resolution_dimension);
479 
480   std::vector<uint32_t> physical_camera_ids =
481       device_session_hwl_->GetPhysicalCameraIds();
482   for (uint32_t id : physical_camera_ids) {
483     std::unique_ptr<google_camera_hal::HalCameraMetadata>
484         physical_cam_characteristics;
485     res = device_session_hwl_->GetPhysicalCameraCharacteristics(
486         id, &physical_cam_characteristics);
487     if (res != OK) {
488       ALOGE("%s: Get camera: %u characteristics failed: %s(%d)", __FUNCTION__,
489             id, strerror(-res), res);
490       return;
491     }
492 
493     res = utils::GetSensorActiveArraySize(physical_cam_characteristics.get(),
494                                           &active_array_size,
495                                           /*maximum_resolution*/ false);
496     if (res != OK) {
497       ALOGE("%s: Failed to get cam: %u, active array size: %s(%d)",
498             __FUNCTION__, id, strerror(-res), res);
499       return;
500     }
501     Dimension active_array_dimension = {
502         active_array_size.right - active_array_size.left + 1,
503         active_array_size.bottom - active_array_size.top + 1};
504     params.physical_cam_active_array_dimension.emplace(id,
505                                                        active_array_dimension);
506     Dimension max_res_dimension;
507     if (GetMaxResDimension(physical_cam_characteristics.get(),
508                            max_res_dimension) == OK) {
509       params.physical_cam_active_array_maximum_resolution_dimension.emplace(
510           id, max_res_dimension);
511     }
512   }
513 
514   res = utils::GetZoomRatioRange(characteristics, &params.zoom_ratio_range);
515   if (res != OK) {
516     ALOGW("%s: Failed to get the zoom ratio range: %s(%d)", __FUNCTION__,
517           strerror(-res), res);
518     return;
519   }
520 
521   params.zoom_ratio_mapper_hwl = device_session_hwl_->GetZoomRatioMapperHwl();
522 
523   zoom_ratio_mapper_.Initialize(&params);
524 }
525 
DeriveGroupedStreamIdMap()526 void CameraDeviceSession::DeriveGroupedStreamIdMap() {
527   // Group stream ids by stream group id
528   std::unordered_map<int32_t, std::vector<int32_t>> group_to_streams_map;
529   for (const auto& [stream_id, stream] : configured_streams_map_) {
530     if (stream.stream_type == StreamType::kOutput && stream.group_id != -1) {
531       group_to_streams_map[stream.group_id].push_back(stream_id);
532     }
533   }
534 
535   // For each stream group, map all the streams' ids to one id
536   for (const auto& [group_id, stream_ids] : group_to_streams_map) {
537     for (size_t i = 1; i < stream_ids.size(); i++) {
538       grouped_stream_id_map_[stream_ids[i]] = stream_ids[0];
539     }
540   }
541 }
542 
LoadExternalCaptureSession(std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries)543 status_t CameraDeviceSession::LoadExternalCaptureSession(
544     std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries) {
545   ATRACE_CALL();
546 
547   if (external_capture_session_entries_.size() > 0) {
548     ALOGI("%s: External capture session libraries already loaded; skip.",
549           __FUNCTION__);
550     return OK;
551   }
552 
553   for (const auto& external_session_factory_t :
554        external_session_factory_entries) {
555     ExternalCaptureSessionFactory* external_session =
556         external_session_factory_t();
557     if (!external_session) {
558       ALOGE("%s: External session may be incomplete", __FUNCTION__);
559       continue;
560     }
561 
562     external_capture_session_entries_.push_back(external_session);
563   }
564 
565   return OK;
566 }
567 
~CameraDeviceSession()568 CameraDeviceSession::~CameraDeviceSession() {
569   UnregisterThermalCallback();
570 
571   capture_session_ = nullptr;
572   device_session_hwl_ = nullptr;
573 
574   for (auto external_session : external_capture_session_entries_) {
575     delete external_session;
576   }
577   external_capture_session_entries_.clear();
578 
579   FreeImportedBufferHandles();
580 }
581 
UnregisterThermalCallback()582 void CameraDeviceSession::UnregisterThermalCallback() {
583   std::shared_lock lock(session_callback_lock_);
584   if (thermal_callback_.unregister_thermal_changed_callback != nullptr) {
585     thermal_callback_.unregister_thermal_changed_callback();
586   }
587 }
588 
SetSessionCallback(const CameraDeviceSessionCallback & session_callback,const ThermalCallback & thermal_callback)589 void CameraDeviceSession::SetSessionCallback(
590     const CameraDeviceSessionCallback& session_callback,
591     const ThermalCallback& thermal_callback) {
592   ATRACE_CALL();
593   std::lock_guard lock(session_callback_lock_);
594   session_callback_ = session_callback;
595   thermal_callback_ = thermal_callback;
596 
597   status_t res = thermal_callback_.register_thermal_changed_callback(
598       NotifyThrottlingFunc([this](const Temperature& temperature) {
599         NotifyThrottling(temperature);
600       }),
601       /*filter_type=*/false,
602       /*type=*/TemperatureType::kUnknown);
603   if (res != OK) {
604     ALOGW("%s: Registering thermal callback failed: %s(%d)", __FUNCTION__,
605           strerror(-res), res);
606   }
607 }
608 
NotifyThrottling(const Temperature & temperature)609 void CameraDeviceSession::NotifyThrottling(const Temperature& temperature) {
610   switch (temperature.throttling_status) {
611     case ThrottlingSeverity::kNone:
612     case ThrottlingSeverity::kLight:
613     case ThrottlingSeverity::kModerate:
614       ALOGI("%s: temperature type: %d, severity: %u, value: %f", __FUNCTION__,
615             temperature.type, temperature.throttling_status, temperature.value);
616       return;
617     case ThrottlingSeverity::kSevere:
618     case ThrottlingSeverity::kCritical:
619     case ThrottlingSeverity::kEmergency:
620     case ThrottlingSeverity::kShutdown:
621       ALOGW("%s: temperature type: %d, severity: %u, value: %f", __FUNCTION__,
622             temperature.type, temperature.throttling_status, temperature.value);
623       {
624         std::lock_guard<std::mutex> lock(session_lock_);
625         thermal_throttling_ = true;
626       }
627       return;
628     default:
629       ALOGE("%s: Unknown throttling status %u for type %d", __FUNCTION__,
630             temperature.throttling_status, temperature.type);
631       return;
632   }
633 }
634 
ConstructDefaultRequestSettings(RequestTemplate type,std::unique_ptr<HalCameraMetadata> * default_settings)635 status_t CameraDeviceSession::ConstructDefaultRequestSettings(
636     RequestTemplate type, std::unique_ptr<HalCameraMetadata>* default_settings) {
637   ATRACE_CALL();
638   status_t res = device_session_hwl_->ConstructDefaultRequestSettings(
639       type, default_settings);
640   if (res != OK) {
641     ALOGE("%s: Construct default settings for type %d failed: %s(%d)",
642           __FUNCTION__, type, strerror(-res), res);
643     return res;
644   }
645 
646   return hal_vendor_tag_utils::ModifyDefaultRequestSettings(
647       type, default_settings->get());
648 }
649 
ConfigureStreams(const StreamConfiguration & stream_config,bool v2,ConfigureStreamsReturn * configured_streams)650 status_t CameraDeviceSession::ConfigureStreams(
651     const StreamConfiguration& stream_config, bool v2,
652     ConfigureStreamsReturn* configured_streams) {
653   ATRACE_CALL();
654   bool set_realtime_thread = false;
655   int32_t schedule_policy;
656   struct sched_param schedule_param = {0};
657   if (configured_streams == nullptr) {
658     ALOGE("%s: configured_streams output is nullptr", __FUNCTION__);
659     return BAD_VALUE;
660   }
661   std::vector<HalStream>& hal_config = configured_streams->hal_streams;
662   if (utils::SupportRealtimeThread()) {
663     bool get_thread_schedule = false;
664     if (pthread_getschedparam(pthread_self(), &schedule_policy,
665                               &schedule_param) == 0) {
666       get_thread_schedule = true;
667     } else {
668       ALOGE("%s: pthread_getschedparam fail", __FUNCTION__);
669     }
670 
671     if (get_thread_schedule) {
672       status_t res = utils::SetRealtimeThread(pthread_self());
673       if (res != OK) {
674         ALOGE("%s: SetRealtimeThread fail", __FUNCTION__);
675       } else {
676         set_realtime_thread = true;
677       }
678     }
679   }
680 
681   std::lock_guard<std::mutex> lock(session_lock_);
682 
683   std::lock_guard lock_capture_session(capture_session_lock_);
684   if (capture_session_ != nullptr) {
685     ATRACE_NAME("CameraDeviceSession::DestroyOldSession");
686     capture_session_ = nullptr;
687   }
688 
689   pending_requests_tracker_ = nullptr;
690 
691   if (!configured_streams_map_.empty()) {
692     CleanupStaleStreamsLocked(stream_config.streams);
693   }
694   hal_buffer_managed_stream_ids_.clear();
695 
696   hal_utils::DumpStreamConfiguration(stream_config, "App stream configuration");
697 
698   multi_res_reprocess_ = stream_config.multi_resolution_input_image;
699 
700   // TODO: We would ideally want this to be a part of CreateCaptureSession,
701   // which internally calls IsStreamCombinationSupported. However this
702   // IsStreamCombinationSupported doesn't match the
703   // CameraDevice::IsStreamCombination. We should look at unifying the two for a
704   // potentially cleaner code-base.
705   if (!utils::IsStreamUseCaseSupported(stream_config, camera_id_,
706                                        camera_id_to_stream_use_cases_)) {
707     return BAD_VALUE;
708   }
709   device_session_hwl_->setConfigureStreamsV2(v2);
710   bool multi_resolution_stream_used = false;
711   for (const auto& stream : stream_config.streams) {
712     if (stream.group_id != -1) {
713       multi_resolution_stream_used = true;
714       break;
715     }
716   }
717   capture_session_ = CreateCaptureSession(
718       stream_config, kWrapperCaptureSessionEntries,
719       external_capture_session_entries_, kCaptureSessionEntries,
720       hwl_session_callback_, camera_allocator_hwl_, device_session_hwl_.get(),
721       &hal_config, camera_device_session_callback_.process_capture_result,
722       camera_device_session_callback_.notify,
723       camera_device_session_callback_.process_batch_capture_result);
724 
725   if (capture_session_ == nullptr) {
726     ALOGE("%s: Cannot find a capture session compatible with stream config",
727           __FUNCTION__);
728     if (set_realtime_thread) {
729       utils::UpdateThreadSched(pthread_self(), schedule_policy, &schedule_param);
730     }
731     return BAD_VALUE;
732   }
733   // Backup the streams received from frameworks into configured_streams_map_,
734   // and we can find out specific streams through stream id in output_buffers.
735   for (auto& stream : stream_config.streams) {
736     configured_streams_map_[stream.id] = stream;
737   }
738   if (session_buffer_management_supported_ && v2) {
739     std::set<int32_t> hal_buffer_managed_stream_ids =
740         device_session_hwl_->GetHalBufferManagedStreams(stream_config);
741     hal_buffer_managed_stream_ids_ = hal_buffer_managed_stream_ids;
742     for (auto& hal_stream : hal_config) {
743       if (hal_buffer_managed_stream_ids.find(hal_stream.id) !=
744           hal_buffer_managed_stream_ids.end()) {
745         hal_stream.is_hal_buffer_managed = true;
746       }
747     }
748   } else if (buffer_management_used_ || multi_resolution_stream_used) {
749     // No session specific hal buffer manager supported, all streams are
750     // hal buffer managed. In the case of multi resolution streams we also
751     // are mandated to use hal buffer manager (VTS asserts for this)
752     for (auto& hal_stream : hal_config) {
753       if (configured_streams_map_.find(hal_stream.id) ==
754           configured_streams_map_.end()) {
755         ALOGE("%s: HalStream id %d not found in configured streams map",
756               __FUNCTION__, hal_stream.id);
757         return UNKNOWN_ERROR;
758       }
759       if (configured_streams_map_[hal_stream.id].stream_type ==
760           StreamType::kInput) {
761         continue;
762       }
763       hal_stream.is_hal_buffer_managed = true;
764       hal_buffer_managed_stream_ids_.insert(hal_stream.id);
765     }
766   }
767 
768   stream_buffer_cache_manager_ =
769       StreamBufferCacheManager::Create(hal_buffer_managed_stream_ids_);
770   if (stream_buffer_cache_manager_ == nullptr) {
771     ALOGE("%s: Failed to create stream buffer cache manager.", __FUNCTION__);
772     if (set_realtime_thread) {
773       utils::UpdateThreadSched(pthread_self(), schedule_policy, &schedule_param);
774     }
775     return UNKNOWN_ERROR;
776   }
777   if (hal_buffer_managed_stream_ids_.size() != 0) {
778     status_t res =
779         RegisterStreamsIntoCacheManagerLocked(stream_config, hal_config);
780     if (res != OK) {
781       ALOGE("%s: Failed to register streams into stream buffer cache manager.",
782             __FUNCTION__);
783       if (set_realtime_thread) {
784         utils::UpdateThreadSched(pthread_self(), schedule_policy,
785                                  &schedule_param);
786       }
787       return res;
788     }
789   }
790 
791   // (b/129561652): Framework assumes HalStream is sorted.
792   std::sort(hal_config.begin(), hal_config.end(),
793             [](const HalStream& a, const HalStream& b) { return a.id < b.id; });
794 
795   // Derives all stream ids within a group to a representative stream id
796   DeriveGroupedStreamIdMap();
797 
798   // If buffer management is support, create a pending request tracker for
799   // capture request throttling.
800   pending_requests_tracker_ = PendingRequestsTracker::Create(
801       hal_config, grouped_stream_id_map_, hal_buffer_managed_stream_ids_);
802   if (pending_requests_tracker_ == nullptr) {
803     ALOGE("%s: Cannot create a pending request tracker.", __FUNCTION__);
804     if (set_realtime_thread) {
805       utils::UpdateThreadSched(pthread_self(), schedule_policy, &schedule_param);
806     }
807     return UNKNOWN_ERROR;
808   }
809 
810   {
811     std::lock_guard<std::mutex> request_lock(request_record_lock_);
812     pending_request_streams_.clear();
813     error_notified_requests_.clear();
814     placeholder_buffer_observed_.clear();
815     pending_results_.clear();
816     ignore_shutters_.clear();
817   }
818 
819   has_valid_settings_ = false;
820   thermal_throttling_ = false;
821   thermal_throttling_notified_ = false;
822   last_request_settings_ = nullptr;
823   last_timestamp_ns_for_trace_ = 0;
824 
825   if (set_realtime_thread) {
826     utils::UpdateThreadSched(pthread_self(), schedule_policy, &schedule_param);
827   }
828   return OK;
829 }
830 
UpdateBufferHandlesLocked(std::vector<StreamBuffer> * buffers,bool update_hal_buffer_managed_streams)831 status_t CameraDeviceSession::UpdateBufferHandlesLocked(
832     std::vector<StreamBuffer>* buffers, bool update_hal_buffer_managed_streams) {
833   ATRACE_CALL();
834   if (buffers == nullptr) {
835     ALOGE("%s: buffers cannot be nullptr", __FUNCTION__);
836     return BAD_VALUE;
837   }
838 
839   for (auto& buffer : *buffers) {
840     bool is_hal_buffer_managed =
841         hal_buffer_managed_stream_ids_.find(buffer.stream_id) !=
842         hal_buffer_managed_stream_ids_.end();
843     // Skip the update if import_hal_buffer_managed_streams doesn't match the
844     //  stream ids hal buffer manager behavior.
845     bool skip = (!is_hal_buffer_managed && update_hal_buffer_managed_streams) ||
846                 (!update_hal_buffer_managed_streams && is_hal_buffer_managed);
847     if (skip) {
848       continue;
849     }
850     // Get the buffer handle from buffer handle map.
851     BufferCache buffer_cache = {buffer.stream_id, buffer.buffer_id};
852     auto buffer_handle_it = imported_buffer_handle_map_.find(buffer_cache);
853     if (buffer_handle_it == imported_buffer_handle_map_.end()) {
854       ALOGE("%s: Cannot find buffer handle for stream %u, buffer %" PRIu64,
855             __FUNCTION__, buffer.stream_id, buffer.buffer_id);
856       return NAME_NOT_FOUND;
857     }
858 
859     buffer.buffer = buffer_handle_it->second;
860   }
861 
862   return OK;
863 }
864 
CreateCaptureRequestLocked(const CaptureRequest & request,CaptureRequest * updated_request)865 status_t CameraDeviceSession::CreateCaptureRequestLocked(
866     const CaptureRequest& request, CaptureRequest* updated_request) {
867   ATRACE_CALL();
868   if (updated_request == nullptr) {
869     return BAD_VALUE;
870   }
871 
872   if (request.settings != nullptr) {
873     last_request_settings_ = HalCameraMetadata::Clone(request.settings.get());
874   }
875 
876   updated_request->frame_number = request.frame_number;
877   updated_request->settings = HalCameraMetadata::Clone(request.settings.get());
878   updated_request->input_buffers = request.input_buffers;
879   updated_request->input_buffer_metadata.clear();
880   updated_request->output_buffers = request.output_buffers;
881   std::vector<uint32_t> physical_camera_ids =
882       device_session_hwl_->GetPhysicalCameraIds();
883   for (auto& [camid, physical_setting] : request.physical_camera_settings) {
884     if (std::find(physical_camera_ids.begin(), physical_camera_ids.end(),
885                   camid) == physical_camera_ids.end()) {
886       ALOGE("%s: Pyhsical camera id %d in request had not registered",
887             __FUNCTION__, camid);
888       return BAD_VALUE;
889     }
890     updated_request->physical_camera_settings[camid] =
891         HalCameraMetadata::Clone(physical_setting.get());
892   }
893   updated_request->input_width = request.input_width;
894   updated_request->input_height = request.input_height;
895 
896   // Returns -1 if kThermalThrottling is not defined, skip following process.
897   if (get_camera_metadata_tag_type(VendorTagIds::kThermalThrottling) != -1) {
898     // Create settings to set thermal throttling key if needed.
899     if (thermal_throttling_ && !thermal_throttling_notified_ &&
900         updated_request->settings == nullptr) {
901       updated_request->settings =
902           HalCameraMetadata::Clone(last_request_settings_.get());
903       thermal_throttling_notified_ = true;
904     }
905 
906     if (updated_request->settings != nullptr) {
907       status_t res = updated_request->settings->Set(
908           VendorTagIds::kThermalThrottling, &thermal_throttling_,
909           /*data_count=*/1);
910       if (res != OK) {
911         ALOGE("%s: Setting thermal throttling key failed: %s(%d)", __FUNCTION__,
912               strerror(-res), res);
913         return res;
914       }
915     }
916   }
917 
918   AppendOutputIntentToSettingsLocked(request, updated_request);
919 
920   {
921     std::lock_guard<std::mutex> lock(imported_buffer_handle_map_lock_);
922 
923     status_t res = UpdateBufferHandlesLocked(&updated_request->input_buffers);
924     if (res != OK) {
925       ALOGE("%s: Updating input buffer handles failed: %s(%d)", __FUNCTION__,
926             strerror(-res), res);
927       return res;
928     }
929 
930     res = UpdateBufferHandlesLocked(&updated_request->output_buffers);
931     if (res != OK) {
932       ALOGE("%s: Updating output buffer handles failed: %s(%d)", __FUNCTION__,
933             strerror(-res), res);
934       return res;
935     }
936   }
937 
938   zoom_ratio_mapper_.UpdateCaptureRequest(updated_request);
939 
940   return OK;
941 }
942 
ImportBufferHandleLocked(const StreamBuffer & buffer)943 status_t CameraDeviceSession::ImportBufferHandleLocked(
944     const StreamBuffer& buffer) {
945   ATRACE_CALL();
946   buffer_handle_t imported_buffer_handle;
947 
948   status_t status = GraphicBufferMapper::get().importBufferNoValidate(
949       buffer.buffer, &imported_buffer_handle);
950   if (status != OK) {
951     ALOGE("%s: Importing buffer failed: %s", __FUNCTION__,
952           ::android::statusToString(status).c_str());
953     return UNKNOWN_ERROR;
954   }
955 
956   BufferCache buffer_cache = {buffer.stream_id, buffer.buffer_id};
957   return AddImportedBufferHandlesLocked(buffer_cache, imported_buffer_handle);
958 }
959 
ImportBufferHandles(const std::vector<StreamBuffer> & buffers)960 status_t CameraDeviceSession::ImportBufferHandles(
961     const std::vector<StreamBuffer>& buffers) {
962   ATRACE_CALL();
963   std::lock_guard<std::mutex> lock(imported_buffer_handle_map_lock_);
964 
965   // Import buffers that are new to HAL.
966   for (auto& buffer : buffers) {
967     bool is_hal_buffer_managed =
968         hal_buffer_managed_stream_ids_.find(buffer.stream_id) !=
969         hal_buffer_managed_stream_ids_.end();
970     // Skip the update if import_hal_buffer_managed_streams doesn't match the
971     //  stream ids hal buffer manager behavior.
972     if (is_hal_buffer_managed) {
973       ALOGV(
974           "%s: Buffer management is enabled. Skip importing buffer for stream "
975           "id"
976           " %d in request ",
977           __FUNCTION__, buffer.stream_id);
978       continue;
979     }
980     if (!IsBufferImportedLocked(buffer.stream_id, buffer.buffer_id)) {
981       status_t res = ImportBufferHandleLocked(buffer);
982 
983       if (res != OK) {
984         ALOGE("%s: Importing buffer %" PRIu64 " from stream %d failed: %s(%d)",
985               __FUNCTION__, buffer.buffer_id, buffer.stream_id, strerror(-res),
986               res);
987         return res;
988       }
989     }
990   }
991 
992   return OK;
993 }
994 
ImportRequestBufferHandles(const CaptureRequest & request)995 status_t CameraDeviceSession::ImportRequestBufferHandles(
996     const CaptureRequest& request) {
997   ATRACE_CALL();
998 
999   status_t res = ImportBufferHandles(request.input_buffers);
1000   if (res != OK) {
1001     ALOGE("%s: Importing input buffer handles failed: %s(%d)", __FUNCTION__,
1002           strerror(-res), res);
1003     return res;
1004   }
1005 
1006   res = ImportBufferHandles(request.output_buffers);
1007   if (res != OK) {
1008     ALOGE("%s: Importing output buffer handles failed: %s(%d)", __FUNCTION__,
1009           strerror(-res), res);
1010     return res;
1011   }
1012 
1013   return OK;
1014 }
1015 
NotifyErrorMessage(uint32_t frame_number,int32_t stream_id,ErrorCode error_code)1016 void CameraDeviceSession::NotifyErrorMessage(uint32_t frame_number,
1017                                              int32_t stream_id,
1018                                              ErrorCode error_code) {
1019   ALOGI("%s: [sbc] Request %d with stream (%d), return error code (%d)",
1020         __FUNCTION__, frame_number, stream_id, error_code);
1021 
1022   if ((error_code == ErrorCode::kErrorResult ||
1023        error_code == ErrorCode::kErrorRequest) &&
1024       stream_id != kInvalidStreamId) {
1025     ALOGW("%s: [sbc] Request %d reset setream id again", __FUNCTION__,
1026           frame_number);
1027     stream_id = kInvalidStreamId;
1028   }
1029   NotifyMessage message = {.type = MessageType::kError,
1030                            .message.error = {.frame_number = frame_number,
1031                                              .error_stream_id = stream_id,
1032                                              .error_code = error_code}};
1033 
1034   std::shared_lock lock(session_callback_lock_);
1035   session_callback_.notify(message);
1036 }
1037 
TryHandlePlaceholderResult(CaptureResult * result,bool * result_handled)1038 status_t CameraDeviceSession::TryHandlePlaceholderResult(CaptureResult* result,
1039                                                          bool* result_handled) {
1040   if (result == nullptr || result_handled == nullptr) {
1041     ALOGE("%s: result or result_handled is nullptr.", __FUNCTION__);
1042     return BAD_VALUE;
1043   }
1044 
1045   uint32_t frame_number = result->frame_number;
1046   *result_handled = false;
1047   bool need_to_handle_result = false;
1048   bool need_to_notify_error_result = false;
1049   {
1050     std::lock_guard<std::mutex> lock(request_record_lock_);
1051     if (error_notified_requests_.find(frame_number) ==
1052         error_notified_requests_.end()) {
1053       for (auto& stream_buffer : result->output_buffers) {
1054         if (placeholder_buffer_observed_.find(stream_buffer.buffer) !=
1055             placeholder_buffer_observed_.end()) {
1056           error_notified_requests_.insert(frame_number);
1057           if (pending_results_.find(frame_number) != pending_results_.end()) {
1058             need_to_notify_error_result = true;
1059             pending_results_.erase(frame_number);
1060             if (ignore_shutters_.find(frame_number) == ignore_shutters_.end()) {
1061               ignore_shutters_.insert(frame_number);
1062             }
1063           }
1064           need_to_handle_result = true;
1065           break;
1066         }
1067       }
1068     } else {
1069       need_to_handle_result = true;
1070     }
1071   }
1072 
1073   if (need_to_notify_error_result) {
1074     NotifyErrorMessage(frame_number, kInvalidStreamId, ErrorCode::kErrorResult);
1075   }
1076 
1077   if (need_to_handle_result) {
1078     for (auto& stream_buffer : result->output_buffers) {
1079       bool is_placeholder_buffer = false;
1080       if (hal_buffer_managed_stream_ids_.find(stream_buffer.stream_id) ==
1081           hal_buffer_managed_stream_ids_.end()) {
1082         // No need to handle non HAL buffer managed streams here
1083         continue;
1084       }
1085       {
1086         std::lock_guard<std::mutex> lock(request_record_lock_);
1087         is_placeholder_buffer =
1088             (placeholder_buffer_observed_.find(stream_buffer.buffer) !=
1089              placeholder_buffer_observed_.end());
1090       }
1091 
1092       uint64_t buffer_id =
1093           (is_placeholder_buffer ? /*Use invalid for placeholder*/ 0
1094                                  : stream_buffer.buffer_id);
1095       // To avoid publishing duplicated error buffer message, only publish
1096       // it here when getting normal buffer status from HWL
1097       if (stream_buffer.status == BufferStatus::kOk) {
1098         NotifyErrorMessage(frame_number, stream_buffer.stream_id,
1099                            ErrorCode::kErrorBuffer);
1100       }
1101       NotifyBufferError(frame_number, stream_buffer.stream_id, buffer_id);
1102     }
1103 
1104     std::vector<StreamBuffer> buffers;
1105     buffers.insert(buffers.end(), result->output_buffers.begin(),
1106                    result->output_buffers.end());
1107 
1108     if (!buffers.empty()) {
1109       if (pending_requests_tracker_->TrackReturnedResultBuffers(buffers) != OK) {
1110         ALOGE("%s: Tracking requested quota buffers failed", __FUNCTION__);
1111       }
1112       std::vector<StreamBuffer> acquired_buffers;
1113       {
1114         std::lock_guard<std::mutex> lock(request_record_lock_);
1115         for (auto& buffer : buffers) {
1116           if (hal_buffer_managed_stream_ids_.find(buffer.stream_id) ==
1117               hal_buffer_managed_stream_ids_.end()) {
1118             // non HAL buffer managed stream buffers are not tracked by pending
1119             // requests tracker
1120             continue;
1121           }
1122           if (placeholder_buffer_observed_.find(buffer.buffer) ==
1123               placeholder_buffer_observed_.end()) {
1124             acquired_buffers.push_back(buffer);
1125           }
1126         }
1127       }
1128 
1129       if (pending_requests_tracker_->TrackReturnedAcquiredBuffers(
1130               acquired_buffers) != OK) {
1131         ALOGE("%s: Tracking requested acquired buffers failed", __FUNCTION__);
1132       }
1133     }
1134   }
1135 
1136   *result_handled = need_to_handle_result;
1137   return OK;
1138 }
1139 
NotifyBufferError(const CaptureRequest & request)1140 void CameraDeviceSession::NotifyBufferError(const CaptureRequest& request) {
1141   ALOGI("%s: [sbc] Return Buffer Error Status for frame %d", __FUNCTION__,
1142         request.frame_number);
1143 
1144   auto result = std::make_unique<CaptureResult>(CaptureResult({}));
1145   result->frame_number = request.frame_number;
1146   for (auto& stream_buffer : request.output_buffers) {
1147     StreamBuffer buffer;
1148     buffer.stream_id = stream_buffer.stream_id;
1149     buffer.status = BufferStatus::kError;
1150     result->output_buffers.push_back(buffer);
1151   }
1152   for (auto& stream_buffer : request.input_buffers) {
1153     result->input_buffers.push_back(stream_buffer);
1154   }
1155   result->partial_result = 1;
1156 
1157   std::shared_lock lock(session_callback_lock_);
1158   session_callback_.process_capture_result(std::move(result));
1159 }
1160 
NotifyBufferError(uint32_t frame_number,int32_t stream_id,uint64_t buffer_id)1161 void CameraDeviceSession::NotifyBufferError(uint32_t frame_number,
1162                                             int32_t stream_id,
1163                                             uint64_t buffer_id) {
1164   ALOGI("%s: [sbc] Return Buffer Error Status for frame %d stream %d",
1165         __FUNCTION__, frame_number, stream_id);
1166 
1167   auto result = std::make_unique<CaptureResult>(CaptureResult({}));
1168   result->frame_number = frame_number;
1169   StreamBuffer stream_buffer;
1170   stream_buffer.buffer_id = buffer_id;
1171   stream_buffer.stream_id = stream_id;
1172   stream_buffer.status = BufferStatus::kError;
1173   result->output_buffers.push_back(stream_buffer);
1174   result->partial_result = 1;
1175 
1176   std::shared_lock lock(session_callback_lock_);
1177   session_callback_.process_capture_result(std::move(result));
1178 }
1179 
HandleSBCInactiveStreams(const CaptureRequest & request,bool * all_active)1180 status_t CameraDeviceSession::HandleSBCInactiveStreams(
1181     const CaptureRequest& request, bool* all_active) {
1182   if (all_active == nullptr) {
1183     ALOGE("%s: all_active is nullptr", __FUNCTION__);
1184     return BAD_VALUE;
1185   }
1186 
1187   *all_active = true;
1188   for (auto& stream_buffer : request.output_buffers) {
1189     bool is_hal_buffer_managed =
1190         hal_buffer_managed_stream_ids_.find(stream_buffer.stream_id) !=
1191         hal_buffer_managed_stream_ids_.end();
1192     if (!is_hal_buffer_managed) {
1193       continue;
1194     }
1195     bool is_active = true;
1196     status_t res = stream_buffer_cache_manager_->IsStreamActive(
1197         stream_buffer.stream_id, &is_active);
1198     if (res != OK) {
1199       ALOGE("%s: Failed to check if stream is active, error status: %s(%d)",
1200             __FUNCTION__, strerror(-res), res);
1201       return UNKNOWN_ERROR;
1202     }
1203     if (!is_active) {
1204       ALOGI("%s: Stream %d is not active when submitting frame %d request.",
1205             __FUNCTION__, stream_buffer.stream_id, request.frame_number);
1206       *all_active = false;
1207       break;
1208     }
1209   }
1210   if (*all_active == false) {
1211     NotifyErrorMessage(request.frame_number, kInvalidStreamId,
1212                        ErrorCode::kErrorRequest);
1213     NotifyBufferError(request);
1214   }
1215 
1216   return OK;
1217 }
1218 
CheckRequestForStreamBufferCacheManager(const CaptureRequest & request,bool * need_to_process)1219 void CameraDeviceSession::CheckRequestForStreamBufferCacheManager(
1220     const CaptureRequest& request, bool* need_to_process) {
1221   ATRACE_CALL();
1222 
1223   // If any stream in the stream buffer cache manager has been labeld as inactive,
1224   // return ERROR_REQUEST immediately. No need to send the request to HWL.
1225   status_t res = HandleSBCInactiveStreams(request, need_to_process);
1226   if (res != OK) {
1227     ALOGE("%s: Failed to check if streams are active.", __FUNCTION__);
1228     return;
1229   }
1230 
1231   // Note: This function should only be called if buffer_management_used_
1232   // is true.
1233   if (pending_request_streams_.empty()) {
1234     pending_requests_tracker_->OnBufferCacheFlushed();
1235   }
1236 
1237   // Add streams into pending_request_streams_
1238   uint32_t frame_number = request.frame_number;
1239   if (*need_to_process) {
1240     std::lock_guard<std::mutex> lock(request_record_lock_);
1241     pending_results_.insert(frame_number);
1242     for (auto& stream_buffer : request.output_buffers) {
1243       bool is_hal_buffer_managed =
1244           hal_buffer_managed_stream_ids_.find(stream_buffer.stream_id) !=
1245           hal_buffer_managed_stream_ids_.end();
1246       if (!is_hal_buffer_managed) {
1247         // pending_request_streams_ tracks only hal buffer managed streams.
1248         continue;
1249       }
1250       if (grouped_stream_id_map_.count(stream_buffer.stream_id) == 1) {
1251         pending_request_streams_[frame_number].insert(
1252             grouped_stream_id_map_.at(stream_buffer.stream_id));
1253       } else {
1254         pending_request_streams_[frame_number].insert(stream_buffer.stream_id);
1255       }
1256     }
1257   }
1258 }
1259 
ValidateRequestLocked(const CaptureRequest & request)1260 status_t CameraDeviceSession::ValidateRequestLocked(
1261     const CaptureRequest& request) {
1262   // First request must have valid settings.
1263   if (!has_valid_settings_) {
1264     if (request.settings == nullptr ||
1265         request.settings->GetCameraMetadataSize() == 0) {
1266       ALOGE("%s: First request must have valid settings", __FUNCTION__);
1267       return BAD_VALUE;
1268     }
1269 
1270     has_valid_settings_ = true;
1271   }
1272 
1273   if (request.output_buffers.empty()) {
1274     ALOGE("%s: there is no output buffer.", __FUNCTION__);
1275     return BAD_VALUE;
1276   }
1277 
1278   // Check all output streams are configured.
1279   for (auto& buffer : request.input_buffers) {
1280     if (configured_streams_map_.find(buffer.stream_id) ==
1281         configured_streams_map_.end()) {
1282       ALOGE("%s: input stream %d is not configured.", __FUNCTION__,
1283             buffer.stream_id);
1284       return BAD_VALUE;
1285     }
1286     const Stream& input_stream = configured_streams_map_.at(buffer.stream_id);
1287     if (!multi_res_reprocess_ && (request.input_width != input_stream.width ||
1288                                   request.input_height != input_stream.height)) {
1289       ALOGE("%s: Invalid input size [%d, %d], expected [%d, %d]", __FUNCTION__,
1290             request.input_width, request.input_height, input_stream.width,
1291             input_stream.height);
1292       return BAD_VALUE;
1293     }
1294   }
1295   if (request.input_buffers.size() > 0) {
1296     if (multi_res_reprocess_ &&
1297         (request.input_width == 0 || request.input_height == 0)) {
1298       ALOGE(
1299           "%s: Session is a multi-res input session, but has invalid input "
1300           "size [%d, %d]",
1301           __FUNCTION__, request.input_width, request.input_height);
1302       return BAD_VALUE;
1303     }
1304   }
1305 
1306   for (auto& buffer : request.output_buffers) {
1307     if (configured_streams_map_.find(buffer.stream_id) ==
1308         configured_streams_map_.end()) {
1309       ALOGE("%s: output stream %d is not configured.", __FUNCTION__,
1310             buffer.stream_id);
1311       return BAD_VALUE;
1312     }
1313   }
1314 
1315   return OK;
1316 }
1317 
ProcessCaptureRequest(const std::vector<CaptureRequest> & requests,uint32_t * num_processed_requests)1318 status_t CameraDeviceSession::ProcessCaptureRequest(
1319     const std::vector<CaptureRequest>& requests,
1320     uint32_t* num_processed_requests) {
1321   ATRACE_CALL();
1322   std::lock_guard<std::mutex> lock(session_lock_);
1323   if (num_processed_requests == nullptr) {
1324     return BAD_VALUE;
1325   }
1326 
1327   if (requests.empty()) {
1328     ALOGE("%s: requests is empty.", __FUNCTION__);
1329     return BAD_VALUE;
1330   }
1331 
1332   status_t res;
1333   *num_processed_requests = 0;
1334 
1335   for (auto& request : requests) {
1336     if (ATRACE_ENABLED()) {
1337       ATRACE_INT("request_frame_number", request.frame_number);
1338     }
1339 
1340     res = ValidateRequestLocked(request);
1341     if (res != OK) {
1342       ALOGE("%s: Request %d is not valid.", __FUNCTION__, request.frame_number);
1343       return res;
1344     }
1345 
1346     res = ImportRequestBufferHandles(request);
1347     if (res != OK) {
1348       ALOGE("%s: Importing request buffer handles failed: %s(%d)", __FUNCTION__,
1349             strerror(-res), res);
1350       return res;
1351     }
1352 
1353     CaptureRequest updated_request;
1354     res = CreateCaptureRequestLocked(request, &updated_request);
1355     if (res != OK) {
1356       ALOGE("%s: Updating buffer handles failed for frame %u", __FUNCTION__,
1357             request.frame_number);
1358       return res;
1359     }
1360 
1361     bool need_to_process = true;
1362     // If a processCaptureRequest() call is made during flushing,
1363     // notify CAMERA3_MSG_ERROR_REQUEST directly.
1364     if (is_flushing_) {
1365       NotifyErrorMessage(request.frame_number, kInvalidStreamId,
1366                          ErrorCode::kErrorRequest);
1367       NotifyBufferError(request);
1368       need_to_process = false;
1369     } else if (hal_buffer_managed_stream_ids_.size() != 0) {
1370       CheckRequestForStreamBufferCacheManager(updated_request, &need_to_process);
1371     }
1372 
1373     if (need_to_process) {
1374       // For HAL buffer managed streams, framework does not throttle requests
1375       // with stream's max buffers. We need to throttle on our own.
1376       std::vector<int32_t> first_requested_stream_ids;
1377 
1378       res = pending_requests_tracker_->WaitAndTrackRequestBuffers(
1379           updated_request, &first_requested_stream_ids);
1380       if (res != OK) {
1381         ALOGE("%s: Waiting until capture ready failed: %s(%d)", __FUNCTION__,
1382               strerror(-res), res);
1383         return res;
1384       }
1385 
1386       for (auto& stream_id : first_requested_stream_ids) {
1387         ALOGI("%s: [sbc] Stream %d 1st req arrived, notify SBC Manager.",
1388               __FUNCTION__, stream_id);
1389         res = stream_buffer_cache_manager_->NotifyProviderReadiness(stream_id);
1390         if (res != OK) {
1391           ALOGE("%s: Notifying provider readiness failed: %s(%d)", __FUNCTION__,
1392                 strerror(-res), res);
1393           return res;
1394         }
1395       }
1396 
1397       // Check the flush status again to prevent flush being called while we are
1398       // waiting for the request buffers(request throttling).
1399       if (is_flushing_) {
1400         std::vector<StreamBuffer> buffers = updated_request.output_buffers;
1401         {
1402           std::lock_guard<std::mutex> request_lock(request_record_lock_);
1403           pending_request_streams_.erase(updated_request.frame_number);
1404           pending_results_.erase(updated_request.frame_number);
1405         }
1406         NotifyErrorMessage(updated_request.frame_number, kInvalidStreamId,
1407                            ErrorCode::kErrorRequest);
1408         NotifyBufferError(updated_request);
1409         if (pending_requests_tracker_->TrackReturnedResultBuffers(buffers) !=
1410             OK) {
1411           ALOGE("%s: Tracking requested quota buffers failed", __FUNCTION__);
1412         }
1413       } else {
1414         std::shared_lock session_lock(capture_session_lock_);
1415         if (capture_session_ == nullptr) {
1416           ALOGE("%s: Capture session wasn't created.", __FUNCTION__);
1417           return NO_INIT;
1418         }
1419 
1420         res = capture_session_->ProcessRequest(updated_request);
1421         if (res != OK) {
1422           ALOGE("%s: Submitting request to HWL session failed: %s (%d)",
1423                 __FUNCTION__, strerror(-res), res);
1424           return res;
1425         }
1426       }
1427     }
1428 
1429     (*num_processed_requests)++;
1430   }
1431 
1432   return OK;
1433 }
1434 
IsBufferImportedLocked(int32_t stream_id,uint32_t buffer_id)1435 bool CameraDeviceSession::IsBufferImportedLocked(int32_t stream_id,
1436                                                  uint32_t buffer_id) {
1437   BufferCache buffer_cache = {stream_id, buffer_id};
1438   return imported_buffer_handle_map_.find(buffer_cache) !=
1439          imported_buffer_handle_map_.end();
1440 }
1441 
AddImportedBufferHandlesLocked(const BufferCache & buffer_cache,buffer_handle_t buffer_handle)1442 status_t CameraDeviceSession::AddImportedBufferHandlesLocked(
1443     const BufferCache& buffer_cache, buffer_handle_t buffer_handle) {
1444   ATRACE_CALL();
1445   auto buffer_handle_it = imported_buffer_handle_map_.find(buffer_cache);
1446   if (buffer_handle_it == imported_buffer_handle_map_.end()) {
1447     // Add a new buffer cache if it doesn't exist.
1448     imported_buffer_handle_map_.emplace(buffer_cache, buffer_handle);
1449   } else if (buffer_handle_it->second != buffer_handle) {
1450     ALOGE(
1451         "%s: Cached buffer handle %p doesn't match %p for stream %u buffer "
1452         "%" PRIu64,
1453         __FUNCTION__, buffer_handle_it->second, buffer_handle,
1454         buffer_cache.stream_id, buffer_cache.buffer_id);
1455     return BAD_VALUE;
1456   }
1457 
1458   return OK;
1459 }
1460 
RemoveBufferCache(const std::vector<BufferCache> & buffer_caches)1461 void CameraDeviceSession::RemoveBufferCache(
1462     const std::vector<BufferCache>& buffer_caches) {
1463   ATRACE_CALL();
1464   std::lock_guard<std::mutex> lock(imported_buffer_handle_map_lock_);
1465 
1466   for (auto& buffer_cache : buffer_caches) {
1467     auto buffer_handle_it = imported_buffer_handle_map_.find(buffer_cache);
1468     if (buffer_handle_it == imported_buffer_handle_map_.end()) {
1469       ALOGW("%s: Could not find buffer cache for stream %u buffer %" PRIu64,
1470             __FUNCTION__, buffer_cache.stream_id, buffer_cache.buffer_id);
1471       continue;
1472     }
1473 
1474     device_session_hwl_->RemoveCachedBuffers(buffer_handle_it->second);
1475 
1476     status_t res =
1477         GraphicBufferMapper::get().freeBuffer(buffer_handle_it->second);
1478     if (res != OK) {
1479       ALOGE("%s: Freeing imported buffer failed: %s", __FUNCTION__,
1480             ::android::statusToString(res).c_str());
1481     }
1482 
1483     imported_buffer_handle_map_.erase(buffer_handle_it);
1484   }
1485 }
1486 
FreeBufferHandlesLocked(int32_t stream_id)1487 void CameraDeviceSession::FreeBufferHandlesLocked(int32_t stream_id) {
1488   for (auto buffer_handle_it = imported_buffer_handle_map_.begin();
1489        buffer_handle_it != imported_buffer_handle_map_.end();) {
1490     if (buffer_handle_it->first.stream_id == stream_id) {
1491       status_t res =
1492           GraphicBufferMapper::get().freeBuffer(buffer_handle_it->second);
1493       if (res != OK) {
1494         ALOGE("%s: Freeing imported buffer failed: %s", __FUNCTION__,
1495               ::android::statusToString(res).c_str());
1496       }
1497       buffer_handle_it = imported_buffer_handle_map_.erase(buffer_handle_it);
1498     } else {
1499       buffer_handle_it++;
1500     }
1501   }
1502 }
1503 
FreeImportedBufferHandles()1504 void CameraDeviceSession::FreeImportedBufferHandles() {
1505   ATRACE_CALL();
1506   std::lock_guard<std::mutex> lock(imported_buffer_handle_map_lock_);
1507 
1508   auto& mapper = GraphicBufferMapper::get();
1509   for (auto buffer_handle_it : imported_buffer_handle_map_) {
1510     status_t status = mapper.freeBuffer(buffer_handle_it.second);
1511     if (status != OK) {
1512       ALOGE("%s: Freeing imported buffer failed: %s", __FUNCTION__,
1513             ::android::statusToString(status).c_str());
1514     }
1515   }
1516 
1517   imported_buffer_handle_map_.clear();
1518 }
1519 
CleanupStaleStreamsLocked(const std::vector<Stream> & new_streams)1520 void CameraDeviceSession::CleanupStaleStreamsLocked(
1521     const std::vector<Stream>& new_streams) {
1522   for (auto stream_it = configured_streams_map_.begin();
1523        stream_it != configured_streams_map_.end();) {
1524     int32_t stream_id = stream_it->first;
1525     bool found = false;
1526     for (const Stream& stream : new_streams) {
1527       if (stream.id == stream_id) {
1528         found = true;
1529         break;
1530       }
1531     }
1532     if (!found) {
1533       std::lock_guard<std::mutex> lock(imported_buffer_handle_map_lock_);
1534       stream_it = configured_streams_map_.erase(stream_it);
1535       FreeBufferHandlesLocked(stream_id);
1536     } else {
1537       stream_it++;
1538     }
1539   }
1540 }
1541 
Flush()1542 status_t CameraDeviceSession::Flush() {
1543   ATRACE_CALL();
1544   std::shared_lock lock(capture_session_lock_);
1545   if (capture_session_ == nullptr) {
1546     return OK;
1547   }
1548 
1549   is_flushing_ = true;
1550   status_t res = capture_session_->Flush();
1551   stream_buffer_cache_manager_->NotifyFlushingAll();
1552   is_flushing_ = false;
1553 
1554   return res;
1555 }
1556 
RepeatingRequestEnd(int32_t frame_number,const std::vector<int32_t> & stream_ids)1557 void CameraDeviceSession::RepeatingRequestEnd(
1558     int32_t frame_number, const std::vector<int32_t>& stream_ids) {
1559   ATRACE_CALL();
1560   std::shared_lock lock(capture_session_lock_);
1561   if (capture_session_ != nullptr) {
1562     capture_session_->RepeatingRequestEnd(frame_number, stream_ids);
1563   }
1564 }
1565 
AppendOutputIntentToSettingsLocked(const CaptureRequest & request,CaptureRequest * updated_request)1566 void CameraDeviceSession::AppendOutputIntentToSettingsLocked(
1567     const CaptureRequest& request, CaptureRequest* updated_request) {
1568   if (updated_request == nullptr || updated_request->settings == nullptr) {
1569     // The frameworks may have no settings and just do nothing here.
1570     return;
1571   }
1572 
1573   bool has_video = false;
1574   bool has_snapshot = false;
1575   bool has_zsl = false;
1576 
1577   // From request output_buffers to find stream id and then find the stream.
1578   for (auto& buffer : request.output_buffers) {
1579     auto stream = configured_streams_map_.find(buffer.stream_id);
1580     if (stream != configured_streams_map_.end()) {
1581       if (utils::IsVideoStream(stream->second)) {
1582         has_video = true;
1583       } else if (utils::IsJPEGSnapshotStream(stream->second)) {
1584         has_snapshot = true;
1585       }
1586     }
1587   }
1588 
1589   for (auto& buffer : request.input_buffers) {
1590     auto stream = configured_streams_map_.find(buffer.stream_id);
1591     if (stream != configured_streams_map_.end()) {
1592       if ((stream->second.usage & GRALLOC_USAGE_HW_CAMERA_ZSL) != 0) {
1593         has_zsl = true;
1594         break;
1595       }
1596     }
1597   }
1598 
1599   uint8_t output_intent = static_cast<uint8_t>(OutputIntent::kPreview);
1600 
1601   if (has_video && has_snapshot) {
1602     output_intent = static_cast<uint8_t>(OutputIntent::kVideoSnapshot);
1603   } else if (has_snapshot) {
1604     output_intent = static_cast<uint8_t>(OutputIntent::kSnapshot);
1605   } else if (has_video) {
1606     output_intent = static_cast<uint8_t>(OutputIntent::kVideo);
1607   } else if (has_zsl) {
1608     output_intent = static_cast<uint8_t>(OutputIntent::kZsl);
1609   }
1610 
1611   // Used to indicate the possible start and end of video recording in traces
1612   if (has_video && !prev_output_intent_has_video_) {
1613     ATRACE_NAME("Start Video Streaming");
1614   } else if (prev_output_intent_has_video_ && !has_video) {
1615     ATRACE_NAME("Stop Video Streaming");
1616   }
1617 
1618   prev_output_intent_has_video_ = has_video;
1619 
1620   status_t res = updated_request->settings->Set(VendorTagIds::kOutputIntent,
1621                                                 &output_intent,
1622                                                 /*data_count=*/1);
1623   if (res != OK) {
1624     ALOGE("%s: Failed to set vendor tag OutputIntent: %s(%d).", __FUNCTION__,
1625           strerror(-res), res);
1626   }
1627 }
1628 
IsReconfigurationRequired(const HalCameraMetadata * old_session,const HalCameraMetadata * new_session,bool * reconfiguration_required)1629 status_t CameraDeviceSession::IsReconfigurationRequired(
1630     const HalCameraMetadata* old_session, const HalCameraMetadata* new_session,
1631     bool* reconfiguration_required) {
1632   if (old_session == nullptr || new_session == nullptr ||
1633       reconfiguration_required == nullptr) {
1634     ALOGE(
1635         "%s: old_session or new_session or reconfiguration_required is "
1636         "nullptr.",
1637         __FUNCTION__);
1638     return BAD_VALUE;
1639   }
1640 
1641   return device_session_hwl_->IsReconfigurationRequired(
1642       old_session, new_session, reconfiguration_required);
1643 }
1644 
UpdateRequestedBufferHandles(std::vector<StreamBuffer> * buffers)1645 status_t CameraDeviceSession::UpdateRequestedBufferHandles(
1646     std::vector<StreamBuffer>* buffers) {
1647   if (buffers == nullptr) {
1648     ALOGE("%s: buffer is nullptr.", __FUNCTION__);
1649     return BAD_VALUE;
1650   }
1651 
1652   std::lock_guard<std::mutex> lock(imported_buffer_handle_map_lock_);
1653 
1654   status_t res;
1655   for (auto& buffer : *buffers) {
1656     // If buffer handle is not nullptr, we need to add the new buffer handle
1657     // to buffer cache.
1658     if (buffer.buffer != nullptr) {
1659       BufferCache buffer_cache = {buffer.stream_id, buffer.buffer_id};
1660       res = AddImportedBufferHandlesLocked(buffer_cache, buffer.buffer);
1661       if (res != OK) {
1662         ALOGE("%s: Adding imported buffer handle failed: %s(%d)", __FUNCTION__,
1663               strerror(-res), res);
1664         return res;
1665       }
1666     }
1667   }
1668 
1669   res = UpdateBufferHandlesLocked(buffers,
1670                                   /*update_hal_buffer_managed_streams=*/true);
1671   if (res != OK) {
1672     ALOGE("%s: Updating output buffer handles failed: %s(%d)", __FUNCTION__,
1673           strerror(-res), res);
1674     return res;
1675   }
1676 
1677   return OK;
1678 }
1679 
RegisterStreamsIntoCacheManagerLocked(const StreamConfiguration & stream_config,const std::vector<HalStream> & hal_streams)1680 status_t CameraDeviceSession::RegisterStreamsIntoCacheManagerLocked(
1681     const StreamConfiguration& stream_config,
1682     const std::vector<HalStream>& hal_streams) {
1683   ATRACE_CALL();
1684 
1685   for (auto& stream : stream_config.streams) {
1686     uint64_t producer_usage = 0;
1687     uint64_t consumer_usage = 0;
1688     int32_t stream_id = -1;
1689     android_pixel_format_t stream_format = stream.format;
1690     for (auto& hal_stream : hal_streams) {
1691       if (hal_stream.id == stream.id) {
1692         producer_usage = hal_stream.producer_usage;
1693         consumer_usage = hal_stream.consumer_usage;
1694         stream_id = hal_stream.id;
1695         if (stream_format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
1696           stream_format = hal_stream.override_format;
1697         }
1698       }
1699     }
1700     if (stream_id == -1) {
1701       ALOGE("%s: Could not fine framework stream in hal configured stream list",
1702             __FUNCTION__);
1703       return UNKNOWN_ERROR;
1704     }
1705     // Input stream buffers are always allocated by the camera service, not by
1706     // request_stream_buffers() callback from the HAL.
1707     if (stream.stream_type != StreamType::kOutput) {
1708       continue;
1709     }
1710 
1711     // The stream is not HAL buffer managed, so no need to register with SBC.
1712     if (hal_buffer_managed_stream_ids_.find(stream_id) ==
1713         hal_buffer_managed_stream_ids_.end()) {
1714       continue;
1715     }
1716     StreamBufferRequestFunc session_request_func = StreamBufferRequestFunc(
1717         [this, stream_id](uint32_t num_buffer,
1718                           std::vector<StreamBuffer>* buffers,
1719                           StreamBufferRequestError* status) -> status_t {
1720           ATRACE_NAME("StreamBufferRequestFunc");
1721           if (buffers == nullptr) {
1722             ALOGE("%s: buffers is nullptr.", __FUNCTION__);
1723             return BAD_VALUE;
1724           }
1725 
1726           if (num_buffer == 0) {
1727             ALOGE("%s: num_buffer is 0", __FUNCTION__);
1728             return BAD_VALUE;
1729           }
1730 
1731           if (status == nullptr) {
1732             ALOGE("%s: status is nullptr.", __FUNCTION__);
1733             return BAD_VALUE;
1734           }
1735 
1736           return RequestStreamBuffers(stream_id, num_buffer, buffers, status);
1737         });
1738 
1739     StreamBufferReturnFunc session_return_func = StreamBufferReturnFunc(
1740         [this](const std::vector<StreamBuffer>& buffers) -> status_t {
1741           ReturnStreamBuffers(buffers);
1742 
1743           for (auto& stream_buffer : buffers) {
1744             ALOGI("%s: [sbc] Flushed buf[%p] bid[%" PRIu64 "] strm[%d] frm[xx]",
1745                   __FUNCTION__, stream_buffer.buffer, stream_buffer.buffer_id,
1746                   stream_buffer.stream_id);
1747           }
1748 
1749           return OK;
1750         });
1751 
1752     StreamBufferCacheRegInfo reg_info = {.request_func = session_request_func,
1753                                          .return_func = session_return_func,
1754                                          .stream_id = stream_id,
1755                                          .width = stream.width,
1756                                          .height = stream.height,
1757                                          .format = stream_format,
1758                                          .producer_flags = producer_usage,
1759                                          .consumer_flags = consumer_usage,
1760                                          .num_buffers_to_cache = 1};
1761 
1762     status_t res = stream_buffer_cache_manager_->RegisterStream(reg_info);
1763     if (res != OK) {
1764       ALOGE(
1765           "%s: Failed to register stream into stream buffer cache manager, "
1766           "error status: %s(%d)",
1767           __FUNCTION__, strerror(-res), res);
1768       return UNKNOWN_ERROR;
1769     }
1770     ALOGI("%s: [sbc] Registered stream %d into SBC manager.", __FUNCTION__,
1771           stream.id);
1772   }
1773 
1774   return OK;
1775 }
1776 
RequestBuffersFromStreamBufferCacheManager(int32_t stream_id,uint32_t num_buffers,std::vector<StreamBuffer> * buffers,uint32_t frame_number)1777 status_t CameraDeviceSession::RequestBuffersFromStreamBufferCacheManager(
1778     int32_t stream_id, uint32_t num_buffers, std::vector<StreamBuffer>* buffers,
1779     uint32_t frame_number) {
1780   if (num_buffers != 1) {
1781     ALOGE(
1782         "%s: Only one buffer per request can be handled now. num_buffers = %d",
1783         __FUNCTION__, num_buffers);
1784     // TODO(b/127988765): handle multiple buffers from multiple streams if
1785     //                    HWL needs this feature.
1786     return BAD_VALUE;
1787   }
1788 
1789   StreamBufferRequestResult buffer_request_result;
1790 
1791   status_t res = this->stream_buffer_cache_manager_->GetStreamBuffer(
1792       stream_id, &buffer_request_result);
1793   if (res != OK) {
1794     ALOGE(
1795         "%s: Failed to get stream buffer from SBC manager, error status: "
1796         "%s(%d).",
1797         __FUNCTION__, strerror(-res), res);
1798     return UNKNOWN_ERROR;
1799   }
1800 
1801   // This function fulfills requests from lower HAL level. It is hard for some
1802   // implementation of lower HAL level to handle the case of a request failure.
1803   // In case a framework buffer can not be delivered to the lower level, a
1804   // placeholder buffer will be returned by the stream buffer cache manager. The
1805   // client at lower level can use that placeholder buffer as a normal buffer
1806   // for writing and so forth. But that buffer will not be returned to the
1807   // framework. This avoids the troublesome for lower level to handle such
1808   // situation. An ERROR_REQUEST needs to be returned to the framework according
1809   // to
1810   // ::android::hardware::camera::device::V3_5::StreamBufferRequestError.
1811   if (buffer_request_result.is_placeholder_buffer) {
1812     ALOGI("%s: [sbc] Placeholder buffer returned for stream: %d, frame: %d",
1813           __FUNCTION__, stream_id, frame_number);
1814     {
1815       std::lock_guard<std::mutex> lock(request_record_lock_);
1816       placeholder_buffer_observed_.insert(buffer_request_result.buffer.buffer);
1817     }
1818   }
1819 
1820   ALOGV("%s: [sbc] => HWL Acquired buf[%p] buf_id[%" PRIu64
1821         "] strm[%d] frm[%u] placeholder[%d]",
1822         __FUNCTION__, buffer_request_result.buffer.buffer,
1823         buffer_request_result.buffer.buffer_id, stream_id, frame_number,
1824         buffer_request_result.is_placeholder_buffer);
1825 
1826   buffers->push_back(buffer_request_result.buffer);
1827   return OK;
1828 }
1829 
RequestStreamBuffers(int32_t stream_id,uint32_t num_buffers,std::vector<StreamBuffer> * buffers,StreamBufferRequestError * request_status)1830 status_t CameraDeviceSession::RequestStreamBuffers(
1831     int32_t stream_id, uint32_t num_buffers, std::vector<StreamBuffer>* buffers,
1832     StreamBufferRequestError* request_status) {
1833   if (buffers == nullptr) {
1834     ALOGE("%s: buffers is nullptr", __FUNCTION__);
1835     return BAD_VALUE;
1836   }
1837 
1838   if (num_buffers == 0) {
1839     ALOGE("%s: num_buffers is 0", __FUNCTION__);
1840     return BAD_VALUE;
1841   }
1842 
1843   if (request_status == nullptr) {
1844     ALOGE("%s: request_status is nullptr", __FUNCTION__);
1845     return BAD_VALUE;
1846   }
1847 
1848   *request_status = StreamBufferRequestError::kOk;
1849   status_t res = pending_requests_tracker_->WaitAndTrackAcquiredBuffers(
1850       stream_id, num_buffers);
1851   if (res != OK) {
1852     ALOGW("%s: Waiting until available buffer failed: %s(%d)", __FUNCTION__,
1853           strerror(-res), res);
1854     *request_status = StreamBufferRequestError::kNoBufferAvailable;
1855     return res;
1856   }
1857 
1858   std::vector<BufferReturn> buffer_returns;
1859   std::vector<BufferRequest> buffer_requests = {{
1860       .stream_id = stream_id,
1861       .num_buffers_requested = num_buffers,
1862   }};
1863 
1864   BufferRequestStatus status = BufferRequestStatus::kOk;
1865   {
1866     int64_t start_timestamp;
1867     std::shared_lock lock(session_callback_lock_);
1868     if (measure_buffer_allocation_time_) {
1869       struct timespec start_time;
1870       if (clock_gettime(CLOCK_BOOTTIME, &start_time)) {
1871         ALOGE("%s: Getting start_time failed.", __FUNCTION__);
1872       } else {
1873         start_timestamp = start_time.tv_sec * kNsPerSec + start_time.tv_nsec;
1874       }
1875     }
1876     status = session_callback_.request_stream_buffers(buffer_requests,
1877                                                       &buffer_returns);
1878     if (measure_buffer_allocation_time_) {
1879       int64_t end_timestamp;
1880       struct timespec end_time;
1881       if (clock_gettime(CLOCK_BOOTTIME, &end_time)) {
1882         ALOGE("%s: Getting end_time failed.", __FUNCTION__);
1883       } else {
1884         end_timestamp = end_time.tv_sec * kNsPerSec + end_time.tv_nsec;
1885         int64_t elapsed_timestamp = end_timestamp - start_timestamp;
1886         if (elapsed_timestamp > kAllocationThreshold) {
1887           ALOGW("%s: buffer allocation time: %" PRIu64 " ms", __FUNCTION__,
1888                 elapsed_timestamp / 1000000);
1889         }
1890       }
1891     }
1892   }
1893 
1894   // need this information when status is not kOk
1895   if (buffer_returns.size() > 0) {
1896     *request_status = buffer_returns[0].val.error;
1897   }
1898 
1899   if (status != BufferRequestStatus::kOk || buffer_returns.size() != 1) {
1900     ALOGW(
1901         "%s: Requesting stream buffer failed. (buffer_returns has %zu "
1902         "entries; status is %s(%d)).",
1903         __FUNCTION__, buffer_returns.size(), strerror(-res), status);
1904     for (auto& buffer_return : buffer_returns) {
1905       ALOGI("%s: stream %d, buffer request error %d", __FUNCTION__,
1906             buffer_return.stream_id, buffer_return.val.error);
1907     }
1908     pending_requests_tracker_->TrackBufferAcquisitionFailure(stream_id,
1909                                                              num_buffers);
1910     pending_requests_tracker_->DumpStatus();
1911     // TODO(b/129362905): Return partial buffers.
1912     return UNKNOWN_ERROR;
1913   }
1914 
1915   *buffers = buffer_returns[0].val.buffers;
1916 
1917   res = UpdateRequestedBufferHandles(buffers);
1918   if (res != OK) {
1919     ALOGE("%s: Updating requested buffer handles failed: %s(%d).", __FUNCTION__,
1920           strerror(-res), res);
1921     // TODO(b/129362905): Return partial buffers.
1922     return res;
1923   }
1924 
1925   ALOGV("%s: [sbc] => CDS Acquired buf[%p] buf_id[%" PRIu64 "] strm[%d]",
1926         __FUNCTION__, buffers->at(0).buffer, buffers->at(0).buffer_id,
1927         stream_id);
1928 
1929   return OK;
1930 }
1931 
ReturnStreamBuffers(const std::vector<StreamBuffer> & buffers)1932 void CameraDeviceSession::ReturnStreamBuffers(
1933     const std::vector<StreamBuffer>& buffers) {
1934   {
1935     std::shared_lock lock(session_callback_lock_);
1936     session_callback_.return_stream_buffers(buffers);
1937   }
1938 
1939   for (auto& stream_buffer : buffers) {
1940     ALOGV("%s: [sbc] <= Return extra buf[%p], bid[%" PRIu64 "], strm[%d]",
1941           __FUNCTION__, stream_buffer.buffer, stream_buffer.buffer_id,
1942           stream_buffer.stream_id);
1943   }
1944 
1945   if (pending_requests_tracker_->TrackReturnedAcquiredBuffers(buffers) != OK) {
1946     ALOGE("%s: Tracking requested buffers failed.", __FUNCTION__);
1947   }
1948 }
1949 
1950 std::unique_ptr<google::camera_common::Profiler>
GetProfiler(uint32_t camera_id,int option)1951 CameraDeviceSession::GetProfiler(uint32_t camera_id, int option) {
1952   return device_session_hwl_->GetProfiler(camera_id, option);
1953 }
1954 
TryHandleCaptureResult(std::unique_ptr<CaptureResult> & result)1955 bool CameraDeviceSession::TryHandleCaptureResult(
1956     std::unique_ptr<CaptureResult>& result) {
1957   if (result == nullptr) {
1958     ALOGE("%s: result is nullptr", __FUNCTION__);
1959     return true;
1960   }
1961   zoom_ratio_mapper_.UpdateCaptureResult(result.get());
1962 
1963   status_t res = UpdatePendingRequest(result.get());
1964   if (res != OK) {
1965     ALOGE("%s: Updating inflight requests/streams failed: %s(%d)", __FUNCTION__,
1966           strerror(-res), res);
1967     return true;
1968   }
1969 
1970   for (auto& stream_buffer : result->output_buffers) {
1971     ALOGV("%s: [sbc] <= Return result output buf[%p], bid[%" PRIu64
1972           "], strm[%d], frm[%u]",
1973           __FUNCTION__, stream_buffer.buffer, stream_buffer.buffer_id,
1974           stream_buffer.stream_id, result->frame_number);
1975   }
1976   for (auto& stream_buffer : result->input_buffers) {
1977     ALOGV("%s: [sbc] <= Return result input buf[%p], bid[%" PRIu64
1978           "], strm[%d], frm[%u]",
1979           __FUNCTION__, stream_buffer.buffer, stream_buffer.buffer_id,
1980           stream_buffer.stream_id, result->frame_number);
1981   }
1982 
1983   // If there is placeholder buffer or a placeholder buffer has been observed of
1984   // this frame, handle the capture result specifically.
1985   bool result_handled = false;
1986   res = TryHandlePlaceholderResult(result.get(), &result_handled);
1987   if (res != OK) {
1988     ALOGE("%s: Failed to handle placeholder result.", __FUNCTION__);
1989     return true;
1990   }
1991   return result_handled;
1992 }
1993 
TrackReturnedBuffers(const std::vector<StreamBuffer> & buffers)1994 void CameraDeviceSession::TrackReturnedBuffers(
1995     const std::vector<StreamBuffer>& buffers) {
1996   if (!buffers.empty()) {
1997     if (pending_requests_tracker_->TrackReturnedAcquiredBuffers(buffers) != OK) {
1998       ALOGE("%s: Tracking requested acquired buffers failed", __FUNCTION__);
1999     }
2000     if (pending_requests_tracker_->TrackReturnedResultBuffers(buffers) != OK) {
2001       ALOGE("%s: Tracking requested quota buffers failed", __FUNCTION__);
2002     }
2003   }
2004 }
2005 
2006 }  // namespace google_camera_hal
2007 }  // namespace android
2008