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 #ifndef HARDWARE_GOOGLE_CAMERA_HAL_UTILS_RESULT_DISPATCHER_H_
18 #define HARDWARE_GOOGLE_CAMERA_HAL_UTILS_RESULT_DISPATCHER_H_
19 
20 #include <android-base/thread_annotations.h>
21 
22 #include <map>
23 #include <string>
24 #include <string_view>
25 #include <thread>
26 
27 #include "hal_types.h"
28 
29 namespace android {
30 namespace google_camera_hal {
31 
32 // ResultDispatcher dispatches capture results in the order of frame numbers,
33 // including result metadata, shutters, and stream buffers.
34 //
35 // The client can add results and shutters via AddResult() (or AddBatchResult())
36 // and AddShutter() in any order. ResultDispatcher will invoke
37 // ProcessCaptureResultFunc (or ProcessBatchCaptureResultFunc) and NotifyFunc to
38 // notify result metadata, shutters, and stream buffers in the in the order of
39 // increasing frame numbers.
40 class ResultDispatcher {
41  public:
42   // Create a ResultDispatcher.
43   // partial_result_count is the partial result count.
44   // process_capture_result is the callback to notify a capture result.
45   // process_batch_capture_result is the callback to notify multiple capture
46   // results at once.
47   // stream_config is the session stream configuration.
48   // notify is the function to notify shutter messages.
49   // If process_batch_capture_result is not null, it has the priority over
50   // process_capture_result.
51   static std::unique_ptr<ResultDispatcher> Create(
52       uint32_t partial_result_count,
53       ProcessCaptureResultFunc process_capture_result,
54       ProcessBatchCaptureResultFunc process_batch_capture_result,
55       NotifyFunc notify, const StreamConfiguration& stream_config,
56       std::string_view name = "ResultDispatcher");
57 
58   virtual ~ResultDispatcher();
59 
60   // Add a pending request. This tells ResultDispatcher to watch for
61   // the shutter, result metadata, and stream buffers for this request,
62   // that will be added later via AddResult() and AddShutter().
63   status_t AddPendingRequest(const CaptureRequest& pending_request)
64       EXCLUDES(result_lock_);
65 
66   // Add a ready result. If the result doesn't belong to a pending request that
67   // was previously added via AddPendingRequest(), an error will be returned.
68   status_t AddResult(std::unique_ptr<CaptureResult> result);
69 
70   // Add a batch of results which contains multiple ready results.
71   status_t AddBatchResult(std::vector<std::unique_ptr<CaptureResult>> results);
72 
73   // Add a shutter for a frame number. If the frame number doesn't belong to a
74   // pending request that was previously added via AddPendingRequest(), an error
75   // will be returned.
76   status_t AddShutter(uint32_t frame_number, int64_t timestamp_ns,
77                       int64_t readout_timestamp_ns) EXCLUDES(result_lock_);
78 
79   // Add an error notification for a frame number. When this is called, we no
80   // longer wait for a shutter message or result metadata for the given frame.
81   status_t AddError(const ErrorMessage& error) EXCLUDES(result_lock_);
82 
83   // Remove a pending request.
84   void RemovePendingRequest(uint32_t frame_number) EXCLUDES(result_lock_);
85 
86   ResultDispatcher(uint32_t partial_result_count,
87                    ProcessCaptureResultFunc process_capture_result,
88                    ProcessBatchCaptureResultFunc process_batch_capture_result,
89                    NotifyFunc notify, const StreamConfiguration& stream_config,
90                    std::string_view name = "ResultDispatcher");
91 
92  private:
93   static constexpr uint32_t kCallbackThreadTimeoutMs = 500;
94   const uint32_t kPartialResultCount;
95 
96   // Define the request types. Normal is for general application.
97   // Reprocess is for reprocessing requests.
98   enum class RequestType : uint32_t {
99     kNormal = 0,
100     kReprocess,
101   };
102 
103   // Define the stream key types. Single stream type is for normal streams.
104   // Group stream type is for the group streams of multi-resolution streams.
105   enum class StreamKeyType : uint32_t {
106     kSingleStream = 0,
107     kGroupStream,
108   };
109 
110   // The key of the stream_pending_buffers_map_, which has different types.
111   // Type kSingleStream indicates the StreamKey represents a single stream, and
112   // the id will be the stream id.
113   // Type kGroupStream indicates the StreamKey represents a stream group, and
114   // the id will be the stream group id. All of the buffers of certain stream
115   // group will be tracked together, as there's only one buffer from the group
116   // streams should be returned each request.
117   typedef std::pair</*id=*/int32_t, StreamKeyType> StreamKey;
118 
119   // Define a pending shutter that will be ready later when AddShutter() is
120   // called.
121   struct PendingShutter {
122     int64_t timestamp_ns = 0;
123     int64_t readout_timestamp_ns = 0;
124     bool ready = false;
125   };
126 
127   // Define a pending buffer that will be ready later when AddResult() is
128   // called.
129   struct PendingBuffer {
130     StreamBuffer buffer = {};
131     bool is_input = false;
132     bool ready = false;
133   };
134 
135   // Define a pending result metadata that will be ready later when AddResult()
136   // is called.
137   struct PendingResultMetadata {
138     std::unique_ptr<HalCameraMetadata> metadata;
139     std::vector<PhysicalCameraMetadata> physical_metadata;
140     uint32_t partial_result_count = 0;
141     bool ready = false;
142   };
143 
144   // Template class for pending data queues.
145   // Pending data can be shutter, early/final result metadata, buffer, and each
146   // type of data has its own queue. Handles having multiple queues per request
147   // type, adds to the appropriate queue and checks all queues for ready data.
148   template <typename FrameData>
149   class DispatchQueue {
150    public:
151     DispatchQueue(std::string_view dispatcher_name = "DefaultDispatcher",
152                   std::string_view data_name = "DefaultData");
153 
154     // Add a request to the dispatch queue that will later be populated with
155     // results.
156     status_t AddRequest(uint32_t frame_number, RequestType request_type);
157 
158     // Remove request for frame number from data queue
159     void RemoveRequest(uint32_t frame_number);
160 
161     // Add results for the request in the queue of the same frame number
162     status_t AddResult(uint32_t frame_number, FrameData result);
163 
164     // Move ready data to caller, returns failure status if no data is ready
165     // Data is ready if its result has been added and is the first in its queue
166     status_t GetReadyData(uint32_t& frame_number, FrameData& ready_data);
167 
168     void PrintTimeoutMessages();
169 
170    private:
171     // Name of the dispatcher for debug messages
172     std::string_view dispatcher_name_;
173     // Name of the data (shutter, metadata, buffer + stream key) for debug
174     // messages
175     std::string data_name_;
176 
177     // Queue for data of reprocess request types
178     std::map<uint32_t, FrameData> reprocess_request_map_;
179     // Queue for data of normal request types
180     std::map<uint32_t, FrameData> normal_request_map_;
181   };
182 
183   // Add a pending shutter, result metadata, and buffers for a frame number.
184   status_t AddPendingRequestLocked(const CaptureRequest& pending_request)
185       EXCLUSIVE_LOCKS_REQUIRED(result_lock_);
186 
187   // Add a pending buffer for the associated stream
188   status_t AddPendingBufferLocked(uint32_t frame_number,
189                                   const StreamBuffer& buffer,
190                                   RequestType request_type)
191       EXCLUSIVE_LOCKS_REQUIRED(result_lock_);
192 
193   // Remove pending shutter, result metadata, and buffers for a frame number.
194   void RemovePendingRequestLocked(uint32_t frame_number)
195       EXCLUSIVE_LOCKS_REQUIRED(result_lock_);
196 
197   // Add result metadata and buffers to the storage to send them from the notify
198   // callback thread.
199   status_t AddResultImpl(std::unique_ptr<CaptureResult> result);
200 
201   // Compose a capture result which contains a result metadata.
202   std::unique_ptr<CaptureResult> MakeResultMetadata(
203       uint32_t frame_number, std::unique_ptr<HalCameraMetadata> metadata,
204       std::vector<PhysicalCameraMetadata> physical_metadata,
205       uint32_t partial_result);
206 
207   // Invoke the capture result callback to notify capture results.
208   void NotifyCaptureResults(std::vector<std::unique_ptr<CaptureResult>> results);
209 
210   status_t AddResultMetadata(
211       uint32_t frame_number, std::unique_ptr<HalCameraMetadata> metadata,
212       std::vector<PhysicalCameraMetadata> physical_metadata,
213       uint32_t partial_result) EXCLUDES(result_lock_);
214   ;
215 
216   status_t AddBuffer(uint32_t frame_number, StreamBuffer buffer, bool is_input)
217       EXCLUDES(result_lock_);
218 
219   // Check all pending shutters and invoke notify_ with shutters that are ready.
220   void NotifyShutters() EXCLUDES(result_lock_);
221 
222   // Check all pending result metadata and invoke the capture result callback
223   // with the result metadata that are ready.
224   void NotifyResultMetadata() EXCLUDES(result_lock_);
225 
226   // Get a result with a buffer that is ready to be notified via the capture
227   // result callback.
228   status_t GetReadyBufferResult(std::unique_ptr<CaptureResult>* result)
229       EXCLUDES(result_lock_);
230 
231   // Check all pending buffers and invoke notify_ with buffers that are ready.
232   void NotifyBuffers();
233 
234   // Thread loop to check pending shutters, result metadata, and buffers. It
235   // notifies the client when one is ready.
236   void NotifyCallbackThreadLoop();
237 
238   void PrintTimeoutMessages() EXCLUDES(result_lock_);
239 
240   // Initialize the group stream ids map if needed. Must be protected with
241   // result_lock_.
242   void InitializeGroupStreamIdsMap(const StreamConfiguration& stream_config)
243       EXCLUDES(result_lock_);
244 
245   // Name used for debugging purpose to disambiguate multiple ResultDispatchers.
246   std::string name_;
247 
248   std::mutex result_lock_;
249 
250   // Queue for shutter data.
251   DispatchQueue<PendingShutter> pending_shutters_ GUARDED_BY(result_lock_);
252   // Queue for early result metadata.
253   DispatchQueue<PendingResultMetadata> pending_early_metadata_
254       GUARDED_BY(result_lock_);
255   // Queue for final result metadata.
256   DispatchQueue<PendingResultMetadata> pending_final_metadata_
257       GUARDED_BY(result_lock_);
258 
259   // Maps from a stream or stream group to a queue for buffer data.
260   // Protected by result_lock_.
261   // For single streams, pending buffers would be tracked by streams.
262   // For multi-resolution streams, camera HAL can return only one stream buffer
263   // within the same stream group each request. So all of the buffers of certain
264   // stream group will be tracked together via a single map.
265   // TODO: b/347771069 - Update to use unordered_map
266   std::map<StreamKey, DispatchQueue<PendingBuffer>> stream_pending_buffers_map_
267       GUARDED_BY(result_lock_);
268 
269   // Create a StreamKey for a stream
270   inline StreamKey CreateStreamKey(int32_t stream_id) const;
271 
272   // Dump a StreamKey to a debug string
273   inline std::string DumpStreamKey(const StreamKey& stream_key) const;
274 
275   std::mutex process_capture_result_lock_;
276   ProcessCaptureResultFunc process_capture_result_;
277   ProcessBatchCaptureResultFunc process_batch_capture_result_;
278   NotifyFunc notify_;
279 
280   // A thread to run NotifyCallbackThreadLoop().
281   std::thread notify_callback_thread_;
282 
283   std::mutex notify_callback_lock_;
284 
285   // Condition to wake up notify_callback_thread_. Used with
286   // notify_callback_lock.
287   std::condition_variable notify_callback_condition_;
288 
289   // Protected by notify_callback_lock.
290   bool notify_callback_thread_exiting_ = false;
291 
292   // State of callback thread is notified or not.
293   volatile bool is_result_shutter_updated_ = false;
294 
295   // A map of group streams only, from stream ID to the group ID it belongs.
296   std::map</*stream id=*/int32_t, /*group id=*/int32_t> group_stream_map_;
297 };
298 
299 }  // namespace google_camera_hal
300 }  // namespace android
301 
302 #endif  // HARDWARE_GOOGLE_CAMERA_HAL_UTILS_RESULT_DISPATCHER_H_
303