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-IOStreamBase"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20
21#include <inttypes.h>
22
23#include <utils/Log.h>
24#include <utils/Trace.h>
25#include "device3/Camera3IOStreamBase.h"
26#include "device3/StatusTracker.h"
27
28namespace android {
29
30namespace camera3 {
31
32Camera3IOStreamBase::Camera3IOStreamBase(int id, camera3_stream_type_t type,
33        uint32_t width, uint32_t height, size_t maxSize, int format,
34        android_dataspace dataSpace, camera3_stream_rotation_t rotation,
35        const String8& physicalCameraId, int setId) :
36        Camera3Stream(id, type,
37                width, height, maxSize, format, dataSpace, rotation,
38                physicalCameraId, setId),
39        mTotalBufferCount(0),
40        mHandoutTotalBufferCount(0),
41        mHandoutOutputBufferCount(0),
42        mFrameCount(0),
43        mLastTimestamp(0) {
44
45    mCombinedFence = new Fence();
46
47    if (maxSize > 0 &&
48            (format != HAL_PIXEL_FORMAT_BLOB && format != HAL_PIXEL_FORMAT_RAW_OPAQUE)) {
49        ALOGE("%s: Bad format for size-only stream: %d", __FUNCTION__,
50                format);
51        mState = STATE_ERROR;
52    }
53}
54
55Camera3IOStreamBase::~Camera3IOStreamBase() {
56    disconnectLocked();
57}
58
59bool Camera3IOStreamBase::hasOutstandingBuffersLocked() const {
60    nsecs_t signalTime = mCombinedFence->getSignalTime();
61    ALOGV("%s: Stream %d: Has %zu outstanding buffers,"
62            " buffer signal time is %" PRId64,
63            __FUNCTION__, mId, mHandoutTotalBufferCount, signalTime);
64    if (mHandoutTotalBufferCount > 0 || signalTime == INT64_MAX) {
65        return true;
66    }
67    return false;
68}
69
70void Camera3IOStreamBase::dump(int fd, const Vector<String16> &args) const {
71    (void) args;
72    String8 lines;
73
74    uint64_t consumerUsage = 0;
75    status_t res = getEndpointUsage(&consumerUsage);
76    if (res != OK) consumerUsage = 0;
77
78    lines.appendFormat("      State: %d\n", mState);
79    lines.appendFormat("      Dims: %d x %d, format 0x%x, dataspace 0x%x\n",
80            camera3_stream::width, camera3_stream::height,
81            camera3_stream::format, camera3_stream::data_space);
82    lines.appendFormat("      Max size: %zu\n", mMaxSize);
83    lines.appendFormat("      Combined usage: %" PRIu64 ", max HAL buffers: %d\n",
84            mUsage | consumerUsage, camera3_stream::max_buffers);
85    lines.appendFormat("      Frames produced: %d, last timestamp: %" PRId64 " ns\n",
86            mFrameCount, mLastTimestamp);
87    lines.appendFormat("      Total buffers: %zu, currently dequeued: %zu\n",
88            mTotalBufferCount, mHandoutTotalBufferCount);
89    write(fd, lines.string(), lines.size());
90
91    Camera3Stream::dump(fd, args);
92}
93
94status_t Camera3IOStreamBase::configureQueueLocked() {
95    status_t res;
96
97    switch (mState) {
98        case STATE_IN_RECONFIG:
99            res = disconnectLocked();
100            if (res != OK) {
101                return res;
102            }
103            break;
104        case STATE_IN_CONFIG:
105            // OK
106            break;
107        default:
108            ALOGE("%s: Bad state: %d", __FUNCTION__, mState);
109            return INVALID_OPERATION;
110    }
111
112    return OK;
113}
114
115size_t Camera3IOStreamBase::getBufferCountLocked() {
116    return mTotalBufferCount;
117}
118
119size_t Camera3IOStreamBase::getHandoutOutputBufferCountLocked() {
120    return mHandoutOutputBufferCount;
121}
122
123size_t Camera3IOStreamBase::getHandoutInputBufferCountLocked() {
124    return (mHandoutTotalBufferCount - mHandoutOutputBufferCount);
125}
126
127status_t Camera3IOStreamBase::disconnectLocked() {
128    switch (mState) {
129        case STATE_IN_RECONFIG:
130        case STATE_CONFIGURED:
131        case STATE_ABANDONED:
132            // OK
133            break;
134        default:
135            // No connection, nothing to do
136            ALOGV("%s: Stream %d: Already disconnected",
137                  __FUNCTION__, mId);
138            return -ENOTCONN;
139    }
140
141    if (mHandoutTotalBufferCount > 0) {
142        ALOGE("%s: Can't disconnect with %zu buffers still dequeued!",
143                __FUNCTION__, mHandoutTotalBufferCount);
144        return INVALID_OPERATION;
145    }
146
147   return OK;
148}
149
150void Camera3IOStreamBase::handoutBufferLocked(camera3_stream_buffer &buffer,
151                                              buffer_handle_t *handle,
152                                              int acquireFence,
153                                              int releaseFence,
154                                              camera3_buffer_status_t status,
155                                              bool output) {
156    /**
157     * Note that all fences are now owned by HAL.
158     */
159
160    // Handing out a raw pointer to this object. Increment internal refcount.
161    incStrong(this);
162    buffer.stream = this;
163    buffer.buffer = handle;
164    buffer.acquire_fence = acquireFence;
165    buffer.release_fence = releaseFence;
166    buffer.status = status;
167
168    // Inform tracker about becoming busy
169    if (mHandoutTotalBufferCount == 0 && mState != STATE_IN_CONFIG &&
170            mState != STATE_IN_RECONFIG && mState != STATE_PREPARING) {
171        /**
172         * Avoid a spurious IDLE->ACTIVE->IDLE transition when using buffers
173         * before/after register_stream_buffers during initial configuration
174         * or re-configuration, or during prepare pre-allocation
175         */
176        sp<StatusTracker> statusTracker = mStatusTracker.promote();
177        if (statusTracker != 0) {
178            statusTracker->markComponentActive(mStatusId);
179        }
180    }
181    mHandoutTotalBufferCount++;
182
183    if (output) {
184        mHandoutOutputBufferCount++;
185    }
186}
187
188status_t Camera3IOStreamBase::getBufferPreconditionCheckLocked() const {
189    // Allow dequeue during IN_[RE]CONFIG for registration, in
190    // PREPARING for pre-allocation
191    if (mState != STATE_CONFIGURED &&
192            mState != STATE_IN_CONFIG && mState != STATE_IN_RECONFIG &&
193            mState != STATE_PREPARING) {
194        ALOGE("%s: Stream %d: Can't get buffers in unconfigured state %d",
195                __FUNCTION__, mId, mState);
196        return INVALID_OPERATION;
197    }
198
199    return OK;
200}
201
202status_t Camera3IOStreamBase::returnBufferPreconditionCheckLocked() const {
203    // Allow buffers to be returned in the error state, to allow for disconnect
204    // and in the in-config states for registration
205    if (mState == STATE_CONSTRUCTED) {
206        ALOGE("%s: Stream %d: Can't return buffers in unconfigured state %d",
207                __FUNCTION__, mId, mState);
208        return INVALID_OPERATION;
209    }
210    if (mHandoutTotalBufferCount == 0) {
211        ALOGE("%s: Stream %d: No buffers outstanding to return", __FUNCTION__,
212                mId);
213        return INVALID_OPERATION;
214    }
215
216    return OK;
217}
218
219status_t Camera3IOStreamBase::returnAnyBufferLocked(
220        const camera3_stream_buffer &buffer,
221        nsecs_t timestamp,
222        bool output) {
223    status_t res;
224
225    // returnBuffer may be called from a raw pointer, not a sp<>, and we'll be
226    // decrementing the internal refcount next. In case this is the last ref, we
227    // might get destructed on the decStrong(), so keep an sp around until the
228    // end of the call - otherwise have to sprinkle the decStrong on all exit
229    // points.
230    sp<Camera3IOStreamBase> keepAlive(this);
231    decStrong(this);
232
233    if ((res = returnBufferPreconditionCheckLocked()) != OK) {
234        return res;
235    }
236
237    sp<Fence> releaseFence;
238    res = returnBufferCheckedLocked(buffer, timestamp, output,
239                                    &releaseFence);
240    // Res may be an error, but we still want to decrement our owned count
241    // to enable clean shutdown. So we'll just return the error but otherwise
242    // carry on
243
244    if (releaseFence != 0) {
245        mCombinedFence = Fence::merge(mName, mCombinedFence, releaseFence);
246    }
247
248    if (output) {
249        mHandoutOutputBufferCount--;
250    }
251
252    mHandoutTotalBufferCount--;
253    if (mHandoutTotalBufferCount == 0 && mState != STATE_IN_CONFIG &&
254            mState != STATE_IN_RECONFIG && mState != STATE_PREPARING) {
255        /**
256         * Avoid a spurious IDLE->ACTIVE->IDLE transition when using buffers
257         * before/after register_stream_buffers during initial configuration
258         * or re-configuration, or during prepare pre-allocation
259         */
260        ALOGV("%s: Stream %d: All buffers returned; now idle", __FUNCTION__,
261                mId);
262        sp<StatusTracker> statusTracker = mStatusTracker.promote();
263        if (statusTracker != 0) {
264            statusTracker->markComponentIdle(mStatusId, mCombinedFence);
265        }
266    }
267
268    mBufferReturnedSignal.signal();
269
270    if (output) {
271        mLastTimestamp = timestamp;
272    }
273
274    return res;
275}
276
277
278
279}; // namespace camera3
280
281}; // namespace android
282