Merge "BufferQueue: Guard against unbounded queue growth"
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index 34dc9fe..099c3df 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -40,7 +40,7 @@
 
 #define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
 
-enum { MAX_SYS_FILES = 8 };
+enum { MAX_SYS_FILES = 10 };
 
 const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
 const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
@@ -99,6 +99,12 @@
         { REQ,      "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
     } },
     { "disk",       "Disk I/O",         0, {
+        { REQ,      "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
+        { REQ,      "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
+        { REQ,      "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
+        { REQ,      "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
+        { REQ,      "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
+        { REQ,      "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
         { REQ,      "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
         { REQ,      "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
         { REQ,      "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
diff --git a/include/gui/BufferQueue.h b/include/gui/BufferQueue.h
index da876ec..891383d 100644
--- a/include/gui/BufferQueue.h
+++ b/include/gui/BufferQueue.h
@@ -69,7 +69,7 @@
 public:
     // BufferQueue will keep track of at most this value of buffers.
     // Attempts at runtime to increase the number of buffers past this will fail.
-    enum { NUM_BUFFER_SLOTS = 32 };
+    enum { NUM_BUFFER_SLOTS = BufferQueueDefs::NUM_BUFFER_SLOTS };
     // Used as a placeholder slot# when the value isn't pointing to an existing buffer.
     enum { INVALID_BUFFER_SLOT = IGraphicBufferConsumer::BufferItem::INVALID_BUFFER_SLOT };
     // Alias to <IGraphicBufferConsumer.h> -- please scope from there in future code!
@@ -199,6 +199,10 @@
     // See IGraphicBufferProducer::detachBuffer
     virtual status_t detachProducerBuffer(int slot);
 
+    // See IGraphicBufferProducer::detachNextBuffer
+    virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+            sp<Fence>* outFence);
+
     // See IGraphicBufferProducer::attachBuffer
     virtual status_t attachProducerBuffer(int* slot,
             const sp<GraphicBuffer>& buffer);
@@ -317,7 +321,7 @@
     // but have not yet been released by the consumer.
     //
     // This should be called from the onBuffersReleased() callback.
-    virtual status_t getReleasedBuffers(uint32_t* slotMask);
+    virtual status_t getReleasedBuffers(uint64_t* slotMask);
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // dequeueBuffer when a width and height of zero is requested.  Default
diff --git a/include/gui/BufferQueueConsumer.h b/include/gui/BufferQueueConsumer.h
index 7f24c83..1912ed0 100644
--- a/include/gui/BufferQueueConsumer.h
+++ b/include/gui/BufferQueueConsumer.h
@@ -93,7 +93,7 @@
     // but have not yet been released by the consumer.
     //
     // This should be called from the onBuffersReleased() callback.
-    virtual status_t getReleasedBuffers(uint32_t* outSlotMask);
+    virtual status_t getReleasedBuffers(uint64_t* outSlotMask);
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // dequeueBuffer when a width and height of zero is requested.  Default
diff --git a/include/gui/BufferQueueDefs.h b/include/gui/BufferQueueDefs.h
index bccc881..83e9580 100644
--- a/include/gui/BufferQueueDefs.h
+++ b/include/gui/BufferQueueDefs.h
@@ -26,7 +26,7 @@
         // BufferQueue will keep track of at most this value of buffers.
         // Attempts at runtime to increase the number of buffers past this
         // will fail.
-        enum { NUM_BUFFER_SLOTS = 32 };
+        enum { NUM_BUFFER_SLOTS = 64 };
 
         typedef BufferSlot SlotsType[NUM_BUFFER_SLOTS];
     } // namespace BufferQueueDefs
diff --git a/include/gui/BufferQueueProducer.h b/include/gui/BufferQueueProducer.h
index 04692a5..9df3633 100644
--- a/include/gui/BufferQueueProducer.h
+++ b/include/gui/BufferQueueProducer.h
@@ -99,6 +99,10 @@
     // See IGraphicBufferProducer::detachBuffer
     virtual status_t detachBuffer(int slot);
 
+    // See IGraphicBufferProducer::detachNextBuffer
+    virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+            sp<Fence>* outFence);
+
     // See IGraphicBufferProducer::attachBuffer
     virtual status_t attachBuffer(int* outSlot, const sp<GraphicBuffer>& buffer);
 
diff --git a/include/gui/IGraphicBufferConsumer.h b/include/gui/IGraphicBufferConsumer.h
index b0d4c76..15f51fe 100644
--- a/include/gui/IGraphicBufferConsumer.h
+++ b/include/gui/IGraphicBufferConsumer.h
@@ -27,6 +27,9 @@
 #include <binder/IInterface.h>
 #include <ui/Rect.h>
 
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
 namespace android {
 // ----------------------------------------------------------------------------
 
@@ -230,7 +233,7 @@
     //
     // Return of a value other than NO_ERROR means an error has occurred:
     // * NO_INIT - the buffer queue has been abandoned.
-    virtual status_t getReleasedBuffers(uint32_t* slotMask) = 0;
+    virtual status_t getReleasedBuffers(uint64_t* slotMask) = 0;
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // dequeueBuffer when a width and height of zero is requested.  Default
diff --git a/include/gui/IGraphicBufferProducer.h b/include/gui/IGraphicBufferProducer.h
index 2b61ab3..d9e116b 100644
--- a/include/gui/IGraphicBufferProducer.h
+++ b/include/gui/IGraphicBufferProducer.h
@@ -185,6 +185,27 @@
     //               it refers to is not currently dequeued and requested.
     virtual status_t detachBuffer(int slot) = 0;
 
+    // detachNextBuffer is equivalent to calling dequeueBuffer, requestBuffer,
+    // and detachBuffer in sequence, except for two things:
+    //
+    // 1) It is unnecessary to know the dimensions, format, or usage of the
+    //    next buffer.
+    // 2) It will not block, since if it cannot find an appropriate buffer to
+    //    return, it will return an error instead.
+    //
+    // Only slots that are free but still contain a GraphicBuffer will be
+    // considered, and the oldest of those will be returned. outBuffer is
+    // equivalent to outBuffer from the requestBuffer call, and outFence is
+    // equivalent to fence from the dequeueBuffer call.
+    //
+    // Return of a value other than NO_ERROR means an error has occurred:
+    // * NO_INIT - the buffer queue has been abandoned.
+    // * BAD_VALUE - either outBuffer or outFence were NULL.
+    // * NO_MEMORY - no slots were found that were both free and contained a
+    //               GraphicBuffer.
+    virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+            sp<Fence>* outFence) = 0;
+
     // attachBuffer attempts to transfer ownership of a buffer to the buffer
     // queue. If this call succeeds, it will be as if this buffer was dequeued
     // from the returned slot number. As such, this call will fail if attaching
diff --git a/include/gui/StreamSplitter.h b/include/gui/StreamSplitter.h
new file mode 100644
index 0000000..f927953
--- /dev/null
+++ b/include/gui/StreamSplitter.h
@@ -0,0 +1,184 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_GUI_STREAMSPLITTER_H
+#define ANDROID_GUI_STREAMSPLITTER_H
+
+#include <gui/IConsumerListener.h>
+#include <gui/IProducerListener.h>
+
+#include <utils/Condition.h>
+#include <utils/KeyedVector.h>
+#include <utils/Mutex.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+class GraphicBuffer;
+class IGraphicBufferConsumer;
+class IGraphicBufferProducer;
+
+// StreamSplitter is an autonomous class that manages one input BufferQueue
+// and multiple output BufferQueues. By using the buffer attach and detach logic
+// in BufferQueue, it is able to present the illusion of a single split
+// BufferQueue, where each buffer queued to the input is available to be
+// acquired by each of the outputs, and is able to be dequeued by the input
+// again only once all of the outputs have released it.
+class StreamSplitter : public BnConsumerListener {
+public:
+    // createSplitter creates a new splitter, outSplitter, using inputQueue as
+    // the input BufferQueue. Output BufferQueues must be added using addOutput
+    // before queueing any buffers to the input.
+    //
+    // A return value other than NO_ERROR means that an error has occurred and
+    // outSplitter has not been modified. BAD_VALUE is returned if inputQueue or
+    // outSplitter is NULL. See IGraphicBufferConsumer::consumerConnect for
+    // explanations of other error codes.
+    static status_t createSplitter(const sp<IGraphicBufferConsumer>& inputQueue,
+            sp<StreamSplitter>* outSplitter);
+
+    // addOutput adds an output BufferQueue to the splitter. The splitter
+    // connects to outputQueue as a CPU producer, and any buffers queued
+    // to the input will be queued to each output. It is assumed that all of the
+    // outputs are added before any buffers are queued on the input. If any
+    // output is abandoned by its consumer, the splitter will abandon its input
+    // queue (see onAbandoned).
+    //
+    // A return value other than NO_ERROR means that an error has occurred and
+    // outputQueue has not been added to the splitter. BAD_VALUE is returned if
+    // outputQueue is NULL. See IGraphicBufferProducer::connect for explanations
+    // of other error codes.
+    status_t addOutput(const sp<IGraphicBufferProducer>& outputQueue);
+
+    // setName sets the consumer name of the input queue
+    void setName(const String8& name);
+
+private:
+    // From IConsumerListener
+    //
+    // During this callback, we store some tracking information, detach the
+    // buffer from the input, and attach it to each of the outputs. This call
+    // can block if there are too many outstanding buffers. If it blocks, it
+    // will resume when onBufferReleasedByOutput releases a buffer back to the
+    // input.
+    virtual void onFrameAvailable();
+
+    // From IConsumerListener
+    // We don't care about released buffers because we detach each buffer as
+    // soon as we acquire it. See the comment for onBufferReleased below for
+    // some clarifying notes about the name.
+    virtual void onBuffersReleased() {}
+
+    // From IConsumerListener
+    // We don't care about sideband streams, since we won't be splitting them
+    virtual void onSidebandStreamChanged() {}
+
+    // This is the implementation of the onBufferReleased callback from
+    // IProducerListener. It gets called from an OutputListener (see below), and
+    // 'from' is which producer interface from which the callback was received.
+    //
+    // During this callback, we detach the buffer from the output queue that
+    // generated the callback, update our state tracking to see if this is the
+    // last output releasing the buffer, and if so, release it to the input.
+    // If we release the buffer to the input, we allow a blocked
+    // onFrameAvailable call to proceed.
+    void onBufferReleasedByOutput(const sp<IGraphicBufferProducer>& from);
+
+    // When this is called, the splitter disconnects from (i.e., abandons) its
+    // input queue and signals any waiting onFrameAvailable calls to wake up.
+    // It still processes callbacks from other outputs, but only detaches their
+    // buffers so they can continue operating until they run out of buffers to
+    // acquire. This must be called with mMutex locked.
+    void onAbandonedLocked();
+
+    // This is a thin wrapper class that lets us determine which BufferQueue
+    // the IProducerListener::onBufferReleased callback is associated with. We
+    // create one of these per output BufferQueue, and then pass the producer
+    // into onBufferReleasedByOutput above.
+    class OutputListener : public BnProducerListener,
+                           public IBinder::DeathRecipient {
+    public:
+        OutputListener(const sp<StreamSplitter>& splitter,
+                const sp<IGraphicBufferProducer>& output);
+        virtual ~OutputListener();
+
+        // From IProducerListener
+        virtual void onBufferReleased();
+
+        // From IBinder::DeathRecipient
+        virtual void binderDied(const wp<IBinder>& who);
+
+    private:
+        sp<StreamSplitter> mSplitter;
+        sp<IGraphicBufferProducer> mOutput;
+    };
+
+    class BufferTracker : public LightRefBase<BufferTracker> {
+    public:
+        BufferTracker(const sp<GraphicBuffer>& buffer);
+
+        const sp<GraphicBuffer>& getBuffer() const { return mBuffer; }
+        const sp<Fence>& getMergedFence() const { return mMergedFence; }
+
+        void mergeFence(const sp<Fence>& with);
+
+        // Returns the new value
+        // Only called while mMutex is held
+        size_t incrementReleaseCountLocked() { return ++mReleaseCount; }
+
+    private:
+        // Only destroy through LightRefBase
+        friend LightRefBase<BufferTracker>;
+        ~BufferTracker();
+
+        // Disallow copying
+        BufferTracker(const BufferTracker& other);
+        BufferTracker& operator=(const BufferTracker& other);
+
+        sp<GraphicBuffer> mBuffer; // One instance that holds this native handle
+        sp<Fence> mMergedFence;
+        size_t mReleaseCount;
+    };
+
+    // Only called from createSplitter
+    StreamSplitter(const sp<IGraphicBufferConsumer>& inputQueue);
+
+    // Must be accessed through RefBase
+    virtual ~StreamSplitter();
+
+    static const int MAX_OUTSTANDING_BUFFERS = 2;
+
+    // mIsAbandoned is set to true when an output dies. Once the StreamSplitter
+    // has been abandoned, it will continue to detach buffers from other
+    // outputs, but it will disconnect from the input and not attempt to
+    // communicate with it further.
+    bool mIsAbandoned;
+
+    Mutex mMutex;
+    Condition mReleaseCondition;
+    int mOutstandingBuffers;
+    sp<IGraphicBufferConsumer> mInput;
+    Vector<sp<IGraphicBufferProducer> > mOutputs;
+
+    // Map of GraphicBuffer IDs (GraphicBuffer::getId()) to buffer tracking
+    // objects (which are mostly for counting how many outputs have released the
+    // buffer, but also contain merged release fences).
+    KeyedVector<uint64_t, sp<BufferTracker> > mBuffers;
+};
+
+} // namespace android
+
+#endif
diff --git a/libs/gui/Android.mk b/libs/gui/Android.mk
index 04a8a8d..ca94aa3 100644
--- a/libs/gui/Android.mk
+++ b/libs/gui/Android.mk
@@ -30,6 +30,7 @@
 	Sensor.cpp \
 	SensorEventQueue.cpp \
 	SensorManager.cpp \
+	StreamSplitter.cpp \
 	Surface.cpp \
 	SurfaceControl.cpp \
 	SurfaceComposerClient.cpp \
diff --git a/libs/gui/BufferQueue.cpp b/libs/gui/BufferQueue.cpp
index d04b67d..b07e115 100644
--- a/libs/gui/BufferQueue.cpp
+++ b/libs/gui/BufferQueue.cpp
@@ -103,6 +103,11 @@
     return mProducer->detachBuffer(slot);
 }
 
+status_t BufferQueue::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+        sp<Fence>* outFence) {
+    return mProducer->detachNextBuffer(outBuffer, outFence);
+}
+
 status_t BufferQueue::attachProducerBuffer(int* slot,
         const sp<GraphicBuffer>& buffer) {
     return mProducer->attachBuffer(slot, buffer);
@@ -158,7 +163,7 @@
     return mConsumer->disconnect();
 }
 
-status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
+status_t BufferQueue::getReleasedBuffers(uint64_t* slotMask) {
     return mConsumer->getReleasedBuffers(slotMask);
 }
 
diff --git a/libs/gui/BufferQueueConsumer.cpp b/libs/gui/BufferQueueConsumer.cpp
index 872eae6..f3f26ac 100644
--- a/libs/gui/BufferQueueConsumer.cpp
+++ b/libs/gui/BufferQueueConsumer.cpp
@@ -245,11 +245,27 @@
     mSlots[*outSlot].mGraphicBuffer = buffer;
     mSlots[*outSlot].mBufferState = BufferSlot::ACQUIRED;
     mSlots[*outSlot].mAttachedByConsumer = true;
-    mSlots[*outSlot].mAcquireCalled = true;
     mSlots[*outSlot].mNeedsCleanupOnRelease = false;
     mSlots[*outSlot].mFence = Fence::NO_FENCE;
     mSlots[*outSlot].mFrameNumber = 0;
 
+    // mAcquireCalled tells BufferQueue that it doesn't need to send a valid
+    // GraphicBuffer pointer on the next acquireBuffer call, which decreases
+    // Binder traffic by not un/flattening the GraphicBuffer. However, it
+    // requires that the consumer maintain a cached copy of the slot <--> buffer
+    // mappings, which is why the consumer doesn't need the valid pointer on
+    // acquire.
+    //
+    // The StreamSplitter is one of the primary users of the attach/detach
+    // logic, and while it is running, all buffers it acquires are immediately
+    // detached, and all buffers it eventually releases are ones that were
+    // attached (as opposed to having been obtained from acquireBuffer), so it
+    // doesn't make sense to maintain the slot/buffer mappings, which would
+    // become invalid for every buffer during detach/attach. By setting this to
+    // false, the valid GraphicBuffer pointer will always be sent with acquire
+    // for attached buffers.
+    mSlots[*outSlot].mAcquireCalled = false;
+
     return NO_ERROR;
 }
 
@@ -359,7 +375,7 @@
     return NO_ERROR;
 }
 
-status_t BufferQueueConsumer::getReleasedBuffers(uint32_t *outSlotMask) {
+status_t BufferQueueConsumer::getReleasedBuffers(uint64_t *outSlotMask) {
     ATRACE_CALL();
 
     if (outSlotMask == NULL) {
@@ -374,10 +390,10 @@
         return NO_INIT;
     }
 
-    uint32_t mask = 0;
+    uint64_t mask = 0;
     for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
         if (!mSlots[s].mAcquireCalled) {
-            mask |= (1u << s);
+            mask |= (1ULL << s);
         }
     }
 
@@ -387,12 +403,12 @@
     BufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
     while (current != mCore->mQueue.end()) {
         if (current->mAcquireCalled) {
-            mask &= ~(1u << current->mSlot);
+            mask &= ~(1ULL << current->mSlot);
         }
         ++current;
     }
 
-    BQ_LOGV("getReleasedBuffers: returning mask %#x", mask);
+    BQ_LOGV("getReleasedBuffers: returning mask %#" PRIx64, mask);
     *outSlotMask = mask;
     return NO_ERROR;
 }
diff --git a/libs/gui/BufferQueueCore.cpp b/libs/gui/BufferQueueCore.cpp
index 71ba4e7..593b6f1 100644
--- a/libs/gui/BufferQueueCore.cpp
+++ b/libs/gui/BufferQueueCore.cpp
@@ -191,7 +191,7 @@
         mSlots[slot].mNeedsCleanupOnRelease = true;
     }
     mSlots[slot].mBufferState = BufferSlot::FREE;
-    mSlots[slot].mFrameNumber = 0;
+    mSlots[slot].mFrameNumber = UINT32_MAX;
     mSlots[slot].mAcquireCalled = false;
 
     // Destroy fence as BufferQueue now takes ownership
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index bd9b8b2..f536a59 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -405,6 +405,50 @@
     return NO_ERROR;
 }
 
+status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+        sp<Fence>* outFence) {
+    ATRACE_CALL();
+
+    if (outBuffer == NULL) {
+        BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
+        return BAD_VALUE;
+    } else if (outFence == NULL) {
+        BQ_LOGE("detachNextBuffer: outFence must not be NULL");
+        return BAD_VALUE;
+    }
+
+    Mutex::Autolock lock(mCore->mMutex);
+
+    if (mCore->mIsAbandoned) {
+        BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
+        return NO_INIT;
+    }
+
+    // Find the oldest valid slot
+    int found = BufferQueueCore::INVALID_BUFFER_SLOT;
+    for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
+        if (mSlots[s].mBufferState == BufferSlot::FREE &&
+                mSlots[s].mGraphicBuffer != NULL) {
+            if (found == BufferQueueCore::INVALID_BUFFER_SLOT ||
+                    mSlots[s].mFrameNumber < mSlots[found].mFrameNumber) {
+                found = s;
+            }
+        }
+    }
+
+    if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
+        return NO_MEMORY;
+    }
+
+    BQ_LOGV("detachNextBuffer detached slot %d", found);
+
+    *outBuffer = mSlots[found].mGraphicBuffer;
+    *outFence = mSlots[found].mFence;
+    mCore->freeBufferLocked(found);
+
+    return NO_ERROR;
+}
+
 status_t BufferQueueProducer::attachBuffer(int* outSlot,
         const sp<android::GraphicBuffer>& buffer) {
     ATRACE_CALL();
diff --git a/libs/gui/ConsumerBase.cpp b/libs/gui/ConsumerBase.cpp
index b6adc54..f1b8fa8 100644
--- a/libs/gui/ConsumerBase.cpp
+++ b/libs/gui/ConsumerBase.cpp
@@ -121,10 +121,10 @@
         return;
     }
 
