1/*
2 * Copyright (C) 2007 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 "GraphicBuffer"
18
19#include <ui/GraphicBuffer.h>
20
21#include <cutils/atomic.h>
22
23#include <grallocusage/GrallocUsageConversion.h>
24
25#include <ui/DetachedBufferHandle.h>
26#include <ui/Gralloc2.h>
27#include <ui/GraphicBufferAllocator.h>
28#include <ui/GraphicBufferMapper.h>
29
30namespace android {
31
32// ===========================================================================
33// Buffer and implementation of ANativeWindowBuffer
34// ===========================================================================
35
36static uint64_t getUniqueId() {
37    static volatile int32_t nextId = 0;
38    uint64_t id = static_cast<uint64_t>(getpid()) << 32;
39    id |= static_cast<uint32_t>(android_atomic_inc(&nextId));
40    return id;
41}
42
43sp<GraphicBuffer> GraphicBuffer::from(ANativeWindowBuffer* anwb) {
44    return static_cast<GraphicBuffer *>(anwb);
45}
46
47GraphicBuffer::GraphicBuffer()
48    : BASE(), mOwner(ownData), mBufferMapper(GraphicBufferMapper::get()),
49      mInitCheck(NO_ERROR), mId(getUniqueId()), mGenerationNumber(0)
50{
51    width  =
52    height =
53    stride =
54    format =
55    usage_deprecated = 0;
56    usage  = 0;
57    layerCount = 0;
58    handle = NULL;
59}
60
61// deprecated
62GraphicBuffer::GraphicBuffer(uint32_t inWidth, uint32_t inHeight,
63        PixelFormat inFormat, uint32_t inUsage, std::string requestorName)
64    : GraphicBuffer(inWidth, inHeight, inFormat, 1, static_cast<uint64_t>(inUsage), requestorName)
65{
66}
67
68GraphicBuffer::GraphicBuffer(uint32_t inWidth, uint32_t inHeight,
69        PixelFormat inFormat, uint32_t inLayerCount, uint64_t usage, std::string requestorName)
70    : GraphicBuffer()
71{
72    mInitCheck = initWithSize(inWidth, inHeight, inFormat, inLayerCount,
73            usage, std::move(requestorName));
74}
75
76// deprecated
77GraphicBuffer::GraphicBuffer(uint32_t inWidth, uint32_t inHeight,
78        PixelFormat inFormat, uint32_t inLayerCount, uint32_t inUsage,
79        uint32_t inStride, native_handle_t* inHandle, bool keepOwnership)
80    : GraphicBuffer(inHandle, keepOwnership ? TAKE_HANDLE : WRAP_HANDLE,
81            inWidth, inHeight, inFormat, inLayerCount, static_cast<uint64_t>(inUsage),
82            inStride)
83{
84}
85
86GraphicBuffer::GraphicBuffer(const native_handle_t* handle,
87        HandleWrapMethod method, uint32_t width, uint32_t height,
88        PixelFormat format, uint32_t layerCount,
89        uint64_t usage,
90        uint32_t stride)
91    : GraphicBuffer()
92{
93    mInitCheck = initWithHandle(handle, method, width, height, format,
94            layerCount, usage, stride);
95}
96
97GraphicBuffer::~GraphicBuffer()
98{
99    if (handle) {
100        free_handle();
101    }
102}
103
104void GraphicBuffer::free_handle()
105{
106    if (mOwner == ownHandle) {
107        mBufferMapper.freeBuffer(handle);
108    } else if (mOwner == ownData) {
109        GraphicBufferAllocator& allocator(GraphicBufferAllocator::get());
110        allocator.free(handle);
111    }
112    handle = NULL;
113}
114
115status_t GraphicBuffer::initCheck() const {
116    return static_cast<status_t>(mInitCheck);
117}
118
119void GraphicBuffer::dumpAllocationsToSystemLog()
120{
121    GraphicBufferAllocator::dumpToSystemLog();
122}
123
124ANativeWindowBuffer* GraphicBuffer::getNativeBuffer() const
125{
126    LOG_ALWAYS_FATAL_IF(this == NULL, "getNativeBuffer() called on NULL GraphicBuffer");
127    return static_cast<ANativeWindowBuffer*>(
128            const_cast<GraphicBuffer*>(this));
129}
130
131status_t GraphicBuffer::reallocate(uint32_t inWidth, uint32_t inHeight,
132        PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage)
133{
134    if (mOwner != ownData)
135        return INVALID_OPERATION;
136
137    if (handle &&
138            static_cast<int>(inWidth) == width &&
139            static_cast<int>(inHeight) == height &&
140            inFormat == format &&
141            inLayerCount == layerCount &&
142            inUsage == usage)
143        return NO_ERROR;
144
145    if (handle) {
146        GraphicBufferAllocator& allocator(GraphicBufferAllocator::get());
147        allocator.free(handle);
148        handle = 0;
149    }
150    return initWithSize(inWidth, inHeight, inFormat, inLayerCount, inUsage, "[Reallocation]");
151}
152
153bool GraphicBuffer::needsReallocation(uint32_t inWidth, uint32_t inHeight,
154        PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage)
155{
156    if (static_cast<int>(inWidth) != width) return true;
157    if (static_cast<int>(inHeight) != height) return true;
158    if (inFormat != format) return true;
159    if (inLayerCount != layerCount) return true;
160    if ((usage & inUsage) != inUsage) return true;
161    return false;
162}
163
164status_t GraphicBuffer::initWithSize(uint32_t inWidth, uint32_t inHeight,
165        PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage,
166        std::string requestorName)
167{
168    GraphicBufferAllocator& allocator = GraphicBufferAllocator::get();
169    uint32_t outStride = 0;
170    status_t err = allocator.allocate(inWidth, inHeight, inFormat, inLayerCount,
171            inUsage, &handle, &outStride, mId,
172            std::move(requestorName));
173    if (err == NO_ERROR) {
174        mBufferMapper.getTransportSize(handle, &mTransportNumFds, &mTransportNumInts);
175
176        width = static_cast<int>(inWidth);
177        height = static_cast<int>(inHeight);
178        format = inFormat;
179        layerCount = inLayerCount;
180        usage = inUsage;
181        usage_deprecated = int(usage);
182        stride = static_cast<int>(outStride);
183    }
184    return err;
185}
186
187status_t GraphicBuffer::initWithHandle(const native_handle_t* handle,
188        HandleWrapMethod method, uint32_t width, uint32_t height,
189        PixelFormat format, uint32_t layerCount, uint64_t usage,
190        uint32_t stride)
191{
192    ANativeWindowBuffer::width  = static_cast<int>(width);
193    ANativeWindowBuffer::height = static_cast<int>(height);
194    ANativeWindowBuffer::stride = static_cast<int>(stride);
195    ANativeWindowBuffer::format = format;
196    ANativeWindowBuffer::usage  = usage;
197    ANativeWindowBuffer::usage_deprecated = int(usage);
198
199    ANativeWindowBuffer::layerCount = layerCount;
200
201    mOwner = (method == WRAP_HANDLE) ? ownNone : ownHandle;
202
203    if (method == TAKE_UNREGISTERED_HANDLE || method == CLONE_HANDLE) {
204        buffer_handle_t importedHandle;
205        status_t err = mBufferMapper.importBuffer(handle, width, height,
206                layerCount, format, usage, stride, &importedHandle);
207        if (err != NO_ERROR) {
208            initWithHandle(nullptr, WRAP_HANDLE, 0, 0, 0, 0, 0, 0);
209
210            return err;
211        }
212
213        if (method == TAKE_UNREGISTERED_HANDLE) {
214            native_handle_close(handle);
215            native_handle_delete(const_cast<native_handle_t*>(handle));
216        }
217
218        handle = importedHandle;
219        mBufferMapper.getTransportSize(handle, &mTransportNumFds, &mTransportNumInts);
220    }
221
222    ANativeWindowBuffer::handle = handle;
223
224    return NO_ERROR;
225}
226
227status_t GraphicBuffer::lock(uint32_t inUsage, void** vaddr)
228{
229    const Rect lockBounds(width, height);
230    status_t res = lock(inUsage, lockBounds, vaddr);
231    return res;
232}
233
234status_t GraphicBuffer::lock(uint32_t inUsage, const Rect& rect, void** vaddr)
235{
236    if (rect.left < 0 || rect.right  > width ||
237        rect.top  < 0 || rect.bottom > height) {
238        ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
239                rect.left, rect.top, rect.right, rect.bottom,
240                width, height);
241        return BAD_VALUE;
242    }
243    status_t res = getBufferMapper().lock(handle, inUsage, rect, vaddr);
244    return res;
245}
246
247status_t GraphicBuffer::lockYCbCr(uint32_t inUsage, android_ycbcr* ycbcr)
248{
249    const Rect lockBounds(width, height);
250    status_t res = lockYCbCr(inUsage, lockBounds, ycbcr);
251    return res;
252}
253
254status_t GraphicBuffer::lockYCbCr(uint32_t inUsage, const Rect& rect,
255        android_ycbcr* ycbcr)
256{
257    if (rect.left < 0 || rect.right  > width ||
258        rect.top  < 0 || rect.bottom > height) {
259        ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
260                rect.left, rect.top, rect.right, rect.bottom,
261                width, height);
262        return BAD_VALUE;
263    }
264    status_t res = getBufferMapper().lockYCbCr(handle, inUsage, rect, ycbcr);
265    return res;
266}
267
268status_t GraphicBuffer::unlock()
269{
270    status_t res = getBufferMapper().unlock(handle);
271    return res;
272}
273
274status_t GraphicBuffer::lockAsync(uint32_t inUsage, void** vaddr, int fenceFd)
275{
276    const Rect lockBounds(width, height);
277    status_t res = lockAsync(inUsage, lockBounds, vaddr, fenceFd);
278    return res;
279}
280
281status_t GraphicBuffer::lockAsync(uint32_t inUsage, const Rect& rect,
282        void** vaddr, int fenceFd)
283{
284    return lockAsync(inUsage, inUsage, rect, vaddr, fenceFd);
285}
286
287status_t GraphicBuffer::lockAsync(uint64_t inProducerUsage,
288        uint64_t inConsumerUsage, const Rect& rect, void** vaddr, int fenceFd)
289{
290    if (rect.left < 0 || rect.right  > width ||
291        rect.top  < 0 || rect.bottom > height) {
292        ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
293                rect.left, rect.top, rect.right, rect.bottom,
294                width, height);
295        return BAD_VALUE;
296    }
297    status_t res = getBufferMapper().lockAsync(handle, inProducerUsage,
298            inConsumerUsage, rect, vaddr, fenceFd);
299    return res;
300}
301
302status_t GraphicBuffer::lockAsyncYCbCr(uint32_t inUsage, android_ycbcr* ycbcr,
303        int fenceFd)
304{
305    const Rect lockBounds(width, height);
306    status_t res = lockAsyncYCbCr(inUsage, lockBounds, ycbcr, fenceFd);
307    return res;
308}
309
310status_t GraphicBuffer::lockAsyncYCbCr(uint32_t inUsage, const Rect& rect,
311        android_ycbcr* ycbcr, int fenceFd)
312{
313    if (rect.left < 0 || rect.right  > width ||
314        rect.top  < 0 || rect.bottom > height) {
315        ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
316                rect.left, rect.top, rect.right, rect.bottom,
317                width, height);
318        return BAD_VALUE;
319    }
320    status_t res = getBufferMapper().lockAsyncYCbCr(handle, inUsage, rect, ycbcr, fenceFd);
321    return res;
322}
323
324status_t GraphicBuffer::unlockAsync(int *fenceFd)
325{
326    status_t res = getBufferMapper().unlockAsync(handle, fenceFd);
327    return res;
328}
329
330size_t GraphicBuffer::getFlattenedSize() const {
331    return static_cast<size_t>(13 + (handle ? mTransportNumInts : 0)) * sizeof(int);
332}
333
334size_t GraphicBuffer::getFdCount() const {
335    return static_cast<size_t>(handle ? mTransportNumFds : 0);
336}
337
338status_t GraphicBuffer::flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const {
339    size_t sizeNeeded = GraphicBuffer::getFlattenedSize();
340    if (size < sizeNeeded) return NO_MEMORY;
341
342    size_t fdCountNeeded = GraphicBuffer::getFdCount();
343    if (count < fdCountNeeded) return NO_MEMORY;
344
345    int32_t* buf = static_cast<int32_t*>(buffer);
346    buf[0] = 'GB01';
347    buf[1] = width;
348    buf[2] = height;
349    buf[3] = stride;
350    buf[4] = format;
351    buf[5] = static_cast<int32_t>(layerCount);
352    buf[6] = int(usage); // low 32-bits
353    buf[7] = static_cast<int32_t>(mId >> 32);
354    buf[8] = static_cast<int32_t>(mId & 0xFFFFFFFFull);
355    buf[9] = static_cast<int32_t>(mGenerationNumber);
356    buf[10] = 0;
357    buf[11] = 0;
358    buf[12] = int(usage >> 32); // high 32-bits
359
360    if (handle) {
361        buf[10] = int32_t(mTransportNumFds);
362        buf[11] = int32_t(mTransportNumInts);
363        memcpy(fds, handle->data, static_cast<size_t>(mTransportNumFds) * sizeof(int));
364        memcpy(buf + 13, handle->data + handle->numFds,
365                static_cast<size_t>(mTransportNumInts) * sizeof(int));
366    }
367
368    buffer = static_cast<void*>(static_cast<uint8_t*>(buffer) + sizeNeeded);
369    size -= sizeNeeded;
370    if (handle) {
371        fds += mTransportNumFds;
372        count -= static_cast<size_t>(mTransportNumFds);
373    }
374
375    return NO_ERROR;
376}
377
378status_t GraphicBuffer::unflatten(
379        void const*& buffer, size_t& size, int const*& fds, size_t& count) {
380
381    int const* buf = static_cast<int const*>(buffer);
382
383    // NOTE: it turns out that some media code generates a flattened GraphicBuffer manually!!!!!
384    // see H2BGraphicBufferProducer.cpp
385    uint32_t flattenWordCount = 0;
386    if (buf[0] == 'GB01') {
387        // new version with 64-bits usage bits
388        flattenWordCount = 13;
389    } else if (buf[0] == 'GBFR') {
390        // old version, when usage bits were 32-bits
391        flattenWordCount = 12;
392    } else {
393        return BAD_TYPE;
394    }
395
396    const size_t numFds  = static_cast<size_t>(buf[10]);
397    const size_t numInts = static_cast<size_t>(buf[11]);
398
399    // Limit the maxNumber to be relatively small. The number of fds or ints
400    // should not come close to this number, and the number itself was simply
401    // chosen to be high enough to not cause issues and low enough to prevent
402    // overflow problems.
403    const size_t maxNumber = 4096;
404    if (numFds >= maxNumber || numInts >= (maxNumber - flattenWordCount)) {
405        width = height = stride = format = usage_deprecated = 0;
406        layerCount = 0;
407        usage = 0;
408        handle = NULL;
409        ALOGE("unflatten: numFds or numInts is too large: %zd, %zd", numFds, numInts);
410        return BAD_VALUE;
411    }
412
413    const size_t sizeNeeded = (flattenWordCount + numInts) * sizeof(int);
414    if (size < sizeNeeded) return NO_MEMORY;
415
416    size_t fdCountNeeded = numFds;
417    if (count < fdCountNeeded) return NO_MEMORY;
418
419    if (handle) {
420        // free previous handle if any
421        free_handle();
422    }
423
424    if (numFds || numInts) {
425        width  = buf[1];
426        height = buf[2];
427        stride = buf[3];
428        format = buf[4];
429        layerCount = static_cast<uintptr_t>(buf[5]);
430        usage_deprecated = buf[6];
431        if (flattenWordCount == 13) {
432            usage = (uint64_t(buf[12]) << 32) | uint32_t(buf[6]);
433        } else {
434            usage = uint64_t(usage_deprecated);
435        }
436        native_handle* h = native_handle_create(
437                static_cast<int>(numFds), static_cast<int>(numInts));
438        if (!h) {
439            width = height = stride = format = usage_deprecated = 0;
440            layerCount = 0;
441            usage = 0;
442            handle = NULL;
443            ALOGE("unflatten: native_handle_create failed");
444            return NO_MEMORY;
445        }
446        memcpy(h->data, fds, numFds * sizeof(int));
447        memcpy(h->data + numFds, buf + flattenWordCount, numInts * sizeof(int));
448        handle = h;
449    } else {
450        width = height = stride = format = usage_deprecated = 0;
451        layerCount = 0;
452        usage = 0;
453        handle = NULL;
454    }
455
456    mId = static_cast<uint64_t>(buf[7]) << 32;
457    mId |= static_cast<uint32_t>(buf[8]);
458
459    mGenerationNumber = static_cast<uint32_t>(buf[9]);
460
461    mOwner = ownHandle;
462
463    if (handle != 0) {
464        buffer_handle_t importedHandle;
465        status_t err = mBufferMapper.importBuffer(handle, uint32_t(width), uint32_t(height),
466                uint32_t(layerCount), format, usage, uint32_t(stride), &importedHandle);
467        if (err != NO_ERROR) {
468            width = height = stride = format = usage_deprecated = 0;
469            layerCount = 0;
470            usage = 0;
471            handle = NULL;
472            ALOGE("unflatten: registerBuffer failed: %s (%d)", strerror(-err), err);
473            return err;
474        }
475
476        native_handle_close(handle);
477        native_handle_delete(const_cast<native_handle_t*>(handle));
478        handle = importedHandle;
479        mBufferMapper.getTransportSize(handle, &mTransportNumFds, &mTransportNumInts);
480    }
481
482    buffer = static_cast<void const*>(static_cast<uint8_t const*>(buffer) + sizeNeeded);
483    size -= sizeNeeded;
484    fds += numFds;
485    count -= numFds;
486
487    return NO_ERROR;
488}
489
490bool GraphicBuffer::isDetachedBuffer() const {
491    return mDetachedBufferHandle && mDetachedBufferHandle->isValid();
492}
493
494status_t GraphicBuffer::setDetachedBufferHandle(std::unique_ptr<DetachedBufferHandle> channel) {
495    if (isDetachedBuffer()) {
496        ALOGW("setDetachedBuffer: there is already a BufferHub channel associated with this "
497              "GraphicBuffer. Replacing the old one.");
498    }
499
500    mDetachedBufferHandle = std::move(channel);
501    return NO_ERROR;
502}
503
504std::unique_ptr<DetachedBufferHandle> GraphicBuffer::takeDetachedBufferHandle() {
505    return std::move(mDetachedBufferHandle);
506}
507
508// ---------------------------------------------------------------------------
509
510}; // namespace android
511