1/*
2 * Copyright (C) 2013 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 "Camera3-InputStream"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20
21#include <gui/BufferItem.h>
22#include <utils/Log.h>
23#include <utils/Trace.h>
24#include "Camera3InputStream.h"
25
26namespace android {
27
28namespace camera3 {
29
30Camera3InputStream::Camera3InputStream(int id,
31        uint32_t width, uint32_t height, int format) :
32        Camera3IOStreamBase(id, CAMERA3_STREAM_INPUT, width, height, /*maxSize*/0,
33                            format, HAL_DATASPACE_UNKNOWN, CAMERA3_STREAM_ROTATION_0) {
34
35    if (format == HAL_PIXEL_FORMAT_BLOB) {
36        ALOGE("%s: Bad format, BLOB not supported", __FUNCTION__);
37        mState = STATE_ERROR;
38    }
39}
40
41Camera3InputStream::~Camera3InputStream() {
42    disconnectLocked();
43}
44
45status_t Camera3InputStream::getInputBufferLocked(
46        camera3_stream_buffer *buffer) {
47    ATRACE_CALL();
48    status_t res;
49
50    // FIXME: will not work in (re-)registration
51    if (mState == STATE_IN_CONFIG || mState == STATE_IN_RECONFIG) {
52        ALOGE("%s: Stream %d: Buffer registration for input streams"
53              " not implemented (state %d)",
54              __FUNCTION__, mId, mState);
55        return INVALID_OPERATION;
56    }
57
58    if ((res = getBufferPreconditionCheckLocked()) != OK) {
59        return res;
60    }
61
62    ANativeWindowBuffer* anb;
63    int fenceFd;
64
65    assert(mConsumer != 0);
66
67    BufferItem bufferItem;
68
69    res = mConsumer->acquireBuffer(&bufferItem, /*waitForFence*/false);
70    if (res != OK) {
71        ALOGE("%s: Stream %d: Can't acquire next output buffer: %s (%d)",
72                __FUNCTION__, mId, strerror(-res), res);
73        return res;
74    }
75
76    anb = bufferItem.mGraphicBuffer->getNativeBuffer();
77    assert(anb != NULL);
78    fenceFd = bufferItem.mFence->dup();
79
80    /**
81     * FenceFD now owned by HAL except in case of error,
82     * in which case we reassign it to acquire_fence
83     */
84    handoutBufferLocked(*buffer, &(anb->handle), /*acquireFence*/fenceFd,
85                        /*releaseFence*/-1, CAMERA3_BUFFER_STATUS_OK, /*output*/false);
86    mBuffersInFlight.push_back(bufferItem);
87
88    return OK;
89}
90
91status_t Camera3InputStream::returnBufferCheckedLocked(
92            const camera3_stream_buffer &buffer,
93            nsecs_t timestamp,
94            bool output,
95            /*out*/
96            sp<Fence> *releaseFenceOut) {
97
98    (void)timestamp;
99    (void)output;
100    ALOG_ASSERT(!output, "Expected output to be false");
101
102    status_t res;
103
104    bool bufferFound = false;
105    BufferItem bufferItem;
106    {
107        // Find the buffer we are returning
108        Vector<BufferItem>::iterator it, end;
109        for (it = mBuffersInFlight.begin(), end = mBuffersInFlight.end();
110             it != end;
111             ++it) {
112
113            const BufferItem& tmp = *it;
114            ANativeWindowBuffer *anb = tmp.mGraphicBuffer->getNativeBuffer();
115            if (anb != NULL && &(anb->handle) == buffer.buffer) {
116                bufferFound = true;
117                bufferItem = tmp;
118                mBuffersInFlight.erase(it);
119                break;
120            }
121        }
122    }
123    if (!bufferFound) {
124        ALOGE("%s: Stream %d: Can't return buffer that wasn't sent to HAL",
125              __FUNCTION__, mId);
126        return INVALID_OPERATION;
127    }
128
129    if (buffer.status == CAMERA3_BUFFER_STATUS_ERROR) {
130        if (buffer.release_fence != -1) {
131            ALOGE("%s: Stream %d: HAL should not set release_fence(%d) when "
132                  "there is an error", __FUNCTION__, mId, buffer.release_fence);
133            close(buffer.release_fence);
134        }
135
136        /**
137         * Reassign release fence as the acquire fence incase of error
138         */
139        const_cast<camera3_stream_buffer*>(&buffer)->release_fence =
140                buffer.acquire_fence;
141    }
142
143    /**
144     * Unconditionally return buffer to the buffer queue.
145     * - Fwk takes over the release_fence ownership
146     */
147    sp<Fence> releaseFence = new Fence(buffer.release_fence);
148    res = mConsumer->releaseBuffer(bufferItem, releaseFence);
149    if (res != OK) {
150        ALOGE("%s: Stream %d: Error releasing buffer back to buffer queue:"
151                " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
152    }
153
154    *releaseFenceOut = releaseFence;
155
156    return res;
157}
158
159status_t Camera3InputStream::returnInputBufferLocked(
160        const camera3_stream_buffer &buffer) {
161    ATRACE_CALL();
162
163    return returnAnyBufferLocked(buffer, /*timestamp*/0, /*output*/false);
164}
165
166status_t Camera3InputStream::getInputBufferProducerLocked(
167            sp<IGraphicBufferProducer> *producer) {
168    ATRACE_CALL();
169
170    if (producer == NULL) {
171        return BAD_VALUE;
172    } else if (mProducer == NULL) {
173        ALOGE("%s: No input stream is configured", __FUNCTION__);
174        return INVALID_OPERATION;
175    }
176
177    *producer = mProducer;
178    return OK;
179}
180
181status_t Camera3InputStream::disconnectLocked() {
182
183    status_t res;
184
185    if ((res = Camera3IOStreamBase::disconnectLocked()) != OK) {
186        return res;
187    }
188
189    assert(mBuffersInFlight.size() == 0);
190
191    mConsumer->abandon();
192
193    /**
194     *  no-op since we can't disconnect the producer from the consumer-side
195     */
196
197    mState = (mState == STATE_IN_RECONFIG) ? STATE_IN_CONFIG
198                                           : STATE_CONSTRUCTED;
199    return OK;
200}
201
202void Camera3InputStream::dump(int fd, const Vector<String16> &args) const {
203    (void) args;
204    String8 lines;
205    lines.appendFormat("    Stream[%d]: Input\n", mId);
206    write(fd, lines.string(), lines.size());
207
208    Camera3IOStreamBase::dump(fd, args);
209}
210
211status_t Camera3InputStream::configureQueueLocked() {
212    status_t res;
213
214    if ((res = Camera3IOStreamBase::configureQueueLocked()) != OK) {
215        return res;
216    }
217
218    assert(mMaxSize == 0);
219    assert(camera3_stream::format != HAL_PIXEL_FORMAT_BLOB);
220
221    mHandoutTotalBufferCount = 0;
222    mFrameCount = 0;
223
224    if (mConsumer.get() == 0) {
225        sp<IGraphicBufferProducer> producer;
226        sp<IGraphicBufferConsumer> consumer;
227        BufferQueue::createBufferQueue(&producer, &consumer);
228
229        int minUndequeuedBuffers = 0;
230        res = producer->query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBuffers);
231        if (res != OK || minUndequeuedBuffers < 0) {
232            ALOGE("%s: Stream %d: Could not query min undequeued buffers (error %d, bufCount %d)",
233                    __FUNCTION__, mId, res, minUndequeuedBuffers);
234            return res;
235        }
236        size_t minBufs = static_cast<size_t>(minUndequeuedBuffers);
237
238        if (camera3_stream::max_buffers == 0) {
239            ALOGE("%s: %d: HAL sets max_buffer to 0. Must be at least 1.",
240                    __FUNCTION__, __LINE__);
241            return INVALID_OPERATION;
242        }
243
244        /*
245         * We promise never to 'acquire' more than camera3_stream::max_buffers
246         * at any one time.
247         *
248         * Boost the number up to meet the minimum required buffer count.
249         *
250         * (Note that this sets consumer-side buffer count only,
251         * and not the sum of producer+consumer side as in other camera streams).
252         */
253        mTotalBufferCount = camera3_stream::max_buffers > minBufs ?
254            camera3_stream::max_buffers : minBufs;
255        // TODO: somehow set the total buffer count when producer connects?
256
257        mConsumer = new BufferItemConsumer(consumer, camera3_stream::usage,
258                                           mTotalBufferCount);
259        mConsumer->setName(String8::format("Camera3-InputStream-%d", mId));
260
261        mProducer = producer;
262    }
263
264    res = mConsumer->setDefaultBufferSize(camera3_stream::width,
265                                          camera3_stream::height);
266    if (res != OK) {
267        ALOGE("%s: Stream %d: Could not set buffer dimensions %dx%d",
268              __FUNCTION__, mId, camera3_stream::width, camera3_stream::height);
269        return res;
270    }
271    res = mConsumer->setDefaultBufferFormat(camera3_stream::format);
272    if (res != OK) {
273        ALOGE("%s: Stream %d: Could not set buffer format %d",
274              __FUNCTION__, mId, camera3_stream::format);
275        return res;
276    }
277
278    return OK;
279}
280
281status_t Camera3InputStream::getEndpointUsage(uint32_t *usage) const {
282    // Per HAL3 spec, input streams have 0 for their initial usage field.
283    *usage = 0;
284    return OK;
285}
286
287}; // namespace camera3
288
289}; // namespace android
290