-    uint32_t mask = 0;
+    uint64_t mask = 0;
     mConsumer->getReleasedBuffers(&mask);
     for (int i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
-        if (mask & (1 << i)) {
+        if (mask & (1ULL << i)) {
             freeBufferLocked(i);
         }
     }
diff --git a/libs/gui/IGraphicBufferConsumer.cpp b/libs/gui/IGraphicBufferConsumer.cpp
index 1b19626..f6d087d 100644
--- a/libs/gui/IGraphicBufferConsumer.cpp
+++ b/libs/gui/IGraphicBufferConsumer.cpp
@@ -14,12 +14,6 @@
  * limitations under the License.
  */
 
-#define EGL_EGLEXT_PROTOTYPES
-
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-
-
 #include <stdint.h>
 #include <sys/types.h>
 
@@ -298,14 +292,18 @@
         return reply.readInt32();
     }
 
-    virtual status_t getReleasedBuffers(uint32_t* slotMask) {
+    virtual status_t getReleasedBuffers(uint64_t* slotMask) {
         Parcel data, reply;
+        if (slotMask == NULL) {
+            ALOGE("getReleasedBuffers: slotMask must not be NULL");
+            return BAD_VALUE;
+        }
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
         status_t result = remote()->transact(GET_RELEASED_BUFFERS, data, &reply);
         if (result != NO_ERROR) {
             return result;
         }
-        *slotMask = reply.readInt32();
+        *slotMask = reply.readInt64();
         return reply.readInt32();
     }
 
@@ -480,9 +478,9 @@
         } break;
         case GET_RELEASED_BUFFERS: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t slotMask;
