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