Merge 84f19b689f495298aef42fda64b567fd5923daee on remote branch

Change-Id: I15d4a23bcd5f9715647695d552f47f68fcd7e4dc
diff --git a/common/hal/aidl_service/aidl_camera_device_session.cc b/common/hal/aidl_service/aidl_camera_device_session.cc
index 9af6de1..49d8282 100644
--- a/common/hal/aidl_service/aidl_camera_device_session.cc
+++ b/common/hal/aidl_service/aidl_camera_device_session.cc
@@ -19,6 +19,7 @@
 //#define LOG_NDEBUG 0
 #include "aidl_camera_device_session.h"
 
+#include <android/binder_ibinder_platform.h>
 #include <cutils/properties.h>
 #include <cutils/trace.h>
 #include <log/log.h>
@@ -798,6 +799,12 @@
   return ScopedAStatus::ok();
 }
 
+::ndk::SpAIBinder AidlCameraDeviceSession::createBinder() {
+  auto binder = BnCameraDeviceSession::createBinder();
+  AIBinder_setInheritRt(binder.get(), true);
+  return binder;
+}
+
 }  // namespace implementation
 }  // namespace device
 }  // namespace camera
diff --git a/common/hal/aidl_service/aidl_camera_device_session.h b/common/hal/aidl_service/aidl_camera_device_session.h
index e14604d..3423d8f 100644
--- a/common/hal/aidl_service/aidl_camera_device_session.h
+++ b/common/hal/aidl_service/aidl_camera_device_session.h
@@ -113,6 +113,9 @@
 
   AidlCameraDeviceSession() = default;
 
+ protected:
+  ::ndk::SpAIBinder createBinder() override;
+
  private:
   static constexpr uint32_t kRequestMetadataQueueSizeBytes = 1 << 20;  // 1MB
   static constexpr uint32_t kResultMetadataQueueSizeBytes = 1 << 20;   // 1MB
diff --git a/common/hal/aidl_service/version_script.py b/common/hal/aidl_service/version_script.py
index 5551ad9..54c2a2f 100644
--- a/common/hal/aidl_service/version_script.py
+++ b/common/hal/aidl_service/version_script.py
@@ -20,7 +20,7 @@
 import re
 import sys
 
-BRANCH_SPECIFIC_VERSION_IDENTIFIER = 4  # main
+BRANCH_SPECIFIC_VERSION_IDENTIFIER = 6  # main
 DEFAULT_ENG_BUILD_NUMBER = 2147480000
 DEFAULT_BAD_BUILD_NUMBER = DEFAULT_ENG_BUILD_NUMBER - 1
 
diff --git a/common/hal/google_camera_hal/camera_device_session.cc b/common/hal/google_camera_hal/camera_device_session.cc
index f1821e6..f0fb273 100644
--- a/common/hal/google_camera_hal/camera_device_session.cc
+++ b/common/hal/google_camera_hal/camera_device_session.cc
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-//#define LOG_NDEBUG 0
+// #define LOG_NDEBUG 0
 #define LOG_TAG "GCH_CameraDeviceSession"
 #define ATRACE_TAG ATRACE_TAG_CAMERA
 #include "camera_device_session.h"
@@ -1858,9 +1858,9 @@
       ALOGI("%s: stream %d, buffer request error %d", __FUNCTION__,
             buffer_return.stream_id, buffer_return.val.error);
     }
-
     pending_requests_tracker_->TrackBufferAcquisitionFailure(stream_id,
                                                              num_buffers);
+    pending_requests_tracker_->DumpStatus();
     // TODO(b/129362905): Return partial buffers.
     return UNKNOWN_ERROR;
   }
diff --git a/common/hal/google_camera_hal/camera_provider.cc b/common/hal/google_camera_hal/camera_provider.cc
index 2d816eb..30e184d 100644
--- a/common/hal/google_camera_hal/camera_provider.cc
+++ b/common/hal/google_camera_hal/camera_provider.cc
@@ -23,6 +23,9 @@
 #include <log/log.h>
 #include <utils/Trace.h>
 
+#if !GCH_HWL_USE_DLOPEN
+#include "lyric_hwl/madvise_library_list.h"
+#endif
 #include "vendor_tag_defs.h"
 #include "vendor_tag_utils.h"
 
@@ -282,6 +285,8 @@
 #if GCH_HWL_USE_DLOPEN
   configure_streams_libs = reinterpret_cast<decltype(configure_streams_libs)>(
       dlsym(hwl_lib_handle_, "configure_streams_libraries"));
+#else
+  configure_streams_libs = &configure_streams_libraries;
 #endif
   *device =
       CameraDevice::Create(std::move(camera_device_hwl),
diff --git a/common/hal/google_camera_hal/hdrplus_capture_session.cc b/common/hal/google_camera_hal/hdrplus_capture_session.cc
index c7b676a..9a78e6e 100644
--- a/common/hal/google_camera_hal/hdrplus_capture_session.cc
+++ b/common/hal/google_camera_hal/hdrplus_capture_session.cc
@@ -480,8 +480,8 @@
   }
 
   // Create result dispatcher
-  result_dispatcher_ =
-      ResultDispatcher::Create(kPartialResult, process_capture_result, notify);
+  result_dispatcher_ = ResultDispatcher::Create(
+      kPartialResult, process_capture_result, notify, "HdrplusDispatcher");
   if (result_dispatcher_ == nullptr) {
     ALOGE("%s: Cannot create result dispatcher.", __FUNCTION__);
     return UNKNOWN_ERROR;
diff --git a/common/hal/google_camera_hal/pending_requests_tracker.cc b/common/hal/google_camera_hal/pending_requests_tracker.cc
index 87ad722..23eae69 100644
--- a/common/hal/google_camera_hal/pending_requests_tracker.cc
+++ b/common/hal/google_camera_hal/pending_requests_tracker.cc
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-//#define LOG_NDEBUG 0
+// #define LOG_NDEBUG 0
 #define LOG_TAG "GCH_PendingRequestsTracker"
 #define ATRACE_TAG ATRACE_TAG_CAMERA
 #include <log/log.h>
@@ -318,5 +318,33 @@
   stream_acquired_buffers_[overridden_stream_id] -= num_buffers;
 }
 
