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.", __FUNCTION__);
287       return false;
288     }
289 
290     // Check all output buffers will be captured from the same physical camera.
291     uint32_t physical_camera_id;
292     for (uint32_t i = 0; i < block_request.request.output_buffers.size(); i++) {
293       uint32_t buffer_camera_id;
294       status_t res = GetBufferPhysicalCameraIdLocked(
295           block_request.request.output_buffers[0], &buffer_camera_id);
296       if (res != OK) {
297         ALOGE("%s: Getting buffer's physical camera ID failed: %s(%d)",
298               __FUNCTION__, strerror(-res), res);
299         return false;
300       }
301 
302       if (i == 0) {
303         physical_camera_id = buffer_camera_id;
304       } else if (buffer_camera_id != physical_camera_id) {
305         ALOGE("%s: Buffers should belong to the same camera ID in a request.",
306               __FUNCTION__);
307         return false;
308       }
309     }
310 
311     // Check no two requests will be captured from the same physical camera.
312     if (request_camera_ids.find(physical_camera_id) != request_camera_ids.end()) {
313       ALOGE("%s: No two requests can be captured from the same camera ID (%u).",
314             __FUNCTION__, physical_camera_id);
315       return false;
316     }
317 
318     request_camera_ids.insert(physical_camera_id);
319   }
320 
321   return true;
322 }
323 
ForwardPendingRequests(const std::vector<ProcessBlockRequest> & process_block_requests,const CaptureRequest & remaining_session_request)324 status_t MultiCameraRtProcessBlock::ForwardPendingRequests(
325     const std::vector<ProcessBlockRequest>& process_block_requests,
326     const CaptureRequest& remaining_session_request) {
327   std::lock_guard<std::mutex> lock(result_processor_mutex_);
328   if (result_processor_ == nullptr) {
329     ALOGE("%s: result processor was not set.", __FUNCTION__);
330     return NO_INIT;
331   }
332 
333   return result_processor_->AddPendingRequests(process_block_requests,
334                                                remaining_session_request);
335 }
336 
PrepareBlockByCameraId(uint32_t camera_id,uint32_t frame_number)337 status_t MultiCameraRtProcessBlock::PrepareBlockByCameraId(
338     uint32_t camera_id, uint32_t frame_number) {
339   return device_session_hwl_->PreparePipeline(camera_pipeline_ids_[camera_id],
340                                               frame_number);
341 }
342 
ProcessRequests(const std::vector<ProcessBlockRequest> & process_block_requests,const CaptureRequest & remaining_session_request)343 status_t MultiCameraRtProcessBlock::ProcessRequests(
344     const std::vector<ProcessBlockRequest>& process_block_requests,
345     const CaptureRequest& remaining_session_request) {
346   ATRACE_CALL();
347   std::shared_lock lock(configure_shared_mutex_);
348   if (configured_streams_.empty()) {
349     ALOGE("%s: block is not configured.", __FUNCTION__);
350     return NO_INIT;
351   }
352 
353   if (!AreRequestsValidLocked(process_block_requests)) {
354     ALOGE("%s: Requests are not supported.", __FUNCTION__);
355     return BAD_VALUE;
356   }
357 
358   status_t res =
359       ForwardPendingRequests(process_block_requests, remaining_session_request);
360   if (res != OK) {
361     ALOGE("%s: Forwarding pending requests failed: %s(%d)", __FUNCTION__,
362           strerror(-res), res);
363     return res;
364   }
365 
366   // Get pipeline ID for each request.
367   std::vector<uint32_t> pipeline_ids;
368   for (auto& block_request : process_block_requests) {
369     uint32_t pipeline_id;
370 
371     // Get the camera ID of the request's first output buffer. All output
372     // buffers should belong to the same pipeline ID, which is checked in
373     // AreRequestsSupportedLocked.
374     res = GetOutputBufferPipelineIdLocked(
375         block_request.request.output_buffers[0], &pipeline_id);
376     if (res != OK) {
377       ALOGE("%s: Getting buffer's pipeline ID failed: %s(%d)", __FUNCTION__,
378             strerror(-res), res);
379       return res;
380     }
381 
382     res = request_id_manager_->SetPipelineRequestId(
383         block_request.request_id, block_request.request.frame_number,
384         pipeline_id);
385     if (res != OK) {
386       ALOGE("%s: Adding pipeline request id info failed: %s(%d)", __FUNCTION__,
387             strerror(-res), res);
388       return res;
389     }
390 
391     pipeline_ids.push_back(pipeline_id);
392     ALOGV("%s: frame_number %u pipeline_id %u request_id %u", __FUNCTION__,
393           block_request.request.frame_number, pipeline_id,
394           block_request.request_id);
395   }
396 
397   std::vector<HwlPipelineRequest> hwl_requests;
398   res = hal_utils::CreateHwlPipelineRequests(&hwl_requests, pipeline_ids,
399                                              process_block_requests);
400   if (res != OK) {
401     ALOGE("%s: Creating HWL pipeline requests failed: %s(%d)", __FUNCTION__,
402           strerror(-res), res);
403     return res;
404   }
405 
406   return device_session_hwl_->SubmitRequests(
407       process_block_requests[0].request.frame_number, hwl_requests);
408 }
409 
Flush()410 status_t MultiCameraRtProcessBlock::Flush() {
411   ATRACE_CALL();
412   std::shared_lock lock(configure_shared_mutex_);
413   if (configured_streams_.empty()) {
414     return OK;
415   }
416 
417   status_t res = device_session_hwl_->Flush();
418   if (res != OK) {
419     ALOGE("%s: Flushing hwl device session failed.", __FUNCTION__);
420     return res;
421   }
422 
423   if (result_processor_ == nullptr) {
424     ALOGW("%s: result processor is nullptr.", __FUNCTION__);
425     return res;
426   }
427 
428   return result_processor_->FlushPendingRequests();
429 }
430 
NotifyHwlPipelineResult(std::unique_ptr<HwlPipelineResult> hwl_result)431 void MultiCameraRtProcessBlock::NotifyHwlPipelineResult(
432     std::unique_ptr<HwlPipelineResult> hwl_result) {
433   ATRACE_CALL();
434   std::lock_guard<std::mutex> lock(result_processor_mutex_);
435   if (result_processor_ == nullptr) {
436     ALOGE("%s: result processor is nullptr. Dropping a result", __FUNCTION__);
437     return;
438   }
439 
440   uint32_t frame_number = hwl_result->frame_number;
441   uint32_t pipeline_id = hwl_result->pipeline_id;
442   if (hwl_result->result_metadata == nullptr &&
443       hwl_result->input_buffers.empty() && hwl_result->output_buffers.empty()) {
444     ALOGV("%s: Skip empty result. pipeline_id %u frame_number %u", __FUNCTION__,
445           pipeline_id, frame_number);
446     return;
447   }
448   auto capture_result = hal_utils::ConvertToCaptureResult(std::move(hwl_result));
449   if (capture_result == nullptr) {
450     ALOGE("%s: Converting to capture result failed.", __FUNCTION__);
451     return;
452   }
453 
454   ALOGV(
455       "%s: pipeline id %u frame_number %u output_buffer size %zu input_buffers "
456       "size %zu metadata %p ",
457       __FUNCTION__, pipeline_id, frame_number,
458       capture_result->output_buffers.size(),
459       capture_result->input_buffers.size(),
460       capture_result->result_metadata.get());
461 
462   uint32_t request_id = 0;
463   status_t res = request_id_manager_->GetPipelineRequestId(
464       pipeline_id, frame_number, &request_id);
465   if (res != OK) {
466     ALOGE("%s: Get request Id and remove pending failed. res %d", __FUNCTION__,
467           res);
468     return;
469   }
470 
471   ProcessBlockResult block_result = {.request_id = request_id,
472                                      .result = std::move(capture_result)};
473   result_processor_->ProcessResult(std::move(block_result));
474 }
475 
NotifyHwlPipelineMessage(uint32_t pipeline_id,const NotifyMessage & message)476 void MultiCameraRtProcessBlock::NotifyHwlPipelineMessage(
477     uint32_t pipeline_id, const NotifyMessage& message) {
478   ATRACE_CALL();
479   std::lock_guard<std::mutex> lock(result_processor_mutex_);
480   if (result_processor_ == nullptr) {
481     ALOGE("%s: result processor is nullptr. Dropping a message", __FUNCTION__);
482     return;
483   }
484   uint32_t frame_number = message.type == MessageType::kShutter
485                               ? message.message.shutter.frame_number
486                               : message.message.error.frame_number;
487   ALOGV("%s: pipeline id %u frame_number %u type %d", __FUNCTION__, pipeline_id,
488         frame_number, message.type);
489   uint32_t request_id = 0;
490   status_t res = request_id_manager_->GetPipelineRequestId(
491       pipeline_id, frame_number, &request_id);
492   if (res != OK) {
493     ALOGE("%s: Get request Id and remove pending failed. res %d", __FUNCTION__,
494           res);
495     return;
496   }
497   ProcessBlockNotifyMessage block_message = {.request_id = request_id,
498                                              .message = message};
499   result_processor_->Notify(std::move(block_message));
500 }
501 
502 }  // namespace google_camera_hal
503 }  // namespace android
504