+            uint64_t slotMask;
             status_t result = getReleasedBuffers(&slotMask);
-            reply->writeInt32(slotMask);
+            reply->writeInt64(slotMask);
             reply->writeInt32(result);
             return NO_ERROR;
         } break;
diff --git a/libs/gui/IGraphicBufferProducer.cpp b/libs/gui/IGraphicBufferProducer.cpp
index c0b08c1..aa6acb9 100644
--- a/libs/gui/IGraphicBufferProducer.cpp
+++ b/libs/gui/IGraphicBufferProducer.cpp
@@ -37,6 +37,7 @@
     SET_BUFFER_COUNT,
     DEQUEUE_BUFFER,
     DETACH_BUFFER,
+    DETACH_NEXT_BUFFER,
     ATTACH_BUFFER,
     QUEUE_BUFFER,
     CANCEL_BUFFER,
@@ -123,6 +124,37 @@
         return result;
     }
 
+    virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+            sp<Fence>* outFence) {
+        if (outBuffer == NULL) {
+            ALOGE("detachNextBuffer: outBuffer must not be NULL");
+            return BAD_VALUE;
+        } else if (outFence == NULL) {
+            ALOGE("detachNextBuffer: outFence must not be NULL");
+            return BAD_VALUE;
+        }
+        Parcel data, reply;
+        data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
+        status_t result = remote()->transact(DETACH_NEXT_BUFFER, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
+        if (result == NO_ERROR) {
+            bool nonNull = reply.readInt32();
+            if (nonNull) {
+                *outBuffer = new GraphicBuffer;
+                reply.read(**outBuffer);
+            }
+            nonNull = reply.readInt32();
+            if (nonNull) {
+                *outFence = new Fence;
+                reply.read(**outFence);
+            }
+        }
+        return result;
+    }
+
     virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
@@ -274,6 +306,24 @@
             reply->writeInt32(result);
             return NO_ERROR;
         } break;
