• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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,nsecs_t readoutTimestamp,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             nsecs_t readoutTimestamp,
109             bool output,
110             int32_t /*transform*/,
111             const std::vector<size_t>&,
112             /*out*/
113             sp<Fence> *releaseFenceOut) {
114 
115     (void)timestamp;
116     (void)readoutTimestamp;
117     (void)output;
118     ALOG_ASSERT(!output, "Expected output to be false");
119 
120     status_t res;
121 
122     bool bufferFound = false;
123     BufferItem bufferItem;
124     {
125         // Find the buffer we are returning
126         Vector<BufferItem>::iterator it, end;
127         for (it = mBuffersInFlight.begin(), end = mBuffersInFlight.end();
128              it != end;
129              ++it) {
130 
131             const BufferItem& tmp = *it;
132             ANativeWindowBuffer *anb = tmp.mGraphicBuffer->getNativeBuffer();
133             if (anb != NULL && &(anb->handle) == buffer.buffer) {
134                 bufferFound = true;
135                 bufferItem = tmp;
136                 mBuffersInFlight.erase(it);
137                 break;
138             }
139         }
140     }
141     if (!bufferFound) {
142         ALOGE("%s: Stream %d: Can't return buffer that wasn't sent to HAL",
143               __FUNCTION__, mId);
144         return INVALID_OPERATION;
145     }
146 
147     if (buffer.status == CAMERA_BUFFER_STATUS_ERROR) {
148         if (buffer.release_fence != -1) {
149             ALOGE("%s: Stream %d: HAL should not set release_fence(%d) when "
150                   "there is an error", __FUNCTION__, mId, buffer.release_fence);
151             close(buffer.release_fence);
152         }
153 
154         /**
155          * Reassign release fence as the acquire fence incase of error
156          */
157         const_cast<camera_stream_buffer*>(&buffer)->release_fence =
158                 buffer.acquire_fence;
159     }
160 
161     /**
162      * Unconditionally return buffer to the buffer queue.
163      * - Fwk takes over the release_fence ownership
164      */
165     sp<Fence> releaseFence = new Fence(buffer.release_fence);
166     res = mConsumer->releaseBuffer(bufferItem, releaseFence);
167     if (res != OK) {
168         ALOGE("%s: Stream %d: Error releasing buffer back to buffer queue:"
169                 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
170     }
171 
172     *releaseFenceOut = releaseFence;
173 
174     return res;
175 }
176 
returnInputBufferLocked(const camera_stream_buffer & buffer)177 status_t Camera3InputStream::returnInputBufferLocked(
178         const camera_stream_buffer &buffer) {
179     ATRACE_CALL();
180 
181     return returnAnyBufferLocked(buffer, /*timestamp*/0, /*readoutTimestamp*/0,
182                                  /*output*/false, /*transform*/ -1);
183 }
184 
getInputBufferProducerLocked(sp<IGraphicBufferProducer> * producer)185 status_t Camera3InputStream::getInputBufferProducerLocked(
186             sp<IGraphicBufferProducer> *producer) {
187     ATRACE_CALL();
188 
189     if (producer == NULL) {
190         return BAD_VALUE;
191     } else if (mProducer == NULL) {
192         ALOGE("%s: No input stream is configured", __FUNCTION__);
193         return INVALID_OPERATION;
194     }
195 
196     *producer = mProducer;
197     return OK;
198 }
199 
disconnectLocked()200 status_t Camera3InputStream::disconnectLocked() {
201 
202     status_t res;
203 
204     if ((res = Camera3IOStreamBase::disconnectLocked()) != OK) {
205         return res;
206     }
207 
208     assert(mBuffersInFlight.size() == 0);
209 
210     mConsumer->abandon();
211 
212     /**
213      *  no-op since we can't disconnect the producer from the consumer-side
214      */
215 
216     mState = (mState == STATE_IN_RECONFIG) ? STATE_IN_CONFIG
217                                            : STATE_CONSTRUCTED;
218     return OK;
219 }
220 
dump(int fd,const Vector<String16> & args) const221 void Camera3InputStream::dump(int fd, const Vector<String16> &args) const {
222     (void) args;
223     String8 lines;
224     lines.appendFormat("    Stream[%d]: Input\n", mId);
225     write(fd, lines.string(), lines.size());
226 
227     Camera3IOStreamBase::dump(fd, args);
228 }
229 
configureQueueLocked()230 status_t Camera3InputStream::configureQueueLocked() {
231     status_t res;
232 
233     if ((res = Camera3IOStreamBase::configureQueueLocked()) != OK) {
234         return res;
235     }
236 
237     assert(mMaxSize == 0);
238     assert(camera_stream::format != HAL_PIXEL_FORMAT_BLOB);
239 
240     mHandoutTotalBufferCount = 0;
241     mFrameCount = 0;
242     mLastTimestamp = 0;
243 
244     if (mConsumer.get() == 0) {
245         sp<IGraphicBufferProducer> producer;
246         sp<IGraphicBufferConsumer> consumer;
247         BufferQueue::createBufferQueue(&producer, &consumer);
248 
249         int minUndequeuedBuffers = 0;
250         res = producer->query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBuffers);
251         if (res != OK || minUndequeuedBuffers < 0) {
252             ALOGE("%s: Stream %d: Could not query min undequeued buffers (error %d, bufCount %d)",
253                     __FUNCTION__, mId, res, minUndequeuedBuffers);
254             return res;
255         }
256         size_t minBufs = static_cast<size_t>(minUndequeuedBuffers);
257 
258         if (camera_stream::max_buffers == 0) {
259             ALOGE("%s: %d: HAL sets max_buffer to 0. Must be at least 1.",
260                     __FUNCTION__, __LINE__);
261             return INVALID_OPERATION;
262         }
263 
264         /*
265          * We promise never to 'acquire' more than camera_stream::max_buffers
266          * at any one time.
267          *
268          * Boost the number up to meet the minimum required buffer count.
269          *
270          * (Note that this sets consumer-side buffer count only,
271          * and not the sum of producer+consumer side as in other camera streams).
272          */
273         mTotalBufferCount = camera_stream::max_buffers > minBufs ?
274             camera_stream::max_buffers : minBufs;
275         // TODO: somehow set the total buffer count when producer connects?
276 
277         mConsumer = new BufferItemConsumer(consumer, mUsage,
278                                            mTotalBufferCount);
279         mConsumer->setName(String8::format("Camera3-InputStream-%d", mId));
280 
281         mProducer = producer;
282 
283         mConsumer->setBufferFreedListener(this);
284     }
285 
286     res = mConsumer->setDefaultBufferSize(camera_stream::width,
287                                           camera_stream::height);
288     if (res != OK) {
289         ALOGE("%s: Stream %d: Could not set buffer dimensions %dx%d",
290               __FUNCTION__, mId, camera_stream::width, camera_stream::height);
291         return res;
292     }
293     res = mConsumer->setDefaultBufferFormat(camera_stream::format);
294     if (res != OK) {
295         ALOGE("%s: Stream %d: Could not set buffer format %d",
296               __FUNCTION__, mId, camera_stream::format);
297         return res;
298     }
299 
300     return OK;
301 }
302 
getEndpointUsage(uint64_t * usage) const303 status_t Camera3InputStream::getEndpointUsage(uint64_t *usage) const {
304     // Per HAL3 spec, input streams have 0 for their initial usage field.
305     *usage = 0;
306     return OK;
307 }
308 
onBufferFreed(const wp<GraphicBuffer> & gb)309 void Camera3InputStream::onBufferFreed(const wp<GraphicBuffer>& gb) {
310     const sp<GraphicBuffer> buffer = gb.promote();
311     if (buffer != nullptr) {
312         camera_stream_buffer streamBuffer =
313                 {nullptr, &buffer->handle, CAMERA_BUFFER_STATUS_OK, -1, -1};
314         // Check if this buffer is outstanding.
315         if (isOutstandingBuffer(streamBuffer)) {
316             ALOGV("%s: Stream %d: Trying to free a buffer that is still being "
317                     "processed.", __FUNCTION__, mId);
318             return;
319         }
320 
321         sp<Camera3StreamBufferFreedListener> callback = mBufferFreedListener.promote();
322         if (callback != nullptr) {
323             callback->onBufferFreed(mId, buffer->handle);
324         }
325     } else {
326         ALOGE("%s: GraphicBuffer is freed before onBufferFreed callback finishes!", __FUNCTION__);
327     }
328 }
329 
330 }; // namespace camera3
331 
332 }; // namespace android
333