+void PendingRequestsTracker::DumpStatus() {
+  std::string pending_requests_string = "{";
+  {
+    std::lock_guard<std::mutex> lock(pending_requests_mutex_);
+    for (auto& [stream_id, num_pending_buffers] : stream_pending_buffers_) {
+      pending_requests_string += "{" + std::to_string(stream_id) + ": " +
+                                 std::to_string(num_pending_buffers) + "},";
+    }
+  }
+  pending_requests_string += "}";
+
+  std::string pending_acquisition_string = "{";
+  {
+    std::lock_guard<std::mutex> lock(pending_acquisition_mutex_);
+    for (auto& [stream_id, num_acquired_buffers] : stream_acquired_buffers_) {
+      pending_acquisition_string += "{" + std::to_string(stream_id) + ": " +
+                                    std::to_string(num_acquired_buffers) + "},";
+    }
+  }
+  pending_acquisition_string += "}";
+
+  ALOGI(
+      "%s: Buffers (including dummy) pending return from HWL: %s. Buffers "
+      "proactively acquired from the framework: %s.",
+      __FUNCTION__, pending_requests_string.c_str(),
+      pending_acquisition_string.c_str());
+}
+
 }  // namespace google_camera_hal
 }  // namespace android
diff --git a/common/hal/google_camera_hal/pending_requests_tracker.h b/common/hal/google_camera_hal/pending_requests_tracker.h
index cdff661..529eb6a 100644
--- a/common/hal/google_camera_hal/pending_requests_tracker.h
+++ b/common/hal/google_camera_hal/pending_requests_tracker.h
@@ -63,6 +63,9 @@
   // Notify the request tracker that the buffer cache manager has been flushed.
   void OnBufferCacheFlushed();
 
+  // Dump the buffer counting status
+  void DumpStatus();
+
   virtual ~PendingRequestsTracker() = default;
 
  protected:
diff --git a/common/hal/google_camera_hal/realtime_zsl_result_request_processor.cc b/common/hal/google_camera_hal/realtime_zsl_result_request_processor.cc
index 23b9f78..be455eb 100644
--- a/common/hal/google_camera_hal/realtime_zsl_result_request_processor.cc
+++ b/common/hal/google_camera_hal/realtime_zsl_result_request_processor.cc
@@ -24,6 +24,8 @@
 #include <log/log.h>
 #include <utils/Trace.h>
 
+#include <memory>
+
 #include "hal_types.h"
 #include "hal_utils.h"
 #include "realtime_zsl_result_processor.h"
@@ -70,7 +72,7 @@
 }
 
 void RealtimeZslResultRequestProcessor::UpdateOutputBufferCount(
-    int32_t frame_number, int output_buffer_count) {
+    int32_t frame_number, int output_buffer_count, bool is_preview_intent) {
   ATRACE_CALL();
   std::lock_guard<std::mutex> lock(callback_lock_);
   // Cache the CaptureRequest in a queue as the metadata and buffers may not
@@ -79,6 +81,12 @@
       .capture_request = std::make_unique<CaptureRequest>(),
       .framework_buffer_count = output_buffer_count};
   request_entry.capture_request->frame_number = frame_number;
+  if (!is_preview_intent) {
+    // If no preview intent is provided, RealtimeZslRequestProcessor will not
+    // add an internal buffer to the request so there is no ZSL buffer to wait
+    // for in that case.
+    request_entry.zsl_buffer_received = true;
+  }
 
   pending_frame_number_to_requests_[frame_number] = std::move(request_entry);
 }
@@ -93,18 +101,29 @@
     return;
   }
 
+  // May change to ALOGD for per-frame results.
+  ALOGV(
+      "%s: Received result at frame: %d, has metadata (%s), output buffer "
+      "counts: %zu, input buffer counts: %zu",
+      __FUNCTION__, result->frame_number,
+      (result->result_metadata ? "yes" : "no"), result->output_buffers.size(),
+      result->input_buffers.size());
+
   // Pending request should always exist
   RequestEntry& pending_request =
       pending_frame_number_to_requests_[result->frame_number];
+  if (pending_request.capture_request == nullptr) {
+    pending_request.capture_request = std::make_unique<CaptureRequest>();
+    pending_request.capture_request->frame_number = result->frame_number;
+  }
 
   // Return filled raw buffer to internal stream manager
   // And remove raw buffer from result
