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