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_MultiCameraRtProcessBlock"
19 #define ATRACE_TAG ATRACE_TAG_CAMERA
20 #include <log/log.h>
21 #include <utils/Trace.h>
22 
23 #include <unordered_set>
24 
25 #include "hal_utils.h"
26 #include "multicam_realtime_process_block.h"
27 #include "result_processor.h"
28 
29 namespace android {
30 namespace google_camera_hal {
31 
Create(CameraDeviceSessionHwl * device_session_hwl)32 std::unique_ptr<MultiCameraRtProcessBlock> MultiCameraRtProcessBlock::Create(
33     CameraDeviceSessionHwl* device_session_hwl) {
34   ATRACE_CALL();
35   if (!IsSupported(device_session_hwl)) {
36     ALOGE("%s: Not supported.", __FUNCTION__);
37     return nullptr;
38   }
39 
40   auto block = std::unique_ptr<MultiCameraRtProcessBlock>(
41       new MultiCameraRtProcessBlock(device_session_hwl));
42   if (block == nullptr) {
43     ALOGE("%s: Creating MultiCameraRtProcessBlock failed.", __FUNCTION__);
44     return nullptr;
45   }
46   block->request_id_manager_ = PipelineRequestIdManager::Create();
47   if (block->request_id_manager_ == nullptr) {
48     ALOGE("%s: Creating PipelineRequestIdManager failed.", __FUNCTION__);
49     return nullptr;
50   }
51   return block;
52 }
53 
IsSupported(CameraDeviceSessionHwl * device_session_hwl)54 bool MultiCameraRtProcessBlock::IsSupported(
55     CameraDeviceSessionHwl* device_session_hwl) {
56   ATRACE_CALL();
57   if (device_session_hwl == nullptr) {
58     ALOGE("%s: device_session_hwl is nullptr", __FUNCTION__);
59     return false;
60   }
61 
62   if (device_session_hwl->GetPhysicalCameraIds().size() <= 1) {
63     ALOGE("%s: Only support multiple physical cameras", __FUNCTION__);
64     return false;
65   }
66 
67   return true;
68 }
69 
MultiCameraRtProcessBlock(CameraDeviceSessionHwl * device_session_hwl)70 MultiCameraRtProcessBlock::MultiCameraRtProcessBlock(
71     CameraDeviceSessionHwl* device_session_hwl)
72     : kCameraId(device_session_hwl->GetCameraId()),
73       device_session_hwl_(device_session_hwl) {
74   hwl_pipeline_callback_.process_pipeline_result = HwlProcessPipelineResultFunc(
75       [this](std::unique_ptr<HwlPipelineResult> result) {
76         NotifyHwlPipelineResult(std::move(result));
77       });
78 
79   hwl_pipeline_callback_.notify = NotifyHwlPipelineMessageFunc(
80       [this](uint32_t pipeline_id, const NotifyMessage& message) {
81         NotifyHwlPipelineMessage(pipeline_id, message);
82       });
83 }
84 
SetResultProcessor(std::unique_ptr<ResultProcessor> result_processor)85 status_t MultiCameraRtProcessBlock::SetResultProcessor(
86     std::unique_ptr<ResultProcessor> result_processor) {
87   ATRACE_CALL();
88   if (result_processor == nullptr) {
89     ALOGE("%s: result_processor is nullptr", __FUNCTION__);
90     return BAD_VALUE;
91   }
92 
93   std::lock_guard<std::mutex> lock(result_processor_mutex_);
94   if (result_processor_ != nullptr) {
95     ALOGE("%s: result_processor_ was already set.", __FUNCTION__);
96     return ALREADY_EXISTS;
97   }
98 
99   result_processor_ = std::move(result_processor);
100   return OK;
101 }
102 
GetCameraStreamConfigurationMap(const StreamConfiguration & stream_config,CameraStreamConfigurationMap * camera_stream_config_map) const103 status_t MultiCameraRtProcessBlock::GetCameraStreamConfigurationMap(
104     const StreamConfiguration& stream_config,
105     CameraStreamConfigurationMap* camera_stream_config_map) const {
106   if (camera_stream_config_map == nullptr) {
107     ALOGE("%s: camera_stream_config_map is nullptr", __FUNCTION__);
108     return BAD_VALUE;
109   }
110 
111   // Create one stream configuration for each camera.
112   camera_stream_config_map->clear();
113   for (auto& stream : stream_config.streams) {
114     if (stream.stream_type != StreamType::kOutput ||
115         !stream.is_physical_camera_stream) {
116       ALOGE("%s: Only physical output streams are supported.", __FUNCTION__);
117       return BAD_VALUE;
118     }
119 
120     (*camera_stream_config_map)[stream.physical_camera_id].streams.push_back(
121         stream);
122   }
123 
124   // Copy the rest of the stream configuration fields
125   for (auto& [camera_id, config] : *camera_stream_config_map) {
126     config.operation_mode = stream_config.operation_mode;
127     config.session_params =
128         HalCameraMetadata::Clone(stream_config.session_params.get());
129     config.stream_config_counter = stream_config.stream_config_counter;
130   }
131 
132   return OK;
133 }
134 
ConfigureStreams(const StreamConfiguration & stream_config,const StreamConfiguration & overall_config)135 status_t MultiCameraRtProcessBlock::ConfigureStreams(
136     const StreamConfiguration& stream_config,
137     const StreamConfiguration& overall_config) {
138   ATRACE_CALL();
139   std::lock_guard lock(configure_shared_mutex_);
140   if (is_configured_) {
141     ALOGE("%s: Already configured.", __FUNCTION__);
142     return ALREADY_EXISTS;
143   }
144 
145   CameraStreamConfigurationMap camera_stream_configs;
146   status_t res =
147       GetCameraStreamConfigurationMap(stream_config, &camera_stream_configs);
148   if (res != OK) {
149     ALOGE("%s: Failed to get camera stream config map: %s(%d)", __FUNCTION__,
150           strerror(-res), res);
151     return res;
152   }
153 
154   configured_streams_.clear();
155   camera_pipeline_ids_.clear();
156 
157   // Configuration a pipeline for each camera.
158   for (auto& [camera_id, config] : camera_stream_configs) {
159     uint32_t pipeline_id = 0;
160     res = device_session_hwl_->ConfigurePipeline(
161         camera_id, hwl_pipeline_callback_, config, overall_config, &pipeline_id);
162     if (res != OK) {
163       ALOGE("%s: Configuring stream for camera %u failed: %s(%d)", __FUNCTION__,
164             camera_id, strerror(-res), res);
165       return res;
166     }
167     ALOGV("%s: config realtime pipeline camera id %u pipeline_id %u",
168           __FUNCTION__, camera_id, pipeline_id);
169 
170     camera_pipeline_ids_[camera_id] = pipeline_id;
171     for (auto& stream : config.streams) {
172       configured_streams_[stream.id].pipeline_id = pipeline_id;
173       configured_streams_[stream.id].stream = stream;
174     }
175   }
176 
177   is_configured_ = true;
178   return OK;
179 }
180 
GetConfiguredHalStreams(std::vector<HalStream> * hal_streams) const181 status_t MultiCameraRtProcessBlock::GetConfiguredHalStreams(
182     std::vector<HalStream>* hal_streams) const {
183   ATRACE_CALL();
184   std::lock_guard lock(configure_shared_mutex_);
185   if (hal_streams == nullptr) {
186     ALOGE("%s: hal_streams is nullptr.", __FUNCTION__);
187     return BAD_VALUE;
188   }
189 
190   if (!is_configured_) {
191     ALOGE("%s: Not configured yet.", __FUNCTION__);
192     return NO_INIT;
193   }
194 
195   hal_streams->clear();
196   for (auto& [camera_id, pipeline_id] : camera_pipeline_ids_) {
197     std::vector<HalStream> pipeline_hal_stream;
198     status_t res = device_session_hwl_->GetConfiguredHalStream(
199         pipeline_id, &pipeline_hal_stream);
200     if (res != OK) {
201       ALOGE("%s: Getting configured HAL streams for pipeline %u failed: %s(%d)",
202             __FUNCTION__, pipeline_id, strerror(-res), res);
203       return res;
204     }
205 
206     hal_streams->insert(hal_streams->end(), pipeline_hal_stream.begin(),
207                         pipeline_hal_stream.end());
208   }
209 
210   return OK;
211 }
212 
GetBufferPhysicalCameraIdLocked(const StreamBuffer & buffer,uint32_t * camera_id) const213 status_t MultiCameraRtProcessBlock::GetBufferPhysicalCameraIdLocked(
214     const StreamBuffer& buffer, uint32_t* camera_id) const {
215   if (camera_id == nullptr) {
216     ALOGE("%s: camera_id is nullptr", __FUNCTION__);
217     return BAD_VALUE;
218   }
219 
220   int32_t stream_id = buffer.stream_id;
221   auto configured_stream_iter = configured_streams_.find(stream_id);
222   if (configured_stream_iter == configured_streams_.end()) {
223     ALOGE("%s: Stream %d was not configured.", __FUNCTION__, stream_id);
224     return BAD_VALUE;
225   }
226 
227   const ConfiguredStream& configure_stream = configured_stream_iter->second;
228   if (!configure_stream.stream.is_physical_camera_stream) {
229     ALOGE("%s: Stream %d is not a physical stream.", __FUNCTION__, stream_id);
230     return BAD_VALUE;
231   }
232 
233   *camera_id = configure_stream.stream.physical_camera_id;
234   return OK;
235 }
236 
GetOutputBufferPipelineIdLocked(const StreamBuffer & buffer,uint32_t * pipeline_id) const237 status_t MultiCameraRtProcessBlock::GetOutputBufferPipelineIdLocked(
238     const StreamBuffer& buffer, uint32_t* pipeline_id) const {
239   if (pipeline_id == nullptr) {
240     ALOGE("%s: pipeline_id is nullptr", __FUNCTION__);
241     return BAD_VALUE;
242   }
243 
244   uint32_t camera_id;
245   status_t res = GetBufferPhysicalCameraIdLocked(buffer, &camera_id);
246   if (res != OK) {
247     ALOGE("%s: Getting buffer's physical camera ID failed: %s(%d)",
248           __FUNCTION__, strerror(-res), res);
249     return res;
250   }
251 
252   auto camera_pipeline_id_iter = camera_pipeline_ids_.find(camera_id);
253   if (camera_pipeline_id_iter == camera_pipeline_ids_.end()) {
254     ALOGE("%s: Cannot find the pipeline ID for camera %u", __FUNCTION__,
255           camera_id);
256     return BAD_VALUE;
257   }
258 
259   *pipeline_id = camera_pipeline_id_iter->second;
260   return OK;
261 }
262 
AreRequestsValidLocked(const std::vector<ProcessBlockRequest> & block_requests) const263 bool MultiCameraRtProcessBlock::AreRequestsValidLocked(
264     const std::vector<ProcessBlockRequest>& block_requests) const {
265   ATRACE_CALL();
266   if (block_requests.empty()) {
267     ALOGE("%s: requests is empty.", __FUNCTION__);
268     return false;
269   }
270 
271   std::unordered_set<int32_t> request_camera_ids;
272   uint32_t frame_number = block_requests[0].request.frame_number;
273   for (auto& block_request : block_requests) {
274     if (!block_request.request.input_buffers.empty()) {
275       ALOGE("%s: Input buffers are not supported.", __FUNCTION__);
276       return false;
277     }
278 
279     if (block_request.request.output_buffers.size() == 0) {
280       ALOGE("%s: request %u doesn't contain any output streams.", __FUNCTION__,
281             block_request.request.frame_number);
282       return false;
283     }
284 
285     if (block_request.request.frame_number != frame_number) {
286       ALOGE("%s: Not all frame numbers in requests are the same.",
287             __FUNCTION__);
288       return false;
289     }
290 
291     // Check all output buffers will be captured from the same physical camera.
292     uint32_t physical_camera_id;
293     for (uint32_t i = 0; i < block_request.request.output_buffers.size(); i++) {
294       uint32_t buffer_camera_id;
295       status_t res = GetBufferPhysicalCameraIdLocked(
296           block_request.request.output_buffers[0], &buffer_camera_id);
297       if (res != OK) {
298         ALOGE("%s: Getting buffer's physical camera ID failed: %s(%d)",
299               __FUNCTION__, strerror(-res), res);
300         return false;
301       }
302 
303       if (i == 0) {
304         physical_camera_id = buffer_camera_id;
305       } else if (buffer_camera_id != physical_camera_id) {
306         ALOGE("%s: Buffers should belong to the same camera ID in a request.",
307               __FUNCTION__);
308         return false;
309       }
310     }
311 
312     // Check no two requests will be captured from the same physical camera.
313     if (request_camera_ids.find(physical_camera_id) !=
314         request_camera_ids.end()) {
315       ALOGE("%s: No two requests can be captured from the same camera ID (%u).",
316             __FUNCTION__, physical_camera_id);
317       return false;
318     }
319 
320     request_camera_ids.insert(physical_camera_id);
321   }
322 
323   return true;
324 }
325 
ForwardPendingRequests(const std::vector<ProcessBlockRequest> & process_block_requests,const CaptureRequest & remaining_session_request)326 status_t MultiCameraRtProcessBlock::ForwardPendingRequests(
327     const std::vector<ProcessBlockRequest>& process_block_requests,
328     const CaptureRequest& remaining_session_request) {
329   std::lock_guard<std::mutex> lock(result_processor_mutex_);
330   if (result_processor_ == nullptr) {
331     ALOGE("%s: result processor was not set.", __FUNCTION__);
332     return NO_INIT;
333   }
334 
335   return result_processor_->AddPendingRequests(process_block_requests,
336                                                remaining_session_request);
337 }
338 
PrepareBlockByCameraId(uint32_t camera_id,uint32_t frame_number)339 status_t MultiCameraRtProcessBlock::PrepareBlockByCameraId(
340     uint32_t camera_id, uint32_t frame_number) {
341   return device_session_hwl_->PreparePipeline(camera_pipeline_ids_[camera_id],
342                                               frame_number);
343 }
344 
ProcessRequests(const std::vector<ProcessBlockRequest> & process_block_requests,const CaptureRequest & remaining_session_request)345 status_t MultiCameraRtProcessBlock::ProcessRequests(
346     const std::vector<ProcessBlockRequest>& process_block_requests,
347     const CaptureRequest& remaining_session_request) {
348   ATRACE_CALL();
349   std::shared_lock lock(configure_shared_mutex_);
350   if (configured_streams_.empty()) {
351     ALOGE("%s: block is not configured.", __FUNCTION__);
352     return NO_INIT;
353   }
354 
355   if (!AreRequestsValidLocked(process_block_requests)) {
356     ALOGE("%s: Requests are not supported.", __FUNCTION__);
357     return BAD_VALUE;
358   }
359 
360   status_t res =
361       ForwardPendingRequests(process_block_requests, remaining_session_request);
362   if (res != OK) {
363     ALOGE("%s: Forwarding pending requests failed: %s(%d)", __FUNCTION__,
364           strerror(-res), res);
365     return res;
366   }
367 
368   // Get pipeline ID for each request.
369   std::vector<uint32_t> pipeline_ids;
370   for (auto& block_request : process_block_requests) {
371     uint32_t pipeline_id;
372 
373     // Get the camera ID of the request's first output buffer. All output
374     // buffers should belong to the same pipeline ID, which is checked in
375     // AreRequestsSupportedLocked.
376     res = GetOutputBufferPipelineIdLocked(
377         block_request.request.output_buffers[0], &pipeline_id);
378     if (res != OK) {
379       ALOGE("%s: Getting buffer's pipeline ID failed: %s(%d)", __FUNCTION__,
380             strerror(-res), res);
381       return res;
382     }
383 
384     res = request_id_manager_->SetPipelineRequestId(
385         block_request.request_id, block_request.request.frame_number,
386         pipeline_id);
387     if (res != OK) {
388       ALOGE("%s: Adding pipeline request id info failed: %s(%d)", __FUNCTION__,
389             strerror(-res), res);
390       return res;
391     }
392 
393     pipeline_ids.push_back(pipeline_id);
394     ALOGV("%s: frame_number %u pipeline_id %u request_id %u", __FUNCTION__,
395           block_request.request.frame_number, pipeline_id,
396           block_request.request_id);
397   }
398 
399   std::vector<HwlPipelineRequest> hwl_requests;
400   res = hal_utils::CreateHwlPipelineRequests(&hwl_requests, pipeline_ids,
401                                              process_block_requests);
402   if (res != OK) {
403     ALOGE("%s: Creating HWL pipeline requests failed: %s(%d)", __FUNCTION__,
404           strerror(-res), res);
405     return res;
406   }
407 
408   return device_session_hwl_->SubmitRequests(
409       process_block_requests[0].request.frame_number, hwl_requests);
410 }
411 
Flush()412 status_t MultiCameraRtProcessBlock::Flush() {
413   ATRACE_CALL();
414   std::shared_lock lock(configure_shared_mutex_);
415   if (configured_streams_.empty()) {
416     return OK;
417   }
418 
419   status_t res = device_session_hwl_->Flush();
420   if (res != OK) {
421     ALOGE("%s: Flushing hwl device session failed.", __FUNCTION__);
422     return res;
423   }
424 
425   if (result_processor_ == nullptr) {
426     ALOGW("%s: result processor is nullptr.", __FUNCTION__);
427     return res;
428   }
429 
430   return result_processor_->FlushPendingRequests();
431 }
432 
NotifyHwlPipelineResult(std::unique_ptr<HwlPipelineResult> hwl_result)433 void MultiCameraRtProcessBlock::NotifyHwlPipelineResult(
434     std::unique_ptr<HwlPipelineResult> hwl_result) {
435   ATRACE_CALL();
436   std::lock_guard<std::mutex> lock(result_processor_mutex_);
437   if (result_processor_ == nullptr) {
438     ALOGE("%s: result processor is nullptr. Dropping a result", __FUNCTION__);
439     return;
440   }
441 
442   uint32_t frame_number = hwl_result->frame_number;
443   uint32_t pipeline_id = hwl_result->pipeline_id;
444   if (hwl_result->result_metadata == nullptr &&
445       hwl_result->input_buffers.empty() && hwl_result->output_buffers.empty()) {
446     ALOGV("%s: Skip empty result. pipeline_id %u frame_number %u", __FUNCTION__,
447           pipeline_id, frame_number);
448     return;
449   }
450   auto capture_result =
451       hal_utils::ConvertToCaptureResult(std::move(hwl_result));
452   if (capture_result == nullptr) {
453     ALOGE("%s: Converting to capture result failed.", __FUNCTION__);
454     return;
455   }
456 
457   ALOGV(
458       "%s: pipeline id %u frame_number %u output_buffer size %zu input_buffers "
459       "size %zu metadata %p ",
460       __FUNCTION__, pipeline_id, frame_number,
461       capture_result->output_buffers.size(),
462       capture_result->input_buffers.size(),
463       capture_result->result_metadata.get());
464 
465   uint32_t request_id = 0;
466   status_t res = request_id_manager_->GetPipelineRequestId(
467       pipeline_id, frame_number, &request_id);
468   if (res != OK) {
469     ALOGE("%s: Get request Id and remove pending failed. res %d", __FUNCTION__,
470           res);
471     return;
472   }
473 
474   ProcessBlockResult block_result = {.request_id = request_id,
475                                      .result = std::move(capture_result)};
476   result_processor_->ProcessResult(std::move(block_result));
477 }
478 
NotifyHwlPipelineMessage(uint32_t pipeline_id,const NotifyMessage & message)479 void MultiCameraRtProcessBlock::NotifyHwlPipelineMessage(
480     uint32_t pipeline_id, const NotifyMessage& message) {
481   ATRACE_CALL();
482   std::lock_guard<std::mutex> lock(result_processor_mutex_);
483   if (result_processor_ == nullptr) {
484     ALOGE("%s: result processor is nullptr. Dropping a message", __FUNCTION__);
485     return;
486   }
487   uint32_t frame_number = message.type == MessageType::kShutter
488                               ? message.message.shutter.frame_number
489                               : message.message.error.frame_number;
490   ALOGV("%s: pipeline id %u frame_number %u type %d", __FUNCTION__, pipeline_id,
491         frame_number, message.type);
492   uint32_t request_id = 0;
493   status_t res = request_id_manager_->GetPipelineRequestId(
494       pipeline_id, frame_number, &request_id);
495   if (res != OK) {
496     ALOGE("%s: Get request Id and remove pending failed. res %d", __FUNCTION__,
497           res);
498     return;
499   }
500   ProcessBlockNotifyMessage block_message = {.request_id = request_id,
501                                              .message = message};
502   result_processor_->Notify(std::move(block_message));
503 }
504 
505 }  // namespace google_camera_hal
506 }  // namespace android
507