-  bool returned_output = false;
   status_t res;
   std::vector<StreamBuffer> modified_output_buffers;
   for (uint32_t i = 0; i < result->output_buffers.size(); i++) {
     if (stream_id_ == result->output_buffers[i].stream_id) {
-      returned_output = true;
+      pending_request.has_returned_output_to_internal_stream_manager = true;
       res = internal_stream_manager_->ReturnFilledBuffer(
           result->frame_number, result->output_buffers[i]);
       if (res != OK) {
@@ -146,45 +165,8 @@
   if (pending_error_frames_.find(result->frame_number) !=
       pending_error_frames_.end()) {
     RequestEntry& error_entry = pending_error_frames_[result->frame_number];
-    // Also need to process pending buffers and metadata for the frame if exists.
-    // If the result is complete (buffers and all partial results arrived), send
-    // the callback directly. Otherwise wait until the missing pieces arrive.
-    if (pending_request.zsl_buffer_received &&
-        pending_request.framework_buffer_count ==
-            static_cast<int>(
-                pending_request.capture_request->output_buffers.size())) {
-      result->output_buffers = pending_request.capture_request->output_buffers;
-      result->input_buffers = pending_request.capture_request->input_buffers;
-      error_entry.capture_request->output_buffers = result->output_buffers;
-      error_entry.capture_request->input_buffers = result->input_buffers;
-      error_entry.zsl_buffer_received = pending_request.zsl_buffer_received;
-      error_entry.framework_buffer_count =
-          pending_request.framework_buffer_count;
-    }
-    if (pending_request.capture_request->settings != nullptr) {
-      result->result_metadata = HalCameraMetadata::Clone(
-          pending_request.capture_request->settings.get());
-      result->partial_result = pending_request.partial_results_received;
-      error_entry.partial_results_received++;
-    }
-
-    // Reset capture request for pending request as all data has been
-    // transferred to error_entry already.
-    pending_request.capture_request = std::make_unique<CaptureRequest>();
-    pending_request.capture_request->frame_number = result->frame_number;
-
-    if (AllDataCollected(error_entry)) {
-      pending_error_frames_.erase(result->frame_number);
-      pending_frame_number_to_requests_.erase(result->frame_number);
-    }
-
-    // Don't send result to framework if only internal raw callback
-    if (returned_output && result->result_metadata == nullptr &&
-        result->output_buffers.size() == 0) {
-      return;
-    }
-    process_capture_result_(std::move(result));
-    return;
+    return ReturnResultDirectlyForFramesWithErrorsLocked(
+        error_entry, pending_request, std::move(result));
   }
 
   // Fill in final result metadata
@@ -201,7 +183,7 @@
         pending_request.capture_request->settings =
             HalCameraMetadata::Clone(result->result_metadata.get());
       } else {
-        // Append final result to early result
+        // Append early result to final result
         pending_request.capture_request->settings->Append(
             result->result_metadata->GetRawCameraMetadata());
       }
@@ -328,15 +310,110 @@
 
   // Will return buffer for kErrorRequest and kErrorBuffer.
   if (message.type == MessageType::kError) {
+    // May change to ALOGD for per-frame error messages.
+    ALOGV("%s: Received error message at frame: %d, error code (%d)",
+          __FUNCTION__, message.message.error.frame_number,
+          static_cast<int>(message.message.error.error_code));
     if (message.message.error.error_code == ErrorCode::kErrorRequest ||
         message.message.error.error_code == ErrorCode::kErrorBuffer) {
       pending_error_frames_.try_emplace(
           message.message.error.frame_number,
           RequestEntry{.capture_request = std::make_unique<CaptureRequest>()});
+      if (message.message.error.error_code == ErrorCode::kErrorRequest) {
+        // ProcessCaptureResult is not called in the case of metadata error.
+        // Therefore, treat it as if a metadata callback arrived so that we can
+        // know when the request is complete.
+        pending_error_frames_[message.message.error.frame_number]
+            .partial_results_received++;
+      }
     }
+    // Gives latched results (those that have arrived but are waiting for
+    // AllDataCollected()) a chance to return their valid buffer.
+    uint32_t frame_number = message.message.error.frame_number;
+    auto result = std::make_unique<CaptureResult>();
+    result->frame_number = frame_number;
+    if (pending_frame_number_to_requests_.find(frame_number) !=
+        pending_frame_number_to_requests_.end()) {
+      RequestEntry& pending_request =
+          pending_frame_number_to_requests_[frame_number];
+      if (pending_request.zsl_buffer_received) {
+        ReturnResultDirectlyForFramesWithErrorsLocked(
+            pending_error_frames_[frame_number], pending_request,
+            std::move(result));
+      }
+    }
+  } else {
+    // May change to ALOGD for per-frame shutter messages.
+    ALOGV("%s: Received shutter message for frame %d, timestamp_ns: %" PRId64
+          ", readout_timestamp_ns: %" PRId64,
+          __FUNCTION__, message.message.shutter.frame_number,
+          message.message.shutter.timestamp_ns,
+          message.message.shutter.readout_timestamp_ns);
   }
   notify_(message);
 }
 
+void RealtimeZslResultRequestProcessor::CombineErrorAndPendingEntriesToResult(
+    RequestEntry& error_entry, RequestEntry& pending_request,
+    std::unique_ptr<CaptureResult>& result) const {
+  result->output_buffers.insert(
+      result->output_buffers.end(),
+      pending_request.capture_request->output_buffers.begin(),
+      pending_request.capture_request->output_buffers.end());
+  result->input_buffers.insert(
+      result->input_buffers.end(),
+      pending_request.capture_request->input_buffers.begin(),
+      pending_request.capture_request->input_buffers.end());
+  error_entry.capture_request->output_buffers = result->output_buffers;
+  error_entry.capture_request->input_buffers = result->input_buffers;
+  error_entry.zsl_buffer_received = pending_request.zsl_buffer_received;
+  error_entry.framework_buffer_count = pending_request.framework_buffer_count;
+  if (pending_request.capture_request->settings != nullptr) {
+    if (result->result_metadata == nullptr) {
+      // result is a buffer-only result and we have early metadata sitting in
+      // pending_request. Copy this early metadata and its partial_result count.
+      result->result_metadata = HalCameraMetadata::Clone(
+          pending_request.capture_request->settings.get());
+      result->partial_result = pending_request.partial_results_received;
+    } else {
+      // result carries final metadata and we have early metadata sitting in
+      // pending_request. Append the early metadata but keep the
+      // partial_result count to reflect that this is the final metadata.
+      result->result_metadata->Append(
+          pending_request.capture_request->settings->GetRawCameraMetadata());
+    }
+    error_entry.partial_results_received += result->partial_result;
+  }
+
+  // Reset capture request for pending request as all data has been
+  // transferred to error_entry already.
+  pending_request.capture_request = std::make_unique<CaptureRequest>();
+  pending_request.capture_request->frame_number = result->frame_number;
+}
+
+void RealtimeZslResultRequestProcessor::ReturnResultDirectlyForFramesWithErrorsLocked(
+    RequestEntry& error_entry, RequestEntry& pending_request,
+    std::unique_ptr<CaptureResult> result) {
+  // Also need to process pending buffers and metadata for the frame if exists.
+  // If the result is complete (buffers and all partial results arrived), send
+  // the callback directly. Otherwise wait until the missing pieces arrive.
+  CombineErrorAndPendingEntriesToResult(error_entry, pending_request, result);
+
+  if (AllDataCollected(error_entry)) {
+    pending_error_frames_.erase(result->frame_number);
+    pending_frame_number_to_requests_.erase(result->frame_number);
+  }
+
+  // Don't send result to framework if only internal raw callback
+  if (pending_request.has_returned_output_to_internal_stream_manager &&
+      result->result_metadata == nullptr && result->output_buffers.size() == 0) {
+    return;
+  }
+  ALOGV("%s: Returning capture result for frame %d due to existing errors.",
+        __FUNCTION__, result->frame_number);
+  process_capture_result_(std::move(result));
+  return;
+}
+
 }  // namespace google_camera_hal