+        case DETACH_NEXT_BUFFER: {
+            CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
+            sp<GraphicBuffer> buffer;
+            sp<Fence> fence;
+            int32_t result = detachNextBuffer(&buffer, &fence);
+            reply->writeInt32(result);
+            if (result == NO_ERROR) {
+                reply->writeInt32(buffer != NULL);
+                if (buffer != NULL) {
+                    reply->write(*buffer);
+                }
+                reply->writeInt32(fence != NULL);
+                if (fence != NULL) {
+                    reply->write(*fence);
+                }
+            }
+            return NO_ERROR;
+        } break;
         case ATTACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<GraphicBuffer> buffer = new GraphicBuffer();
diff --git a/libs/gui/StreamSplitter.cpp b/libs/gui/StreamSplitter.cpp
new file mode 100644
index 0000000..83e08fb
--- /dev/null
+++ b/libs/gui/StreamSplitter.cpp
@@ -0,0 +1,281 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "StreamSplitter"
+#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+//#define LOG_NDEBUG 0
+
+#include <gui/IGraphicBufferConsumer.h>
+#include <gui/IGraphicBufferProducer.h>
+#include <gui/StreamSplitter.h>
+
+#include <ui/GraphicBuffer.h>
+
+#include <binder/ProcessState.h>
+
+#include <utils/Trace.h>
+
+namespace android {
+
+status_t StreamSplitter::createSplitter(
+        const sp<IGraphicBufferConsumer>& inputQueue,
+        sp<StreamSplitter>* outSplitter) {
+    if (inputQueue == NULL) {
+        ALOGE("createSplitter: inputQueue must not be NULL");
+        return BAD_VALUE;
+    }
+    if (outSplitter == NULL) {
+        ALOGE("createSplitter: outSplitter must not be NULL");
+        return BAD_VALUE;
+    }
+
+    sp<StreamSplitter> splitter(new StreamSplitter(inputQueue));
+    status_t status = splitter->mInput->consumerConnect(splitter, false);
+    if (status == NO_ERROR) {
+        splitter->mInput->setConsumerName(String8("StreamSplitter"));
+        *outSplitter = splitter;
+    }
+    return status;
+}
+
+StreamSplitter::StreamSplitter(const sp<IGraphicBufferConsumer>& inputQueue)
+      : mIsAbandoned(false), mMutex(), mReleaseCondition(),
+        mOutstandingBuffers(0), mInput(inputQueue), mOutputs(), mBuffers() {}
+
+StreamSplitter::~StreamSplitter() {
+    mInput->consumerDisconnect();
+    Vector<sp<IGraphicBufferProducer> >::iterator output = mOutputs.begin();
+    for (; output != mOutputs.end(); ++output) {
+        (*output)->disconnect(NATIVE_WINDOW_API_CPU);
+    }
+
+    if (mBuffers.size() > 0) {
+        ALOGE("%d buffers still being tracked", mBuffers.size());
+    }
+}
+
+status_t StreamSplitter::addOutput(
+        const sp<IGraphicBufferProducer>& outputQueue) {
+    if (outputQueue == NULL) {
+        ALOGE("addOutput: outputQueue must not be NULL");
+        return BAD_VALUE;
+    }
+
+    Mutex::Autolock lock(mMutex);
+
+    IGraphicBufferProducer::QueueBufferOutput queueBufferOutput;
+    sp<OutputListener> listener(new OutputListener(this, outputQueue));
+    outputQueue->asBinder()->linkToDeath(listener);
+    status_t status = outputQueue->connect(listener, NATIVE_WINDOW_API_CPU,
+            /* producerControlledByApp */ false, &queueBufferOutput);
+    if (status != NO_ERROR) {
+        ALOGE("addOutput: failed to connect (%d)", status);
+        return status;
+    }
+
+    mOutputs.push_back(outputQueue);
+
+    return NO_ERROR;
+}
+
+void StreamSplitter::setName(const String8 &name) {
+    Mutex::Autolock lock(mMutex);
+    mInput->setConsumerName(name);
+}
+
+void StreamSplitter::onFrameAvailable() {
+    ATRACE_CALL();
+    Mutex::Autolock lock(mMutex);
+
+    // The current policy is that if any one consumer is consuming buffers too
+    // slowly, the splitter will stall the rest of the outputs by not acquiring
+    // any more buffers from the input. This will cause back pressure on the
+    // input queue, slowing down its producer.
+
+    // If there are too many outstanding buffers, we block until a buffer is
+    // released back to the input in onBufferReleased
+    while (mOutstandingBuffers >= MAX_OUTSTANDING_BUFFERS) {
+        mReleaseCondition.wait(mMutex);
+
+        // If the splitter is abandoned while we are waiting, the release
+        // condition variable will be broadcast, and we should just return
+        // without attempting to do anything more (since the input queue will
+        // also be abandoned).
+        if (mIsAbandoned) {
+            return;
+        }
+    }
+    ++mOutstandingBuffers;
+
+    // Acquire and detach the buffer from the input
+    IGraphicBufferConsumer::BufferItem bufferItem;
+    status_t status = mInput->acquireBuffer(&bufferItem, /* presentWhen */ 0);
+    LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
+            "acquiring buffer from input failed (%d)", status);
+
+    ALOGV("acquired buffer %#llx from input",
+            bufferItem.mGraphicBuffer->getId());
+
+    status = mInput->detachBuffer(bufferItem.mBuf);
+    LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
+            "detaching buffer from input failed (%d)", status);
+
+    // Initialize our reference count for this buffer
+    mBuffers.add(bufferItem.mGraphicBuffer->getId(),
+            new BufferTracker(bufferItem.mGraphicBuffer));
+
+    IGraphicBufferProducer::QueueBufferInput queueInput(
+            bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp,
+            bufferItem.mCrop, bufferItem.mScalingMode,
+            bufferItem.mTransform, bufferItem.mIsDroppable,
+            bufferItem.mFence);
+
+    // Attach and queue the buffer to each of the outputs
+    Vector<sp<IGraphicBufferProducer> >::iterator output = mOutputs.begin();
+    for (; output != mOutputs.end(); ++output) {
+        int slot;
+        status = (*output)->attachBuffer(&slot, bufferItem.mGraphicBuffer);
+        if (status == NO_INIT) {
+            // If we just discovered that this output has been abandoned, note
+            // that, increment the release count so that we still release this
+            // buffer eventually, and move on to the next output
+            onAbandonedLocked();
+            mBuffers.editValueFor(bufferItem.mGraphicBuffer->getId())->
+                    incrementReleaseCountLocked();
+            continue;
+        } else {
+            LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
+                    "attaching buffer to output failed (%d)", status);
+        }
+
+        IGraphicBufferProducer::QueueBufferOutput queueOutput;
+        status = (*output)->queueBuffer(slot, queueInput, &queueOutput);
+        if (status == NO_INIT) {
+            // If we just discovered that this output has been abandoned, note
+            // that, increment the release count so that we still release this
+            // buffer eventually, and move on to the next output
+            onAbandonedLocked();
+            mBuffers.editValueFor(bufferItem.mGraphicBuffer->getId())->
+                    incrementReleaseCountLocked();
+            continue;
+        } else {
+            LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
+                    "queueing buffer to output failed (%d)", status);
+        }
+
+        ALOGV("queued buffer %#llx to output %p",
+                bufferItem.mGraphicBuffer->getId(), output->get());
+    }
+}
+
+void StreamSplitter::onBufferReleasedByOutput(
+        const sp<IGraphicBufferProducer>& from) {
+    ATRACE_CALL();
+    Mutex::Autolock lock(mMutex);
+
+    sp<GraphicBuffer> buffer;
+    sp<Fence> fence;
+    status_t status = from->detachNextBuffer(&buffer, &fence);
+    if (status == NO_INIT) {
+        // If we just discovered that this output has been abandoned, note that,
+        // but we can't do anything else, since buffer is invalid
+        onAbandonedLocked();
+        return;
+    } else {
+        LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
+                "detaching buffer from output failed (%d)", status);
+    }
+
+    ALOGV("detached buffer %#llx from output %p", buffer->getId(), from.get());
+
+    const sp<BufferTracker>& tracker = mBuffers.editValueFor(buffer->getId());
+
+    // Merge the release fence of the incoming buffer so that the fence we send
+    // back to the input includes all of the outputs' fences
+    tracker->mergeFence(fence);
+
+    // Check to see if this is the last outstanding reference to this buffer
+    size_t releaseCount = tracker->incrementReleaseCountLocked();
+    ALOGV("buffer %#llx reference count %d (of %d)", buffer->getId(),
+            releaseCount, mOutputs.size());
+    if (releaseCount < mOutputs.size()) {
+        return;
+    }
+
+    // If we've been abandoned, we can't return the buffer to the input, so just
+    // stop tracking it and move on
+    if (mIsAbandoned) {
+        mBuffers.removeItem(buffer->getId());
+        return;
+    }
+
+    // Attach and release the buffer back to the input
+    int consumerSlot;
+    status = mInput->attachBuffer(&consumerSlot, tracker->getBuffer());
+    LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
+            "attaching buffer to input failed (%d)", status);
+
+    status = mInput->releaseBuffer(consumerSlot, /* frameNumber */ 0,
+            EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, tracker->getMergedFence());
+    LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
+            "releasing buffer to input failed (%d)", status);
+
+    ALOGV("released buffer %#llx to input", buffer->getId());
+
+    // We no longer need to track the buffer once it has been returned to the
+    // input
+    mBuffers.removeItem(buffer->getId());
+
+    // Notify any waiting onFrameAvailable calls
+    --mOutstandingBuffers;
+    mReleaseCondition.signal();
+}
+
+void StreamSplitter::onAbandonedLocked() {
+    ALOGE("one of my outputs has abandoned me");
+    if (!mIsAbandoned) {
+        mInput->consumerDisconnect();
+    }
+    mIsAbandoned = true;
+    mReleaseCondition.broadcast();
+}
+
+StreamSplitter::OutputListener::OutputListener(
+        const sp<StreamSplitter>& splitter,
+        const sp<IGraphicBufferProducer>& output)
+      : mSplitter(splitter), mOutput(output) {}
+
+StreamSplitter::OutputListener::~OutputListener() {}
+
+void StreamSplitter::OutputListener::onBufferReleased() {
+    mSplitter->onBufferReleasedByOutput(mOutput);
+}
+
+void StreamSplitter::OutputListener::binderDied(const wp<IBinder>& /* who */) {
+    Mutex::Autolock lock(mSplitter->mMutex);
+    mSplitter->onAbandonedLocked();
+}
+
+StreamSplitter::BufferTracker::BufferTracker(const sp<GraphicBuffer>& buffer)
+      : mBuffer(buffer), mMergedFence(Fence::NO_FENCE), mReleaseCount(0) {}
+
+StreamSplitter::BufferTracker::~BufferTracker() {}
+
+void StreamSplitter::BufferTracker::mergeFence(const sp<Fence>& with) {
+    mMergedFence = Fence::merge(String8("StreamSplitter"), mMergedFence, with);
+}
+
+} // namespace android
diff --git a/libs/gui/SurfaceControl.cpp b/libs/gui/SurfaceControl.cpp
index 7c6dfb8..7597c99 100644
--- a/libs/gui/SurfaceControl.cpp
+++ b/libs/gui/SurfaceControl.cpp
@@ -92,68 +92,57 @@
 status_t SurfaceControl::setLayerStack(int32_t layerStack) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setLayerStack(mHandle, layerStack);
