1 /* 2 * Copyright 2014,2016 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 ANDROID_SERVERS_STREAMSPLITTER_H 18 #define ANDROID_SERVERS_STREAMSPLITTER_H 19 20 #include <unordered_set> 21 22 #include <camera/CameraMetadata.h> 23 24 #include <gui/IConsumerListener.h> 25 #include <gui/IProducerListener.h> 26 #include <gui/BufferItemConsumer.h> 27 28 #include <utils/Condition.h> 29 #include <utils/Mutex.h> 30 #include <utils/StrongPointer.h> 31 #include <utils/Timers.h> 32 33 #define SP_LOGV(x, ...) ALOGV("[%s] " x, mConsumerName.string(), ##__VA_ARGS__) 34 #define SP_LOGI(x, ...) ALOGI("[%s] " x, mConsumerName.string(), ##__VA_ARGS__) 35 #define SP_LOGW(x, ...) ALOGW("[%s] " x, mConsumerName.string(), ##__VA_ARGS__) 36 #define SP_LOGE(x, ...) ALOGE("[%s] " x, mConsumerName.string(), ##__VA_ARGS__) 37 38 namespace android { 39 40 class GraphicBuffer; 41 class IGraphicBufferConsumer; 42 class IGraphicBufferProducer; 43 44 // Camera3StreamSplitter is an autonomous class that manages one input BufferQueue 45 // and multiple output BufferQueues. By using the buffer attach and detach logic 46 // in BufferQueue, it is able to present the illusion of a single split 47 // BufferQueue, where each buffer queued to the input is available to be 48 // acquired by each of the outputs, and is able to be dequeued by the input 49 // again only once all of the outputs have released it. 50 class Camera3StreamSplitter : public BnConsumerListener { 51 public: 52 53 // Constructor 54 Camera3StreamSplitter(bool useHalBufManager = false); 55 56 // Connect to the stream splitter by creating buffer queue and connecting it 57 // with output surfaces. 58 status_t connect(const std::unordered_map<size_t, sp<Surface>> &surfaces, 59 uint64_t consumerUsage, uint64_t producerUsage, size_t halMaxBuffers, uint32_t width, 60 uint32_t height, android::PixelFormat format, sp<Surface>* consumer, 61 int64_t dynamicRangeProfile); 62 63 // addOutput adds an output BufferQueue to the splitter. The splitter 64 // connects to outputQueue as a CPU producer, and any buffers queued 65 // to the input will be queued to each output. If any output is abandoned 66 // by its consumer, the splitter will abandon its input queue (see onAbandoned). 67 // 68 // A return value other than NO_ERROR means that an error has occurred and 69 // outputQueue has not been added to the splitter. BAD_VALUE is returned if 70 // outputQueue is NULL. See IGraphicBufferProducer::connect for explanations 71 // of other error codes. 72 status_t addOutput(size_t surfaceId, const sp<Surface>& outputQueue); 73 74 //removeOutput will remove a BufferQueue that was previously added to 75 //the splitter outputs. Any pending buffers in the BufferQueue will get 76 //reclaimed. 77 status_t removeOutput(size_t surfaceId); 78 79 // Notification that the graphic buffer has been released to the input 80 // BufferQueue. The buffer should be reused by the camera device instead of 81 // queuing to the outputs. 82 status_t notifyBufferReleased(const sp<GraphicBuffer>& buffer); 83 84 // Attach a buffer to the specified outputs. This call reserves a buffer 85 // slot in the output queue. 86 status_t attachBufferToOutputs(ANativeWindowBuffer* anb, 87 const std::vector<size_t>& surface_ids); 88 89 // Get return value of onFrameAvailable to work around problem that 90 // onFrameAvailable is void. This function should be called by the producer 91 // right after calling queueBuffer(). 92 status_t getOnFrameAvailableResult(); 93 94 // Disconnect the buffer queue from output surfaces. 95 void disconnect(); 96 97 private: 98 // From IConsumerListener 99 // 100 // During this callback, we store some tracking information, detach the 101 // buffer from the input, and attach it to each of the outputs. This call 102 // can block if there are too many outstanding buffers. If it blocks, it 103 // will resume when onBufferReleasedByOutput releases a buffer back to the 104 // input. 105 void onFrameAvailable(const BufferItem& item) override; 106 107 // From IConsumerListener 108 // 109 // Similar to onFrameAvailable, but buffer item is indeed replacing a buffer 110 // in the buffer queue. This can happen when buffer queue is in droppable 111 // mode. 112 void onFrameReplaced(const BufferItem& item) override; 113 114 // From IConsumerListener 115 // We don't care about released buffers because we detach each buffer as 116 // soon as we acquire it. See the comment for onBufferReleased below for 117 // some clarifying notes about the name. onBuffersReleased()118 void onBuffersReleased() override {} 119 120 // From IConsumerListener 121 // We don't care about sideband streams, since we won't be splitting them onSidebandStreamChanged()122 void onSidebandStreamChanged() override {} 123 124 // This is the implementation of the onBufferReleased callback from 125 // IProducerListener. It gets called from an OutputListener (see below), and 126 // 'from' is which producer interface from which the callback was received. 127 // 128 // During this callback, we detach the buffer from the output queue that 129 // generated the callback, update our state tracking to see if this is the 130 // last output releasing the buffer, and if so, release it to the input. 131 // If we release the buffer to the input, we allow a blocked 132 // onFrameAvailable call to proceed. 133 void onBufferReleasedByOutput(const sp<IGraphicBufferProducer>& from); 134 135 // Called by outputBufferLocked when a buffer in the async buffer queue got replaced. 136 void onBufferReplacedLocked(const sp<IGraphicBufferProducer>& from, size_t surfaceId); 137 138 // When this is called, the splitter disconnects from (i.e., abandons) its 139 // input queue and signals any waiting onFrameAvailable calls to wake up. 140 // It still processes callbacks from other outputs, but only detaches their 141 // buffers so they can continue operating until they run out of buffers to 142 // acquire. This must be called with mMutex locked. 143 void onAbandonedLocked(); 144 145 // Decrement the buffer's reference count. Once the reference count becomes 146 // 0, return the buffer back to the input BufferQueue. 147 void decrementBufRefCountLocked(uint64_t id, size_t surfaceId); 148 149 // Check for and handle any output surface dequeue errors. 150 void handleOutputDequeueStatusLocked(status_t res, int slot); 151 152 // Handles released output surface buffers. 153 void returnOutputBufferLocked(const sp<Fence>& fence, const sp<IGraphicBufferProducer>& from, 154 size_t surfaceId, int slot); 155 156 // This is a thin wrapper class that lets us determine which BufferQueue 157 // the IProducerListener::onBufferReleased callback is associated with. We 158 // create one of these per output BufferQueue, and then pass the producer 159 // into onBufferReleasedByOutput above. 160 class OutputListener : public BnProducerListener, 161 public IBinder::DeathRecipient { 162 public: 163 OutputListener(wp<Camera3StreamSplitter> splitter, 164 wp<IGraphicBufferProducer> output); 165 virtual ~OutputListener() = default; 166 167 // From IProducerListener 168 void onBufferReleased() override; 169 170 // From IBinder::DeathRecipient 171 void binderDied(const wp<IBinder>& who) override; 172 173 private: 174 wp<Camera3StreamSplitter> mSplitter; 175 wp<IGraphicBufferProducer> mOutput; 176 }; 177 178 class BufferTracker { 179 public: 180 BufferTracker(const sp<GraphicBuffer>& buffer, 181 const std::vector<size_t>& requestedSurfaces); 182 ~BufferTracker() = default; 183 getBuffer()184 const sp<GraphicBuffer>& getBuffer() const { return mBuffer; } getMergedFence()185 const sp<Fence>& getMergedFence() const { return mMergedFence; } 186 187 void mergeFence(const sp<Fence>& with); 188 189 // Returns the new value 190 // Only called while mMutex is held 191 size_t decrementReferenceCountLocked(size_t surfaceId); 192 requestedSurfaces()193 const std::vector<size_t> requestedSurfaces() const { return mRequestedSurfaces; } 194 195 private: 196 197 // Disallow copying 198 BufferTracker(const BufferTracker& other); 199 BufferTracker& operator=(const BufferTracker& other); 200 201 sp<GraphicBuffer> mBuffer; // One instance that holds this native handle 202 sp<Fence> mMergedFence; 203 204 // Request surfaces for a particular buffer. And when the buffer becomes 205 // available from the input queue, the registered surfaces are used to decide 206 // which output is the buffer sent to. 207 std::vector<size_t> mRequestedSurfaces; 208 size_t mReferenceCount; 209 }; 210 211 // Must be accessed through RefBase 212 virtual ~Camera3StreamSplitter(); 213 214 status_t addOutputLocked(size_t surfaceId, const sp<Surface>& outputQueue); 215 216 status_t removeOutputLocked(size_t surfaceId); 217 218 // Send a buffer to particular output, and increment the reference count 219 // of the buffer. If this output is abandoned, the buffer's reference count 220 // won't be incremented. 221 status_t outputBufferLocked(const sp<IGraphicBufferProducer>& output, 222 const BufferItem& bufferItem, size_t surfaceId); 223 224 // Get unique name for the buffer queue consumer 225 String8 getUniqueConsumerName(); 226 227 // Helper function to get the BufferQueue slot where a particular buffer is attached to. 228 int getSlotForOutputLocked(const sp<IGraphicBufferProducer>& gbp, 229 const sp<GraphicBuffer>& gb); 230 231 // Sum of max consumer buffers for all outputs 232 size_t mMaxConsumerBuffers = 0; 233 size_t mMaxHalBuffers = 0; 234 uint32_t mWidth = 0; 235 uint32_t mHeight = 0; 236 android::PixelFormat mFormat = android::PIXEL_FORMAT_NONE; 237 uint64_t mProducerUsage = 0; 238 int mDynamicRangeProfile = ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD; 239 240 // The attachBuffer call will happen on different thread according to mUseHalBufManager and have 241 // different timing constraint. 242 static const nsecs_t kNormalDequeueBufferTimeout = s2ns(1); // 1 sec 243 static const nsecs_t kHalBufMgrDequeueBufferTimeout = ms2ns(1); // 1 msec 244 245 Mutex mMutex; 246 247 sp<IGraphicBufferProducer> mProducer; 248 sp<IGraphicBufferConsumer> mConsumer; 249 sp<BufferItemConsumer> mBufferItemConsumer; 250 sp<Surface> mSurface; 251 252 //Map graphic buffer ids -> buffer items 253 std::unordered_map<uint64_t, BufferItem> mInputSlots; 254 255 //Map surface ids -> gbp outputs 256 std::unordered_map<int, sp<IGraphicBufferProducer> > mOutputs; 257 258 //Map surface ids -> gbp outputs 259 std::unordered_map<int, sp<Surface>> mOutputSurfaces; 260 261 //Map surface ids -> consumer buffer count 262 std::unordered_map<int, size_t > mConsumerBufferCount; 263 264 // Map of GraphicBuffer IDs (GraphicBuffer::getId()) to buffer tracking 265 // objects (which are mostly for counting how many outputs have released the 266 // buffer, but also contain merged release fences). 267 std::unordered_map<uint64_t, std::unique_ptr<BufferTracker> > mBuffers; 268 269 struct GBPHash { operatorGBPHash270 std::size_t operator()(const sp<IGraphicBufferProducer>& producer) const { 271 return std::hash<IGraphicBufferProducer *>{}(producer.get()); 272 } 273 }; 274 275 std::unordered_map<sp<IGraphicBufferProducer>, sp<OutputListener>, 276 GBPHash> mNotifiers; 277 278 typedef std::vector<sp<GraphicBuffer>> OutputSlots; 279 std::unordered_map<sp<IGraphicBufferProducer>, std::unique_ptr<OutputSlots>, 280 GBPHash> mOutputSlots; 281 282 //A set of buffers that could potentially stay in some of the outputs after removal 283 //and therefore should be detached from the input queue. 284 std::unordered_set<uint64_t> mDetachedBuffers; 285 286 // Latest onFrameAvailable return value 287 std::atomic<status_t> mOnFrameAvailableRes{0}; 288 289 // Currently acquired input buffers 290 size_t mAcquiredInputBuffers; 291 292 String8 mConsumerName; 293 294 const bool mUseHalBufManager; 295 }; 296 297 } // namespace android 298 299 #endif 300