-}  // namespace android
\ No newline at end of file
+}  // namespace android
diff --git a/common/hal/google_camera_hal/realtime_zsl_result_request_processor.h b/common/hal/google_camera_hal/realtime_zsl_result_request_processor.h
index 609b2c3..5454916 100644
--- a/common/hal/google_camera_hal/realtime_zsl_result_request_processor.h
+++ b/common/hal/google_camera_hal/realtime_zsl_result_request_processor.h
@@ -60,7 +60,8 @@
   status_t Flush() override;
   // Override functions of RequestProcessor end.
 
-  void UpdateOutputBufferCount(int32_t frame_number, int output_buffer_count);
+  void UpdateOutputBufferCount(int32_t frame_number, int output_buffer_count,
+                               bool is_preview_intent);
 
  protected:
   RealtimeZslResultRequestProcessor(
@@ -79,10 +80,27 @@
     uint32_t partial_results_received = 0;
     bool zsl_buffer_received = false;
     int framework_buffer_count = INT_MAX;
+    // Whether there were filled raw buffers that have been returned to internal
+    // stream manager.
+    bool has_returned_output_to_internal_stream_manager = false;
   };
 
   bool AllDataCollected(const RequestEntry& request_entry) const;
 
+  // A helper function to combine information for the same frame number from
+  // `pending_error_frames_` and `pending_frame_number_to_requests_` to the
+  // `result`. This is a 3-way update, where `pending_request` info is copied to
+  // `error_entry` and `result`, and `pending_request` info gets reset.
+  void CombineErrorAndPendingEntriesToResult(
+      RequestEntry& error_entry, RequestEntry& pending_request,
+      std::unique_ptr<CaptureResult>& result) const;
+
+  // Returns result directly for frames with errors, if applicable. Call site
+  // must hold callback_lock_.
+  void ReturnResultDirectlyForFramesWithErrorsLocked(
+      RequestEntry& error_entry, RequestEntry& pending_request,
+      std::unique_ptr<CaptureResult> result);
+
   // Results collected so far on a valid frame. Results are passed to the
   // processor block once all items in the RequestEntry struct are complete -
   // i.e. all buffers arrived an all partial results arrived.
diff --git a/common/hal/google_camera_hal/rgbird_capture_session.cc b/common/hal/google_camera_hal/rgbird_capture_session.cc
index 272b2a8..919a2fa 100644
--- a/common/hal/google_camera_hal/rgbird_capture_session.cc
+++ b/common/hal/google_camera_hal/rgbird_capture_session.cc
@@ -986,8 +986,8 @@
   }
 
   // Create result dispatcher
-  result_dispatcher_ =
-      ResultDispatcher::Create(kPartialResult, process_capture_result, notify);
+  result_dispatcher_ = ResultDispatcher::Create(
+      kPartialResult, process_capture_result, notify, "RgbirdDispatcher");
   if (result_dispatcher_ == nullptr) {
     ALOGE("%s: Cannot create result dispatcher.", __FUNCTION__);
     return UNKNOWN_ERROR;
diff --git a/common/hal/google_camera_hal/zsl_snapshot_capture_session.cc b/common/hal/google_camera_hal/zsl_snapshot_capture_session.cc
index 151ed69..ab17df8 100644
--- a/common/hal/google_camera_hal/zsl_snapshot_capture_session.cc
+++ b/common/hal/google_camera_hal/zsl_snapshot_capture_session.cc
@@ -219,7 +219,11 @@
   bool has_preview_stream = false;
   for (const auto& stream : stream_config.streams) {
     if (stream.is_physical_camera_stream) {
-      ALOGE("%s: support logical camera only", __FUNCTION__);
+      ALOGE("%s: support logical stream only", __FUNCTION__);
+      return false;
+    }
+    if (utils::IsSecuredStream(stream)) {
+      ALOGE("%s: don't support secured stream", __FUNCTION__);
       return false;
     }
     if (utils::IsJPEGSnapshotStream(stream) ||
@@ -808,12 +812,17 @@
 status_t ZslSnapshotCaptureSession::ProcessRequest(const CaptureRequest& request) {
   ATRACE_CALL();
   bool is_zsl_request = false;
+  bool is_preview_intent = false;
   camera_metadata_ro_entry entry;
   if (request.settings != nullptr) {
     if (request.settings->Get(ANDROID_CONTROL_ENABLE_ZSL, &entry) == OK &&
         *entry.data.u8 == ANDROID_CONTROL_ENABLE_ZSL_TRUE) {
       is_zsl_request = true;
     }
+    if (request.settings->Get(ANDROID_CONTROL_CAPTURE_INTENT, &entry) == OK &&
+        *entry.data.u8 == ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW) {
+      is_preview_intent = true;
+    }
   }
   status_t res = result_dispatcher_->AddPendingRequest(request, is_zsl_request);
   if (res != OK) {
@@ -827,12 +836,18 @@
       ALOGW(
           "%s: frame (%d) fall back to real time request for snapshot: %s (%d)",
           __FUNCTION__, request.frame_number, strerror(-res), res);
+      if (realtime_zsl_result_request_processor_ != nullptr) {
+        realtime_zsl_result_request_processor_->UpdateOutputBufferCount(
+            request.frame_number, request.output_buffers.size(),
+            is_preview_intent);
+      }
       res = realtime_request_processor_->ProcessRequest(request);
     }
   } else {
     if (realtime_zsl_result_request_processor_ != nullptr) {
       realtime_zsl_result_request_processor_->UpdateOutputBufferCount(
-          request.frame_number, request.output_buffers.size());
+          request.frame_number, request.output_buffers.size(),
+          is_preview_intent);
     }
 
     res = realtime_request_processor_->ProcessRequest(request);
diff --git a/common/hal/tests/result_dispatcher_tests.cc b/common/hal/tests/result_dispatcher_tests.cc
index 7196767..4964ab3 100644
--- a/common/hal/tests/result_dispatcher_tests.cc
+++ b/common/hal/tests/result_dispatcher_tests.cc
@@ -64,7 +64,8 @@
         [this](std::unique_ptr<CaptureResult> result) {
           ProcessCaptureResult(std::move(result));
         },
-        [this](const NotifyMessage& message) { Notify(message); });
+        [this](const NotifyMessage& message) { Notify(message); },
+        "TestResultDispatcher");
 
     ASSERT_NE(result_dispatcher_, nullptr)
         << "Creating ResultDispatcher failed";
diff --git a/common/hal/utils/result_dispatcher.cc b/common/hal/utils/result_dispatcher.cc
index 0a4832c..fdf9502 100644
--- a/common/hal/utils/result_dispatcher.cc
+++ b/common/hal/utils/result_dispatcher.cc
@@ -17,12 +17,16 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "GCH_ResultDispatcher"
 #define ATRACE_TAG ATRACE_TAG_CAMERA
-#include <log/log.h>
-#include <utils/Trace.h>
+#include "result_dispatcher.h"
 
 #include <inttypes.h>
+#include <log/log.h>
+#include <sys/resource.h>
+#include <utils/Trace.h>
 
-#include "result_dispatcher.h"
+#include <string>
+#include <string_view>
+
 #include "utils.h"
 
 namespace android {
@@ -30,12 +34,14 @@
 
 std::unique_ptr<ResultDispatcher> ResultDispatcher::Create(
     uint32_t partial_result_count,
-    ProcessCaptureResultFunc process_capture_result, NotifyFunc notify) {
+    ProcessCaptureResultFunc process_capture_result, NotifyFunc notify,
+    std::string_view name) {
   ATRACE_CALL();
   auto dispatcher = std::unique_ptr<ResultDispatcher>(new ResultDispatcher(
-      partial_result_count, process_capture_result, notify));
+      partial_result_count, process_capture_result, notify, name));
   if (dispatcher == nullptr) {
-    ALOGE("%s: Creating ResultDispatcher failed.", __FUNCTION__);
+    ALOGE("[%s] %s: Creating ResultDispatcher failed.",
+          std::string(name).c_str(), __FUNCTION__);
     return nullptr;
   }
 
@@ -44,8 +50,10 @@
 
 ResultDispatcher::ResultDispatcher(
     uint32_t partial_result_count,
-    ProcessCaptureResultFunc process_capture_result, NotifyFunc notify)
+    ProcessCaptureResultFunc process_capture_result, NotifyFunc notify,
+    std::string_view name)
     : kPartialResultCount(partial_result_count),
