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