+    return mClient->setLayerStack(mHandle, layerStack);
 }
 status_t SurfaceControl::setLayer(int32_t layer) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setLayer(mHandle, layer);
+    return mClient->setLayer(mHandle, layer);
 }
 status_t SurfaceControl::setPosition(float x, float y) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setPosition(mHandle, x, y);
+    return mClient->setPosition(mHandle, x, y);
 }
 status_t SurfaceControl::setSize(uint32_t w, uint32_t h) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setSize(mHandle, w, h);
+    return mClient->setSize(mHandle, w, h);
 }
 status_t SurfaceControl::hide() {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->hide(mHandle);
+    return mClient->hide(mHandle);
 }
 status_t SurfaceControl::show() {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->show(mHandle);
+    return mClient->show(mHandle);
 }
 status_t SurfaceControl::setFlags(uint32_t flags, uint32_t mask) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setFlags(mHandle, flags, mask);
+    return mClient->setFlags(mHandle, flags, mask);
 }
 status_t SurfaceControl::setTransparentRegionHint(const Region& transparent) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setTransparentRegionHint(mHandle, transparent);
+    return mClient->setTransparentRegionHint(mHandle, transparent);
 }
 status_t SurfaceControl::setAlpha(float alpha) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setAlpha(mHandle, alpha);