+      name_(name),
       process_capture_result_(process_capture_result),
       notify_(notify) {
   ATRACE_CALL();
@@ -56,9 +64,18 @@
     status_t res =
         utils::SetRealtimeThread(notify_callback_thread_.native_handle());
     if (res != OK) {
-      ALOGE("%s: SetRealtimeThread fail", __FUNCTION__);
+      ALOGE("[%s] %s: SetRealtimeThread fail", name_.c_str(), __FUNCTION__);
     } else {
-      ALOGI("%s: SetRealtimeThread OK", __FUNCTION__);
+      ALOGI("[%s] %s: SetRealtimeThread OK", name_.c_str(), __FUNCTION__);
+    }
+  } else {
+    // Assign higher priority to reduce the preemption when CPU usage is high
+    int32_t res = setpriority(
+        PRIO_PROCESS,
+        pthread_gettid_np(notify_callback_thread_.native_handle()), -20);
+    if (res != 0) {
+      ALOGE("[%s] %s: Set thread priority fail with error: %s", name_.c_str(),
+            __FUNCTION__, strerror(errno));
     }
   }
 }
@@ -87,8 +104,8 @@
 
   status_t res = AddPendingRequestLocked(pending_request);
   if (res != OK) {
-    ALOGE("%s: Adding a pending request failed: %s(%d).", __FUNCTION__,
-          strerror(-res), res);
+    ALOGE("[%s] %s: Adding a pending request failed: %s(%d).", name_.c_str(),
+          __FUNCTION__, strerror(-res), res);
     RemovePendingRequestLocked(pending_request.frame_number);
     return res;
   }
@@ -103,23 +120,23 @@
 
   status_t res = AddPendingShutterLocked(frame_number);
   if (res != OK) {
-    ALOGE("%s: Adding pending shutter for frame %u failed: %s(%d)",
-          __FUNCTION__, frame_number, strerror(-res), res);
+    ALOGE("[%s] %s: Adding pending shutter for frame %u failed: %s(%d)",
+          name_.c_str(), __FUNCTION__, frame_number, strerror(-res), res);
     return res;
   }
 
   res = AddPendingFinalResultMetadataLocked(frame_number);
   if (res != OK) {
-    ALOGE("%s: Adding pending result metadata for frame %u failed: %s(%d)",
-          __FUNCTION__, frame_number, strerror(-res), res);
+    ALOGE("[%s] %s: Adding pending result metadata for frame %u failed: %s(%d)",
+          name_.c_str(), __FUNCTION__, frame_number, strerror(-res), res);
     return res;
   }
 
   for (auto& buffer : pending_request.input_buffers) {
     res = AddPendingBufferLocked(frame_number, buffer, /*is_input=*/true);
     if (res != OK) {
-      ALOGE("%s: Adding pending input buffer for frame %u failed: %s(%d)",
-            __FUNCTION__, frame_number, strerror(-res), res);
+      ALOGE("[%s] %s: Adding pending input buffer for frame %u failed: %s(%d)",
+            name_.c_str(), __FUNCTION__, frame_number, strerror(-res), res);
       return res;
     }
   }
@@ -127,8 +144,8 @@
   for (auto& buffer : pending_request.output_buffers) {
     res = AddPendingBufferLocked(frame_number, buffer, /*is_input=*/false);
     if (res != OK) {
-      ALOGE("%s: Adding pending output buffer for frame %u failed: %s(%d)",
-            __FUNCTION__, frame_number, strerror(-res), res);
+      ALOGE("[%s] %s: Adding pending output buffer for frame %u failed: %s(%d)",
+            name_.c_str(), __FUNCTION__, frame_number, strerror(-res), res);
       return res;
     }
   }
