Home | History | Annotate | Download | only in foundation
      1 /*
      2  * Copyright (C) 2009 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 #define LOG_TAG "MediaBufferGroup"
     18 #include <utils/Log.h>
     19 
     20 #include <media/stagefright/foundation/ADebug.h>
     21 #include <media/stagefright/MediaBuffer.h>
     22 #include <media/stagefright/MediaBufferGroup.h>
     23 
     24 namespace android {
     25 
     26 // std::min is not constexpr in C++11
     27 template<typename T>
     28 constexpr T MIN(const T &a, const T &b) { return a <= b ? a : b; }
     29 
     30 // MediaBufferGroup may create shared memory buffers at a
     31 // smaller threshold than an isolated new MediaBuffer.
     32 static const size_t kSharedMemoryThreshold = MIN(
     33         (size_t)MediaBuffer::kSharedMemThreshold, (size_t)(4 * 1024));
     34 
     35 MediaBufferGroup::MediaBufferGroup(size_t growthLimit) :
     36     mGrowthLimit(growthLimit) {
     37 }
     38 
     39 MediaBufferGroup::MediaBufferGroup(size_t buffers, size_t buffer_size, size_t growthLimit)
     40     : mGrowthLimit(growthLimit) {
     41 
     42     if (buffer_size >= kSharedMemoryThreshold) {
     43         ALOGD("creating MemoryDealer");
     44         // Using a single MemoryDealer is efficient for a group of shared memory objects.
     45         // This loop guarantees that we use shared memory (no fallback to malloc).
     46 
     47         size_t alignment = MemoryDealer::getAllocationAlignment();
     48         size_t augmented_size = buffer_size + sizeof(MediaBuffer::SharedControl);
     49         size_t total = (augmented_size + alignment - 1) / alignment * alignment * buffers;
     50         sp<MemoryDealer> memoryDealer = new MemoryDealer(total, "MediaBufferGroup");
     51 
     52         for (size_t i = 0; i < buffers; ++i) {
     53             sp<IMemory> mem = memoryDealer->allocate(augmented_size);
     54             if (mem.get() == nullptr || mem->pointer() == nullptr) {
     55                 ALOGW("Only allocated %zu shared buffers of size %zu", i, buffer_size);
     56                 break;
     57             }
     58             MediaBuffer *buffer = new MediaBuffer(mem);
     59             buffer->getSharedControl()->clear();
     60             add_buffer(buffer);
     61         }
     62         return;
     63     }
     64 
     65     // Non-shared memory allocation.
     66     for (size_t i = 0; i < buffers; ++i) {
     67         MediaBuffer *buffer = new MediaBuffer(buffer_size);
     68         if (buffer->data() == nullptr) {
     69             delete buffer; // don't call release, it's not properly formed
     70             ALOGW("Only allocated %zu malloc buffers of size %zu", i, buffer_size);
     71             break;
     72         }
     73         add_buffer(buffer);
     74     }
     75 }
     76 
     77 MediaBufferGroup::~MediaBufferGroup() {
     78     for (MediaBuffer *buffer : mBuffers) {
     79         if (buffer->refcount() != 0) {
     80             const int localRefcount = buffer->localRefcount();
     81             const int remoteRefcount = buffer->remoteRefcount();
     82 
     83             // Fatal if we have a local refcount.
     84             LOG_ALWAYS_FATAL_IF(localRefcount != 0,
     85                     "buffer(%p) localRefcount %d != 0, remoteRefcount %d",
     86                     buffer, localRefcount, remoteRefcount);
     87 
     88             // Log an error if we have a remaining remote refcount,
     89             // as the remote process may have died or may have inappropriate behavior.
     90             // The shared memory associated with the MediaBuffer will
     91             // automatically be reclaimed when there are no remaining fds
     92             // associated with it.
     93             ALOGE("buffer(%p) has residual remoteRefcount %d",
     94                     buffer, remoteRefcount);
     95         }
     96         // gracefully delete.
     97         buffer->setObserver(nullptr);
     98         buffer->release();
     99     }
    100 }
    101 
    102 void MediaBufferGroup::add_buffer(MediaBuffer *buffer) {
    103     Mutex::Autolock autoLock(mLock);
    104 
    105     buffer->setObserver(this);
    106     mBuffers.emplace_back(buffer);
    107     // optionally: mGrowthLimit = max(mGrowthLimit, mBuffers.size());
    108 }
    109 
    110 bool MediaBufferGroup::has_buffers() {
    111     if (mBuffers.size() < mGrowthLimit) {
    112         return true; // We can add more buffers internally.
    113     }
    114     for (MediaBuffer *buffer : mBuffers) {
    115         if (buffer->refcount() == 0) {
    116             return true;
    117         }
    118     }
    119     return false;
    120 }
    121 
    122 status_t MediaBufferGroup::acquire_buffer(
    123         MediaBuffer **out, bool nonBlocking, size_t requestedSize) {
    124     Mutex::Autolock autoLock(mLock);
    125     for (;;) {
    126         size_t smallest = requestedSize;
    127         MediaBuffer *buffer = nullptr;
    128         auto free = mBuffers.end();
    129         for (auto it = mBuffers.begin(); it != mBuffers.end(); ++it) {
    130             if ((*it)->refcount() == 0) {
    131                 const size_t size = (*it)->size();
    132                 if (size >= requestedSize) {
    133                     buffer = *it;
    134                     break;
    135                 }
    136                 if (size < smallest) {
    137                     smallest = size; // always free the smallest buf
    138                     free = it;
    139                 }
    140             }
    141         }
    142         if (buffer == nullptr
    143                 && (free != mBuffers.end() || mBuffers.size() < mGrowthLimit)) {
    144             // We alloc before we free so failure leaves group unchanged.
    145             const size_t allocateSize = requestedSize < SIZE_MAX / 3 * 2 /* NB: ordering */ ?
    146                     requestedSize * 3 / 2 : requestedSize;
    147             buffer = new MediaBuffer(allocateSize);
    148             if (buffer->data() == nullptr) {
    149                 ALOGE("Allocation failure for size %zu", allocateSize);
    150                 delete buffer; // Invalid alloc, prefer not to call release.
    151                 buffer = nullptr;
    152             } else {
    153                 buffer->setObserver(this);
    154                 if (free != mBuffers.end()) {
    155                     ALOGV("reallocate buffer, requested size %zu vs available %zu",
    156                             requestedSize, (*free)->size());
    157                     (*free)->setObserver(nullptr);
    158                     (*free)->release();
    159                     *free = buffer; // in-place replace
    160                 } else {
    161                     ALOGV("allocate buffer, requested size %zu", requestedSize);
    162                     mBuffers.emplace_back(buffer);
    163                 }
    164             }
    165         }
    166         if (buffer != nullptr) {
    167             buffer->add_ref();
    168             buffer->reset();
    169             *out = buffer;
    170             return OK;
    171         }
    172         if (nonBlocking) {
    173             *out = nullptr;
    174             return WOULD_BLOCK;
    175         }
    176         // All buffers are in use, block until one of them is returned.
    177         mCondition.wait(mLock);
    178     }
    179     // Never gets here.
    180 }
    181 
    182 void MediaBufferGroup::signalBufferReturned(MediaBuffer *) {
    183     mCondition.signal();
    184 }
    185 
    186 }  // namespace android
    187