+    return mClient->setAlpha(mHandle, alpha);
 }
 status_t SurfaceControl::setMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setMatrix(mHandle, dsdx, dtdx, dsdy, dtdy);
+    return mClient->setMatrix(mHandle, dsdx, dtdx, dsdy, dtdy);
 }
 status_t SurfaceControl::setCrop(const Rect& crop) {
     status_t err = validate();
     if (err < 0) return err;
-    const sp<SurfaceComposerClient>& client(mClient);
-    return client->setCrop(mHandle, crop);
+    return mClient->setCrop(mHandle, crop);
 }
 
 status_t SurfaceControl::clearLayerFrameStats() const {
diff --git a/libs/gui/tests/Android.mk b/libs/gui/tests/Android.mk
index 2eeb5c7..e460290 100644
--- a/libs/gui/tests/Android.mk
+++ b/libs/gui/tests/Android.mk
@@ -14,6 +14,7 @@
     IGraphicBufferProducer_test.cpp \
     MultiTextureConsumer_test.cpp \
     SRGB_test.cpp \
+    StreamSplitter_test.cpp \
     SurfaceTextureClient_test.cpp \
     SurfaceTextureFBO_test.cpp \
     SurfaceTextureGLThreadToGL_test.cpp \
diff --git a/libs/gui/tests/BufferQueue_test.cpp b/libs/gui/tests/BufferQueue_test.cpp
index fe8f8b1..c781366 100644
--- a/libs/gui/tests/BufferQueue_test.cpp
+++ b/libs/gui/tests/BufferQueue_test.cpp
@@ -301,7 +301,7 @@
     ASSERT_EQ(BAD_VALUE, mConsumer->attachBuffer(&newSlot, NULL));
     ASSERT_EQ(OK, mConsumer->attachBuffer(&newSlot, item.mGraphicBuffer));
 
-    ASSERT_EQ(OK, mConsumer->releaseBuffer(item.mBuf, 0, EGL_NO_DISPLAY,
+    ASSERT_EQ(OK, mConsumer->releaseBuffer(newSlot, 0, EGL_NO_DISPLAY,
             EGL_NO_SYNC_KHR, Fence::NO_FENCE));
 
     ASSERT_EQ(IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION,
diff --git a/libs/gui/tests/StreamSplitter_test.cpp b/libs/gui/tests/StreamSplitter_test.cpp
new file mode 100644
index 0000000..32ec90d
--- /dev/null
+++ b/libs/gui/tests/StreamSplitter_test.cpp
@@ -0,0 +1,246 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "StreamSplitter_test"
+//#define LOG_NDEBUG 0
+
+#include <gui/BufferQueue.h>
+#include <gui/IConsumerListener.h>
+#include <gui/ISurfaceComposer.h>
+#include <gui/StreamSplitter.h>
+#include <private/gui/ComposerService.h>
+
+#include <gtest/gtest.h>
+
+namespace android {
+
+class StreamSplitterTest : public ::testing::Test {
+
+protected:
+    StreamSplitterTest() {
+        const ::testing::TestInfo* const testInfo =
+            ::testing::UnitTest::GetInstance()->current_test_info();
+        ALOGV("Begin test: %s.%s", testInfo->test_case_name(),
+                testInfo->name());
+    }
+
+    ~StreamSplitterTest() {
+        const ::testing::TestInfo* const testInfo =
+            ::testing::UnitTest::GetInstance()->current_test_info();
+        ALOGV("End test:   %s.%s", testInfo->test_case_name(),
+                testInfo->name());
+    }
+};
+
+struct DummyListener : public BnConsumerListener {
+    virtual void onFrameAvailable() {}
+    virtual void onBuffersReleased() {}
+    virtual void onSidebandStreamChanged() {}
+};
+
+class CountedAllocator : public BnGraphicBufferAlloc {
+public:
+    CountedAllocator() : mAllocCount(0) {
+        sp<ISurfaceComposer> composer(ComposerService::getComposerService());
+        mAllocator = composer->createGraphicBufferAlloc();
+    }
+
+    virtual ~CountedAllocator() {}
+
+    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
+            PixelFormat format, uint32_t usage, status_t* error) {
+        ++mAllocCount;
+        sp<GraphicBuffer> buffer = mAllocator->createGraphicBuffer(w, h, format,
+                usage, error);
+        return buffer;
+    }
+
+    int getAllocCount() const { return mAllocCount; }
+
+private:
+    sp<IGraphicBufferAlloc> mAllocator;
+    int mAllocCount;
+};
+
+TEST_F(StreamSplitterTest, OneInputOneOutput) {
+    sp<CountedAllocator> allocator(new CountedAllocator);
+
+    sp<IGraphicBufferProducer> inputProducer;
+    sp<IGraphicBufferConsumer> inputConsumer;
+    BufferQueue::createBufferQueue(&inputProducer, &inputConsumer, allocator);
+
+    sp<IGraphicBufferProducer> outputProducer;
+    sp<IGraphicBufferConsumer> outputConsumer;
+    BufferQueue::createBufferQueue(&outputProducer, &outputConsumer, allocator);
+    ASSERT_EQ(OK, outputConsumer->consumerConnect(new DummyListener, false));
+
+    sp<StreamSplitter> splitter;
+    status_t status = StreamSplitter::createSplitter(inputConsumer, &splitter);
+    ASSERT_EQ(OK, status);
+    ASSERT_EQ(OK, splitter->addOutput(outputProducer));
+
+    IGraphicBufferProducer::QueueBufferOutput qbOutput;
+    ASSERT_EQ(OK, inputProducer->connect(new DummyProducerListener,
+            NATIVE_WINDOW_API_CPU, false, &qbOutput));
+
+    int slot;
+    sp<Fence> fence;
+    sp<GraphicBuffer> buffer;
+    ASSERT_EQ(IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION,
+            inputProducer->dequeueBuffer(&slot, &fence, false, 0, 0, 0,
+                    GRALLOC_USAGE_SW_WRITE_OFTEN));
+    ASSERT_EQ(OK, inputProducer->requestBuffer(slot, &buffer));
+
+    uint32_t* dataIn;
+    ASSERT_EQ(OK, buffer->lock(GraphicBuffer::USAGE_SW_WRITE_OFTEN,
+            reinterpret_cast<void**>(&dataIn)));
+    *dataIn = 0x12345678;
+    ASSERT_EQ(OK, buffer->unlock());
+
+    IGraphicBufferProducer::QueueBufferInput qbInput(0, false,
+            Rect(0, 0, 1, 1), NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false,
+            Fence::NO_FENCE);
+    ASSERT_EQ(OK, inputProducer->queueBuffer(slot, qbInput, &qbOutput));
+
+    IGraphicBufferConsumer::BufferItem item;
+    ASSERT_EQ(OK, outputConsumer->acquireBuffer(&item, 0));
+
+    uint32_t* dataOut;
+    ASSERT_EQ(OK, item.mGraphicBuffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN,
+            reinterpret_cast<void**>(&dataOut)));
+    ASSERT_EQ(*dataOut, 0x12345678);
+    ASSERT_EQ(OK, item.mGraphicBuffer->unlock());
+
+    ASSERT_EQ(OK, outputConsumer->releaseBuffer(item.mBuf, item.mFrameNumber,
+            EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE));
+
+    ASSERT_EQ(IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION,
+            inputProducer->dequeueBuffer(&slot, &fence, false, 0, 0, 0,
+                    GRALLOC_USAGE_SW_WRITE_OFTEN));
+
+    ASSERT_EQ(1, allocator->getAllocCount());
+}
+
+TEST_F(StreamSplitterTest, OneInputMultipleOutputs) {
+    const int NUM_OUTPUTS = 4;
+    sp<CountedAllocator> allocator(new CountedAllocator);
+
+    sp<IGraphicBufferProducer> inputProducer;
+    sp<IGraphicBufferConsumer> inputConsumer;
+    BufferQueue::createBufferQueue(&inputProducer, &inputConsumer, allocator);
+
+    sp<IGraphicBufferProducer> outputProducers[NUM_OUTPUTS] = {};
+    sp<IGraphicBufferConsumer> outputConsumers[NUM_OUTPUTS] = {};
+    for (int output = 0; output < NUM_OUTPUTS; ++output) {
+        BufferQueue::createBufferQueue(&outputProducers[output],
+                &outputConsumers[output], allocator);
+        ASSERT_EQ(OK, outputConsumers[output]->consumerConnect(
+                    new DummyListener, false));
+    }
+
+    sp<StreamSplitter> splitter;
+    status_t status = StreamSplitter::createSplitter(inputConsumer, &splitter);
+    ASSERT_EQ(OK, status);
+    for (int output = 0; output < NUM_OUTPUTS; ++output) {
+        ASSERT_EQ(OK, splitter->addOutput(outputProducers[output]));
+    }
+
+    IGraphicBufferProducer::QueueBufferOutput qbOutput;
+    ASSERT_EQ(OK, inputProducer->connect(new DummyProducerListener,
+            NATIVE_WINDOW_API_CPU, false, &qbOutput));
+
+    int slot;
+    sp<Fence> fence;
+    sp<GraphicBuffer> buffer;
+    ASSERT_EQ(IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION,
+            inputProducer->dequeueBuffer(&slot, &fence, false, 0, 0, 0,
+                    GRALLOC_USAGE_SW_WRITE_OFTEN));
+    ASSERT_EQ(OK, inputProducer->requestBuffer(slot, &buffer));
+
+    uint32_t* dataIn;
+    ASSERT_EQ(OK, buffer->lock(GraphicBuffer::USAGE_SW_WRITE_OFTEN,
+            reinterpret_cast<void**>(&dataIn)));
+    *dataIn = 0x12345678;
+    ASSERT_EQ(OK, buffer->unlock());
+
+    IGraphicBufferProducer::QueueBufferInput qbInput(0, false,
+            Rect(0, 0, 1, 1), NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false,
+            Fence::NO_FENCE);
+    ASSERT_EQ(OK, inputProducer->queueBuffer(slot, qbInput, &qbOutput));
+
+    for (int output = 0; output < NUM_OUTPUTS; ++output) {
+        IGraphicBufferConsumer::BufferItem item;
+        ASSERT_EQ(OK, outputConsumers[output]->acquireBuffer(&item, 0));
+
+        uint32_t* dataOut;
+        ASSERT_EQ(OK, item.mGraphicBuffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN,
+                    reinterpret_cast<void**>(&dataOut)));
+        ASSERT_EQ(*dataOut, 0x12345678);
+        ASSERT_EQ(OK, item.mGraphicBuffer->unlock());
+
+        ASSERT_EQ(OK, outputConsumers[output]->releaseBuffer(item.mBuf,
+                    item.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR,
+                    Fence::NO_FENCE));
+    }
+
+    ASSERT_EQ(IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION,
+            inputProducer->dequeueBuffer(&slot, &fence, false, 0, 0, 0,
+                    GRALLOC_USAGE_SW_WRITE_OFTEN));
+
+    ASSERT_EQ(1, allocator->getAllocCount());
+}
+
+TEST_F(StreamSplitterTest, OutputAbandonment) {
+    sp<IGraphicBufferProducer> inputProducer;
+    sp<IGraphicBufferConsumer> inputConsumer;
+    BufferQueue::createBufferQueue(&inputProducer, &inputConsumer);
+
+    sp<IGraphicBufferProducer> outputProducer;
+    sp<IGraphicBufferConsumer> outputConsumer;
+    BufferQueue::createBufferQueue(&outputProducer, &outputConsumer);
+    ASSERT_EQ(OK, outputConsumer->consumerConnect(new DummyListener, false));
+
+    sp<StreamSplitter> splitter;
+    status_t status = StreamSplitter::createSplitter(inputConsumer, &splitter);
+    ASSERT_EQ(OK, status);
+    ASSERT_EQ(OK, splitter->addOutput(outputProducer));
+
+    IGraphicBufferProducer::QueueBufferOutput qbOutput;
+    ASSERT_EQ(OK, inputProducer->connect(new DummyProducerListener,
+            NATIVE_WINDOW_API_CPU, false, &qbOutput));
+
+    int slot;
+    sp<Fence> fence;
+    sp<GraphicBuffer> buffer;
+    ASSERT_EQ(IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION,
+            inputProducer->dequeueBuffer(&slot, &fence, false, 0, 0, 0,
+                    GRALLOC_USAGE_SW_WRITE_OFTEN));
+    ASSERT_EQ(OK, inputProducer->requestBuffer(slot, &buffer));
+
+    // Abandon the output
+    outputConsumer->consumerDisconnect();
+
+    IGraphicBufferProducer::QueueBufferInput qbInput(0, false,
+            Rect(0, 0, 1, 1), NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false,
+            Fence::NO_FENCE);
+    ASSERT_EQ(OK, inputProducer->queueBuffer(slot, qbInput, &qbOutput));
+
+    // Input should be abandoned
+    ASSERT_EQ(NO_INIT, inputProducer->dequeueBuffer(&slot, &fence, false, 0, 0,
+            0, GRALLOC_USAGE_SW_WRITE_OFTEN));
+}
+
+} // namespace android
diff --git a/libs/ui/Fence.cpp b/libs/ui/Fence.cpp
index 93ec0ce..3c0306c 100644
--- a/libs/ui/Fence.cpp
+++ b/libs/ui/Fence.cpp
@@ -138,7 +138,7 @@
     if (size < getFlattenedSize() || count < getFdCount()) {
         return NO_MEMORY;
     }
-    FlattenableUtils::write(buffer, size, getFdCount());
+    FlattenableUtils::write(buffer, size, (uint32_t)getFdCount());
     if (isValid()) {
         *fds++ = mFenceFd;
         count--;
@@ -156,7 +156,7 @@
         return NO_MEMORY;
     }
 
-    size_t numFds;
+    uint32_t numFds;
     FlattenableUtils::read(buffer, size, numFds);
 
     if (numFds > 1) {
diff --git a/opengl/libs/EGL/Loader.cpp b/opengl/libs/EGL/Loader.cpp
index e528831..1fcc048 100644
--- a/opengl/libs/EGL/Loader.cpp
+++ b/opengl/libs/EGL/Loader.cpp
@@ -188,12 +188,17 @@
     LOG_ALWAYS_FATAL_IF(!hnd, "couldn't find an OpenGL ES implementation");
 
 #if defined(__LP64__)
+    cnx->libEgl   = load_wrapper("/system/lib64/libEGL.so");
     cnx->libGles2 = load_wrapper("/system/lib64/libGLESv2.so");
     cnx->libGles1 = load_wrapper("/system/lib64/libGLESv1_CM.so");
 #else
+    cnx->libEgl   = load_wrapper("/system/lib/libEGL.so");
     cnx->libGles2 = load_wrapper("/system/lib/libGLESv2.so");
     cnx->libGles1 = load_wrapper("/system/lib/libGLESv1_CM.so");
 #endif
+    LOG_ALWAYS_FATAL_IF(!cnx->libEgl,
+            "couldn't load system EGL wrapper libraries");
+
     LOG_ALWAYS_FATAL_IF(!cnx->libGles2 || !cnx->libGles1,
             "couldn't load system OpenGL ES wrapper libraries");
 
diff --git a/opengl/libs/EGL/eglApi.cpp b/opengl/libs/EGL/eglApi.cpp
index b6ffdb2..6e77e45 100644
--- a/opengl/libs/EGL/eglApi.cpp
+++ b/opengl/libs/EGL/eglApi.cpp
@@ -879,11 +879,14 @@
     return err;
 }
 
-static __eglMustCastToProperFunctionPointerType findBuiltinGLWrapper(
+static __eglMustCastToProperFunctionPointerType findBuiltinWrapper(
         const char* procname) {
     const egl_connection_t* cnx = &gEGLImpl;
     void* proc = NULL;
 
+    proc = dlsym(cnx->libEgl, procname);
+    if (proc) return (__eglMustCastToProperFunctionPointerType)proc;
+
     proc = dlsym(cnx->libGles2, procname);
     if (proc) return (__eglMustCastToProperFunctionPointerType)proc;
 
@@ -914,7 +917,7 @@
     addr = findProcAddress(procname, sExtensionMap, NELEM(sExtensionMap));
     if (addr) return addr;
 
-    addr = findBuiltinGLWrapper(procname);
+    addr = findBuiltinWrapper(procname);
     if (addr) return addr;
 
     // this protects accesses to sGLExtentionMap and sGLExtentionSlot
diff --git a/opengl/libs/EGL/egldefs.h b/opengl/libs/EGL/egldefs.h
index b905ea0..9858276 100644
--- a/opengl/libs/EGL/egldefs.h
+++ b/opengl/libs/EGL/egldefs.h
@@ -44,6 +44,7 @@
     EGLint              minor;
     egl_t               egl;
 
+    void*               libEgl;
     void*               libGles1;
     void*               libGles2;
 };
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
index 67229d5..1362ae8 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
@@ -256,7 +256,7 @@
     resetPerFrameState();
 }
 
-void VirtualDisplaySurface::dump(String8& result) const {
+void VirtualDisplaySurface::dump(String8& /* result */) const {
 }
 
 status_t VirtualDisplaySurface::requestBuffer(int pslot,
@@ -285,19 +285,19 @@
     int pslot = mapSource2ProducerSlot(source, *sslot);
     VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
             dbgSourceStr(source), *sslot, pslot, result);
-    uint32_t sourceBit = static_cast<uint32_t>(source) << pslot;
+    uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
 
-    if ((mProducerSlotSource & (1u << pslot)) != sourceBit) {
+    if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
         // This slot was previously dequeued from the other source; must
         // re-request the buffer.
         result |= BUFFER_NEEDS_REALLOCATION;
-        mProducerSlotSource &= ~(1u << pslot);
+        mProducerSlotSource &= ~(1ULL << pslot);
         mProducerSlotSource |= sourceBit;
     }
 
     if (result & RELEASE_ALL_BUFFERS) {
         for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
-            if ((mProducerSlotSource & (1u << i)) == sourceBit)
+            if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
                 mProducerBuffers[i].clear();
         }
     }
@@ -380,6 +380,12 @@
     return INVALID_OPERATION;
 }
 