@@ -139,8 +156,8 @@
 status_t ResultDispatcher::AddPendingShutterLocked(uint32_t frame_number) {
   ATRACE_CALL();
   if (pending_shutters_.find(frame_number) != pending_shutters_.end()) {
-    ALOGE("%s: Pending shutter for frame %u already exists.", __FUNCTION__,
-          frame_number);
+    ALOGE("[%s] %s: Pending shutter for frame %u already exists.",
+          name_.c_str(), __FUNCTION__, frame_number);
     return ALREADY_EXISTS;
   }
 
@@ -153,8 +170,8 @@
   ATRACE_CALL();
   if (pending_final_metadata_.find(frame_number) !=
       pending_final_metadata_.end()) {
-    ALOGE("%s: Pending final result metadata for frame %u already exists.",
-          __FUNCTION__, frame_number);
+    ALOGE("[%s] %s: Pending final result metadata for frame %u already exists.",
+          name_.c_str(), __FUNCTION__, frame_number);
     return ALREADY_EXISTS;
   }
 
@@ -174,8 +191,8 @@
 
   if (stream_pending_buffers_map_[stream_id].find(frame_number) !=
       stream_pending_buffers_map_[stream_id].end()) {
-    ALOGE("%s: Pending buffer of stream %u for frame %u already exists.",
-          __FUNCTION__, stream_id, frame_number);
+    ALOGE("[%s] %s: Pending buffer of stream %u for frame %u already exists.",
+          name_.c_str(), __FUNCTION__, stream_id, frame_number);
     return ALREADY_EXISTS;
   }
 
@@ -205,8 +222,8 @@
                             std::move(result->physical_metadata),
                             result->partial_result);
     if (res != OK) {
-      ALOGE("%s: Adding result metadata failed: %s (%d)", __FUNCTION__,
-            strerror(-res), res);
+      ALOGE("[%s] %s: Adding result metadata failed: %s (%d)", name_.c_str(),
+            __FUNCTION__, strerror(-res), res);
       failed = true;
     }
   }
@@ -214,8 +231,8 @@
   for (auto& buffer : result->output_buffers) {
     res = AddBuffer(frame_number, buffer);
     if (res != OK) {
-      ALOGE("%s: Adding an output buffer failed: %s (%d)", __FUNCTION__,
-            strerror(-res), res);
+      ALOGE("[%s] %s: Adding an output buffer failed: %s (%d)", name_.c_str(),
+            __FUNCTION__, strerror(-res), res);
       failed = true;
     }
   }
@@ -223,8 +240,8 @@
   for (auto& buffer : result->input_buffers) {
     res = AddBuffer(frame_number, buffer);
     if (res != OK) {
-      ALOGE("%s: Adding an input buffer failed: %s (%d)", __FUNCTION__,
-            strerror(-res), res);
+      ALOGE("[%s] %s: Adding an input buffer failed: %s (%d)", name_.c_str(),
+            __FUNCTION__, strerror(-res), res);
       failed = true;
     }
   }
@@ -245,17 +262,16 @@
 
     auto shutter_it = pending_shutters_.find(frame_number);
     if (shutter_it == pending_shutters_.end()) {
-      ALOGE("%s: Cannot find the pending shutter for frame %u", __FUNCTION__,
-            frame_number);
+      ALOGE("[%s] %s: Cannot find the pending shutter for frame %u",
+            name_.c_str(), __FUNCTION__, frame_number);
       return NAME_NOT_FOUND;
     }
 
     if (shutter_it->second.ready) {
-      ALOGE("%s: Already received shutter (%" PRId64
-            ") for frame %u. New "
-            "timestamp %" PRId64,
-            __FUNCTION__, shutter_it->second.timestamp_ns, frame_number,
-            timestamp_ns);
+      ALOGE("[%s] %s: Already received shutter (%" PRId64
+            ") for frame %u. New timestamp %" PRId64,
+            name_.c_str(), __FUNCTION__, shutter_it->second.timestamp_ns,
+            frame_number, timestamp_ns);
       return ALREADY_EXISTS;
     }
 
@@ -288,8 +304,8 @@
   }
 
   NotifyMessage message = {.type = MessageType::kError, .message.error = error};
-  ALOGV("%s: Notify error %u for frame %u stream %d", __FUNCTION__,
-        error.error_code, frame_number, error.error_stream_id);
+  ALOGV("[%s] %s: Notify error %u for frame %u stream %d", name_.c_str(),
+        __FUNCTION__, error.error_code, frame_number, error.error_stream_id);
   notify_(message);
 
   return OK;
@@ -318,14 +334,14 @@
 
   auto metadata_it = pending_final_metadata_.find(frame_number);
   if (metadata_it == pending_final_metadata_.end()) {
-    ALOGE("%s: Cannot find the pending result metadata for frame %u",
-          __FUNCTION__, frame_number);
+    ALOGE("[%s] %s: Cannot find the pending result metadata for frame %u",
+          name_.c_str(), __FUNCTION__, frame_number);
     return NAME_NOT_FOUND;
   }
 
   if (metadata_it->second.ready) {
-    ALOGE("%s: Already received final result metadata for frame %u.",
-          __FUNCTION__, frame_number);
+    ALOGE("[%s] %s: Already received final result metadata for frame %u.",
+          name_.c_str(), __FUNCTION__, frame_number);
     return ALREADY_EXISTS;
   }
 
@@ -341,13 +357,15 @@
     uint32_t partial_result) {
   ATRACE_CALL();
   if (metadata == nullptr) {
-    ALOGE("%s: metadata is nullptr.", __FUNCTION__);
+    ALOGE("[%s] %s: metadata is nullptr.", name_.c_str(), __FUNCTION__);
     return BAD_VALUE;
   }
 
   if (partial_result > kPartialResultCount) {
-    ALOGE("%s: partial_result %u cannot be larger than partial result count %u",
-          __FUNCTION__, partial_result, kPartialResultCount);
+    ALOGE(
+        "[%s] %s: partial_result %u cannot be larger than partial result count "
+        "%u",
+        name_.c_str(), __FUNCTION__, partial_result, kPartialResultCount);
     return BAD_VALUE;
   }
 
@@ -370,21 +388,21 @@
   uint32_t stream_id = buffer.stream_id;
   auto pending_buffers_it = stream_pending_buffers_map_.find(stream_id);
   if (pending_buffers_it == stream_pending_buffers_map_.end()) {
-    ALOGE("%s: Cannot find the pending buffer for stream %u", __FUNCTION__,
-          stream_id);
+    ALOGE("[%s] %s: Cannot find the pending buffer for stream %u",
+          name_.c_str(), __FUNCTION__, stream_id);
     return NAME_NOT_FOUND;
   }
 
   auto pending_buffer_it = pending_buffers_it->second.find(frame_number);
   if (pending_buffer_it == pending_buffers_it->second.end()) {
-    ALOGE("%s: Cannot find the pending buffer for stream %u for frame %u",
-          __FUNCTION__, stream_id, frame_number);
+    ALOGE("[%s] %s: Cannot find the pending buffer for stream %u for frame %u",
+          name_.c_str(), __FUNCTION__, stream_id, frame_number);
     return NAME_NOT_FOUND;
   }
 
   if (pending_buffer_it->second.ready) {
-    ALOGE("%s: Already received a buffer for stream %u for frame %u",
-          __FUNCTION__, stream_id, frame_number);
+    ALOGE("[%s] %s: Already received a buffer for stream %u for frame %u",
+          name_.c_str(), __FUNCTION__, stream_id, frame_number);
     return ALREADY_EXISTS;
   }
 
@@ -395,8 +413,11 @@
 }
 
 void ResultDispatcher::NotifyCallbackThreadLoop() {
-  // max thread name len = 16
-  pthread_setname_np(pthread_self(), "ResDispatcher");
+  // '\0' counts toward the 16-character restriction.
+  constexpr int kPthreadNameLenMinusOne = 16 - 1;
+  pthread_setname_np(
+      pthread_self(),
+      name_.substr(/*pos=*/0, /*count=*/kPthreadNameLenMinusOne).c_str());
 
   while (1) {
     NotifyShutters();
@@ -405,7 +426,8 @@
 
     std::unique_lock<std::mutex> lock(notify_callback_lock_);
     if (notify_callback_thread_exiting_) {
-      ALOGV("%s: NotifyCallbackThreadLoop exits.", __FUNCTION__);
+      ALOGV("[%s] %s: NotifyCallbackThreadLoop exits.", name_.c_str(),
+            __FUNCTION__);
       return;
     }
     if (!is_result_shutter_updated_) {
@@ -422,19 +444,20 @@
 void ResultDispatcher::PrintTimeoutMessages() {
   std::lock_guard<std::mutex> lock(result_lock_);
   for (auto& [frame_number, shutter] : pending_shutters_) {
-    ALOGW("%s: pending shutter for frame %u ready %d", __FUNCTION__,
-          frame_number, shutter.ready);
+    ALOGW("[%s] %s: pending shutter for frame %u ready %d", name_.c_str(),
+          __FUNCTION__, frame_number, shutter.ready);
   }
 
   for (auto& [frame_number, final_metadata] : pending_final_metadata_) {
-    ALOGW("%s: pending final result metadaata for frame %u ready %d",
-          __FUNCTION__, frame_number, final_metadata.ready);
+    ALOGW("[%s] %s: pending final result metadaata for frame %u ready %d",
+          name_.c_str(), __FUNCTION__, frame_number, final_metadata.ready);
   }
 
   for (auto& [stream_id, pending_buffers] : stream_pending_buffers_map_) {
     for (auto& [frame_number, pending_buffer] : pending_buffers) {
-      ALOGW("%s: pending buffer of stream %d for frame %u ready %d",
-            __FUNCTION__, stream_id, frame_number, pending_buffer.ready);
+      ALOGW("[%s] %s: pending buffer of stream %d for frame %u ready %d",
+            name_.c_str(), __FUNCTION__, stream_id, frame_number,
+            pending_buffer.ready);
     }
   }
 }
@@ -442,7 +465,7 @@
 status_t ResultDispatcher::GetReadyShutterMessage(NotifyMessage* message) {
   ATRACE_CALL();
   if (message == nullptr) {
-    ALOGE("%s: message is nullptr", __FUNCTION__);
+    ALOGE("[%s] %s: message is nullptr", name_.c_str(), __FUNCTION__);
     return BAD_VALUE;
   }
 
@@ -470,9 +493,9 @@
     if (GetReadyShutterMessage(&message) != OK) {
       break;
     }
-    ALOGV("%s: Notify shutter for frame %u timestamp %" PRIu64
+    ALOGV("[%s] %s: Notify shutter for frame %u timestamp %" PRIu64
           " readout_timestamp %" PRIu64,
-          __FUNCTION__, message.message.shutter.frame_number,
+          name_.c_str(), __FUNCTION__, message.message.shutter.frame_number,
           message.message.shutter.timestamp_ns,
           message.message.shutter.readout_timestamp_ns);
     notify_(message);
@@ -484,8 +507,8 @@
     std::vector<PhysicalCameraMetadata>* physical_metadata) {
   ATRACE_CALL();
   if (final_metadata == nullptr || frame_number == nullptr) {
-    ALOGE("%s: final_metadata (%p) or frame_number (%p) is nullptr",
-          __FUNCTION__, final_metadata, frame_number);
+    ALOGE("[%s] %s: final_metadata (%p) or frame_number (%p) is nullptr",
+          name_.c_str(), __FUNCTION__, final_metadata, frame_number);
     return BAD_VALUE;
   }
 
@@ -514,7 +537,8 @@
 
   while (GetReadyFinalMetadata(&frame_number, &final_metadata,
                                &physical_metadata) == OK) {
-    ALOGV("%s: Notify final metadata for frame %u", __FUNCTION__, frame_number);
+    ALOGV("[%s] %s: Notify final metadata for frame %u", name_.c_str(),
+          __FUNCTION__, frame_number);
     NotifyResultMetadata(frame_number, std::move(final_metadata),
                          std::move(physical_metadata), kPartialResultCount);
   }
@@ -525,7 +549,7 @@
   ATRACE_CALL();
   std::lock_guard<std::mutex> lock(result_lock_);
   if (result == nullptr) {
-    ALOGE("%s: result is nullptr.", __FUNCTION__);
+    ALOGE("[%s] %s: result is nullptr.", name_.c_str(), __FUNCTION__);
     return BAD_VALUE;
   }
 
@@ -563,7 +587,7 @@
 
   while (GetReadyBufferResult(&result) == OK) {
     if (result == nullptr) {
-      ALOGE("%s: result is nullptr", __FUNCTION__);
+      ALOGE("[%s] %s: result is nullptr", name_.c_str(), __FUNCTION__);
       return;
     }
     std::lock_guard<std::mutex> lock(process_capture_result_lock_);
diff --git a/common/hal/utils/result_dispatcher.h b/common/hal/utils/result_dispatcher.h
index 19e7c9e..d610249 100644
--- a/common/hal/utils/result_dispatcher.h
+++ b/common/hal/utils/result_dispatcher.h
@@ -18,6 +18,8 @@
 #define HARDWARE_GOOGLE_CAMERA_HAL_UTILS_RESULT_DISPATCHER_H_
 
 #include <map>
+#include <string>
+#include <string_view>
 #include <thread>
 
 #include "hal_types.h"
@@ -40,7 +42,8 @@
   // notify is the function to notify shutter messages.
   static std::unique_ptr<ResultDispatcher> Create(
       uint32_t partial_result_count,
-      ProcessCaptureResultFunc process_capture_result, NotifyFunc notify);
+      ProcessCaptureResultFunc process_capture_result, NotifyFunc notify,
+      std::string_view name = "ResultDispatcher");
 
   virtual ~ResultDispatcher();
 
@@ -68,7 +71,8 @@
 
   ResultDispatcher(uint32_t partial_result_count,
                    ProcessCaptureResultFunc process_capture_result,
-                   NotifyFunc notify);
+                   NotifyFunc notify,
+                   std::string_view name = "ResultDispatcher");
 
  private:
   static constexpr uint32_t kCallbackThreadTimeoutMs = 500;
@@ -160,6 +164,9 @@
 
   void PrintTimeoutMessages();
 
+  // Name used for debugging purpose to disambiguate multiple ResultDispatchers.
+  std::string name_;
+
   std::mutex result_lock_;
 
   // Maps from frame numbers to pending shutters.
diff --git a/common/hal/utils/stream_buffer_cache_manager.cc b/common/hal/utils/stream_buffer_cache_manager.cc
index f0f9bea..2333a9d 100644
--- a/common/hal/utils/stream_buffer_cache_manager.cc
+++ b/common/hal/utils/stream_buffer_cache_manager.cc
@@ -223,7 +223,7 @@
 }
 
 void StreamBufferCacheManager::WorkloadThreadLoop() {
-  if (property_get_bool(kRaiseBufAllocationPriority, false)) {
+  if (property_get_bool(kRaiseBufAllocationPriority, true)) {
     pid_t tid = gettid();
     setpriority(PRIO_PROCESS, tid, -20);
   }
diff --git a/common/hal/utils/utils.cc b/common/hal/utils/utils.cc
index 6e0ba2f..751713e 100644
--- a/common/hal/utils/utils.cc
+++ b/common/hal/utils/utils.cc
@@ -520,6 +520,10 @@
   return OK;
 }
 
+bool IsSecuredStream(const Stream& stream) {
+  return (stream.usage & GRALLOC_USAGE_PROTECTED) != 0u;
+}
+
 }  // namespace utils
 }  // namespace google_camera_hal
 }  // namespace android
diff --git a/common/hal/utils/utils.h b/common/hal/utils/utils.h
index 699be9d..c3b0612 100644
--- a/common/hal/utils/utils.h
+++ b/common/hal/utils/utils.h
@@ -38,6 +38,7 @@
 bool IsDepthStream(const Stream& stream);
 bool IsOutputZslStream(const Stream& stream);
 bool IsSoftwareDenoiseEligibleSnapshotStream(const Stream& stream);
+bool IsSecuredStream(const Stream& stream);
 
 bool HasCapability(const HalCameraMetadata* metadata, uint8_t capability);
 
diff --git a/common/hal/utils/zsl_result_dispatcher.cc b/common/hal/utils/zsl_result_dispatcher.cc
index e74d803..6389041 100644
--- a/common/hal/utils/zsl_result_dispatcher.cc
+++ b/common/hal/utils/zsl_result_dispatcher.cc
@@ -63,17 +63,17 @@
   notify_ = NotifyFunc(
       [this](const NotifyMessage& message) { NotifyHalMessage(message); });
 
-  normal_result_dispatcher_ =
-      std::unique_ptr<ResultDispatcher>(new ResultDispatcher(
-          partial_result_count, process_capture_result_, notify_));
+  normal_result_dispatcher_ = std::unique_ptr<ResultDispatcher>(
+      new ResultDispatcher(partial_result_count, process_capture_result_,
+                           notify_, "ZslNormalDispatcher"));
   if (normal_result_dispatcher_ == nullptr) {
     ALOGE("%s: Creating normal_result_dispatcher_ failed.", __FUNCTION__);
     return BAD_VALUE;
   }
 
-  zsl_result_dispatcher_ =
-      std::unique_ptr<ResultDispatcher>(new ResultDispatcher(
-          partial_result_count, process_capture_result_, notify_));
+  zsl_result_dispatcher_ = std::unique_ptr<ResultDispatcher>(
+      new ResultDispatcher(partial_result_count, process_capture_result_,
+                           notify_, "ZslZslDispatcher"));
   if (zsl_result_dispatcher_ == nullptr) {
     ALOGE("%s: Creating zsl_result_dispatcher_ failed.", __FUNCTION__);
     return BAD_VALUE;
diff --git a/common/sensor_listener/goog_sensor_motion.cc b/common/sensor_listener/goog_sensor_motion.cc
index f312ced..b12ea8e 100644
--- a/common/sensor_listener/goog_sensor_motion.cc
+++ b/common/sensor_listener/goog_sensor_motion.cc
@@ -147,6 +147,13 @@
   event_arrival_timestamps->clear();
 
   std::lock_guard<std::mutex> l(event_buffer_lock_);
+
+  event_timestamps->reserve(event_buffer_.size());
+  motion_vector_x->reserve(event_buffer_.size());
+  motion_vector_y->reserve(event_buffer_.size());
+  motion_vector_z->reserve(event_buffer_.size());
+  event_arrival_timestamps->reserve(event_buffer_.size());
+
   for (const auto& event : event_buffer_) {
     int64_t event_time = event.sensor_event.timestamp;
     if (event_time <= start_time || event_time > end_time) {