+status_t VirtualDisplaySurface::detachNextBuffer(
+        sp<GraphicBuffer>* /* outBuffer */, sp<Fence>* /* outFence */) {
+    VDS_LOGE("detachNextBuffer is not available for VirtualDisplaySurface");
+    return INVALID_OPERATION;
+}
+
 status_t VirtualDisplaySurface::attachBuffer(int* /* outSlot */,
         const sp<GraphicBuffer>& /* buffer */) {
     VDS_LOGE("attachBuffer is not available for VirtualDisplaySurface");
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
index 165224a..0ae9804 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
@@ -101,6 +101,8 @@
     virtual status_t dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
             uint32_t w, uint32_t h, uint32_t format, uint32_t usage);
     virtual status_t detachBuffer(int slot);
+    virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+            sp<Fence>* outFence);
     virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer);
     virtual status_t queueBuffer(int pslot,
             const QueueBufferInput& input, QueueBufferOutput* output);
@@ -153,10 +155,10 @@
     // Since we present a single producer interface to the GLES driver, but
     // are internally muxing between the sink and scratch producers, we have
     // to keep track of which source last returned each producer slot from
-    // dequeueBuffer. Each bit in mLastSlotSource corresponds to a producer
+    // dequeueBuffer. Each bit in mProducerSlotSource corresponds to a producer
     // slot. Both mProducerSlotSource and mProducerBuffers are indexed by a
     // "producer slot"; see the mapSlot*() functions.
-    uint32_t mProducerSlotSource;
+    uint64_t mProducerSlotSource;
     sp<GraphicBuffer> mProducerBuffers[BufferQueue::NUM_BUFFER_SLOTS];
 
     // The QueueBufferOutput with the latest info from the sink, and with the
diff --git a/services/surfaceflinger/MonitoredProducer.cpp b/services/surfaceflinger/MonitoredProducer.cpp
index 1a2b7e5..d0e81bc 100644
--- a/services/surfaceflinger/MonitoredProducer.cpp
+++ b/services/surfaceflinger/MonitoredProducer.cpp
@@ -69,6 +69,11 @@
     return mProducer->detachBuffer(slot);
 }
 
+status_t MonitoredProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+        sp<Fence>* outFence) {
+    return mProducer->detachNextBuffer(outBuffer, outFence);
+}
+
 status_t MonitoredProducer::attachBuffer(int* outSlot,
         const sp<GraphicBuffer>& buffer) {
     return mProducer->attachBuffer(outSlot, buffer);
diff --git a/services/surfaceflinger/MonitoredProducer.h b/services/surfaceflinger/MonitoredProducer.h
index 1e6431e..f034e39 100644
--- a/services/surfaceflinger/MonitoredProducer.h
+++ b/services/surfaceflinger/MonitoredProducer.h
@@ -39,6 +39,8 @@
     virtual status_t dequeueBuffer(int* slot, sp<Fence>* fence, bool async,
             uint32_t w, uint32_t h, uint32_t format, uint32_t usage);
     virtual status_t detachBuffer(int slot);
+    virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
+            sp<Fence>* outFence);
     virtual status_t attachBuffer(int* outSlot,
             const sp<GraphicBuffer>& buffer);
     virtual status_t queueBuffer(int slot, const QueueBufferInput& input,