JpegProcessor.cpp revision 138851bd3cadfb60238f87567e24808925731837
1/*
2 * Copyright (C) 2012 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 "Camera2-JpegProcessor"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20
21#include <netinet/in.h>
22
23#include <binder/MemoryBase.h>
24#include <binder/MemoryHeapBase.h>
25#include <utils/Log.h>
26#include <utils/Trace.h>
27#include <gui/Surface.h>
28
29#include "common/CameraDeviceBase.h"
30#include "api1/Camera2Client.h"
31#include "api1/client2/Camera2Heap.h"
32#include "api1/client2/CaptureSequencer.h"
33#include "api1/client2/JpegProcessor.h"
34
35namespace android {
36namespace camera2 {
37
38JpegProcessor::JpegProcessor(
39    sp<Camera2Client> client,
40    wp<CaptureSequencer> sequencer):
41        Thread(false),
42        mDevice(client->getCameraDevice()),
43        mSequencer(sequencer),
44        mId(client->getCameraId()),
45        mCaptureAvailable(false),
46        mCaptureStreamId(NO_STREAM) {
47}
48
49JpegProcessor::~JpegProcessor() {
50    ALOGV("%s: Exit", __FUNCTION__);
51    deleteStream();
52}
53
54void JpegProcessor::onFrameAvailable() {
55    Mutex::Autolock l(mInputMutex);
56    if (!mCaptureAvailable) {
57        mCaptureAvailable = true;
58        mCaptureAvailableSignal.signal();
59    }
60}
61
62status_t JpegProcessor::updateStream(const Parameters &params) {
63    ATRACE_CALL();
64    ALOGV("%s", __FUNCTION__);
65    status_t res;
66
67    Mutex::Autolock l(mInputMutex);
68
69    sp<CameraDeviceBase> device = mDevice.promote();
70    if (device == 0) {
71        ALOGE("%s: Camera %d: Device does not exist", __FUNCTION__, mId);
72        return INVALID_OPERATION;
73    }
74
75    // Find out buffer size for JPEG
76    camera_metadata_ro_entry_t maxJpegSize =
77            params.staticInfo(ANDROID_JPEG_MAX_SIZE);
78    if (maxJpegSize.count == 0) {
79        ALOGE("%s: Camera %d: Can't find ANDROID_JPEG_MAX_SIZE!",
80                __FUNCTION__, mId);
81        return INVALID_OPERATION;
82    }
83
84    if (mCaptureConsumer == 0) {
85        // Create CPU buffer queue endpoint
86        sp<BufferQueue> bq = new BufferQueue();
87        mCaptureConsumer = new CpuConsumer(bq, 1);
88        mCaptureConsumer->setFrameAvailableListener(this);
89        mCaptureConsumer->setName(String8("Camera2Client::CaptureConsumer"));
90        mCaptureWindow = new Surface(bq);
91        // Create memory for API consumption
92        mCaptureHeap = new MemoryHeapBase(maxJpegSize.data.i32[0], 0,
93                                       "Camera2Client::CaptureHeap");
94        if (mCaptureHeap->getSize() == 0) {
95            ALOGE("%s: Camera %d: Unable to allocate memory for capture",
96                    __FUNCTION__, mId);
97            return NO_MEMORY;
98        }
99    }
100
101    if (mCaptureStreamId != NO_STREAM) {
102        // Check if stream parameters have to change
103        uint32_t currentWidth, currentHeight;
104        res = device->getStreamInfo(mCaptureStreamId,
105                &currentWidth, &currentHeight, 0);
106        if (res != OK) {
107            ALOGE("%s: Camera %d: Error querying capture output stream info: "
108                    "%s (%d)", __FUNCTION__,
109                    mId, strerror(-res), res);
110            return res;
111        }
112        if (currentWidth != (uint32_t)params.pictureWidth ||
113                currentHeight != (uint32_t)params.pictureHeight) {
114            ALOGV("%s: Camera %d: Deleting stream %d since the buffer dimensions changed",
115                __FUNCTION__, mId, mCaptureStreamId);
116            res = device->deleteStream(mCaptureStreamId);
117            if (res == -EBUSY) {
118                ALOGV("%s: Camera %d: Device is busy, call updateStream again "
119                      " after it becomes idle", __FUNCTION__, mId);
120                return res;
121            } else if (res != OK) {
122                ALOGE("%s: Camera %d: Unable to delete old output stream "
123                        "for capture: %s (%d)", __FUNCTION__,
124                        mId, strerror(-res), res);
125                return res;
126            }
127            mCaptureStreamId = NO_STREAM;
128        }
129    }
130
131    if (mCaptureStreamId == NO_STREAM) {
132        // Create stream for HAL production
133        res = device->createStream(mCaptureWindow,
134                params.pictureWidth, params.pictureHeight,
135                HAL_PIXEL_FORMAT_BLOB, maxJpegSize.data.i32[0],
136                &mCaptureStreamId);
137        if (res != OK) {
138            ALOGE("%s: Camera %d: Can't create output stream for capture: "
139                    "%s (%d)", __FUNCTION__, mId,
140                    strerror(-res), res);
141            return res;
142        }
143
144    }
145    return OK;
146}
147
148status_t JpegProcessor::deleteStream() {
149    ATRACE_CALL();
150
151    Mutex::Autolock l(mInputMutex);
152
153    if (mCaptureStreamId != NO_STREAM) {
154        sp<CameraDeviceBase> device = mDevice.promote();
155        if (device == 0) {
156            ALOGE("%s: Camera %d: Device does not exist", __FUNCTION__, mId);
157            return INVALID_OPERATION;
158        }
159
160        device->deleteStream(mCaptureStreamId);
161
162        mCaptureHeap.clear();
163        mCaptureWindow.clear();
164        mCaptureConsumer.clear();
165
166        mCaptureStreamId = NO_STREAM;
167    }
168    return OK;
169}
170
171int JpegProcessor::getStreamId() const {
172    Mutex::Autolock l(mInputMutex);
173    return mCaptureStreamId;
174}
175
176void JpegProcessor::dump(int /*fd*/, const Vector<String16>& /*args*/) const {
177}
178
179bool JpegProcessor::threadLoop() {
180    status_t res;
181
182    {
183        Mutex::Autolock l(mInputMutex);
184        while (!mCaptureAvailable) {
185            res = mCaptureAvailableSignal.waitRelative(mInputMutex,
186                    kWaitDuration);
187            if (res == TIMED_OUT) return true;
188        }
189        mCaptureAvailable = false;
190    }
191
192    do {
193        res = processNewCapture();
194    } while (res == OK);
195
196    return true;
197}
198
199status_t JpegProcessor::processNewCapture() {
200    ATRACE_CALL();
201    status_t res;
202    sp<Camera2Heap> captureHeap;
203    sp<MemoryBase> captureBuffer;
204
205    CpuConsumer::LockedBuffer imgBuffer;
206
207    {
208        Mutex::Autolock l(mInputMutex);
209        if (mCaptureStreamId == NO_STREAM) {
210            ALOGW("%s: Camera %d: No stream is available", __FUNCTION__, mId);
211            return INVALID_OPERATION;
212        }
213
214        res = mCaptureConsumer->lockNextBuffer(&imgBuffer);
215        if (res != OK) {
216            if (res != BAD_VALUE) {
217                ALOGE("%s: Camera %d: Error receiving still image buffer: "
218                        "%s (%d)", __FUNCTION__,
219                        mId, strerror(-res), res);
220            }
221            return res;
222        }
223
224        ALOGV("%s: Camera %d: Still capture available", __FUNCTION__,
225                mId);
226
227        if (imgBuffer.format != HAL_PIXEL_FORMAT_BLOB) {
228            ALOGE("%s: Camera %d: Unexpected format for still image: "
229                    "%x, expected %x", __FUNCTION__, mId,
230                    imgBuffer.format,
231                    HAL_PIXEL_FORMAT_BLOB);
232            mCaptureConsumer->unlockBuffer(imgBuffer);
233            return OK;
234        }
235
236        // Find size of JPEG image
237        size_t jpegSize = findJpegSize(imgBuffer.data, imgBuffer.width);
238        if (jpegSize == 0) { // failed to find size, default to whole buffer
239            jpegSize = imgBuffer.width;
240        }
241        size_t heapSize = mCaptureHeap->getSize();
242        if (jpegSize > heapSize) {
243            ALOGW("%s: JPEG image is larger than expected, truncating "
244                    "(got %d, expected at most %d bytes)",
245                    __FUNCTION__, jpegSize, heapSize);
246            jpegSize = heapSize;
247        }
248
249        // TODO: Optimize this to avoid memcopy
250        captureBuffer = new MemoryBase(mCaptureHeap, 0, jpegSize);
251        void* captureMemory = mCaptureHeap->getBase();
252        memcpy(captureMemory, imgBuffer.data, jpegSize);
253
254        mCaptureConsumer->unlockBuffer(imgBuffer);
255    }
256
257    sp<CaptureSequencer> sequencer = mSequencer.promote();
258    if (sequencer != 0) {
259        sequencer->onCaptureAvailable(imgBuffer.timestamp, captureBuffer);
260    }
261
262    return OK;
263}
264
265/*
266 * JPEG FILE FORMAT OVERVIEW.
267 * http://www.jpeg.org/public/jfif.pdf
268 * (JPEG is the image compression algorithm, actual file format is called JFIF)
269 *
270 * "Markers" are 2-byte patterns used to distinguish parts of JFIF files.  The
271 * first byte is always 0xFF, and the second byte is between 0x01 and 0xFE
272 * (inclusive).  Because every marker begins with the same byte, they are
273 * referred to by the second byte's value.
274 *
275 * JFIF files all begin with the Start of Image (SOI) marker, which is 0xD8.
276 * Following it, "segment" sections begin with other markers, followed by a
277 * 2-byte length (in network byte order), then the segment data.
278 *
279 * For our purposes we will ignore the data, and just use the length to skip to
280 * the next segment.  This is necessary because the data inside segments are
281 * allowed to contain the End of Image marker (0xFF 0xD9), preventing us from
282 * naievely scanning until the end.
283 *
284 * After all the segments are processed, the jpeg compressed image stream begins.
285 * This can be considered an opaque format with one requirement: all 0xFF bytes
286 * in this stream must be followed with a 0x00 byte.  This prevents any of the
287 * image data to be interpreted as a segment.  The only exception to this is at
288 * the end of the image stream there is an End of Image (EOI) marker, which is
289 * 0xFF followed by a non-zero (0xD9) byte.
290 */
291
292const uint8_t MARK = 0xFF; // First byte of marker
293const uint8_t SOI = 0xD8; // Start of Image
294const uint8_t EOI = 0xD9; // End of Image
295const size_t MARKER_LENGTH = 2; // length of a marker
296
297#pragma pack(push)
298#pragma pack(1)
299typedef struct segment {
300    uint8_t marker[MARKER_LENGTH];
301    uint16_t length;
302} segment_t;
303#pragma pack(pop)
304
305/* HELPER FUNCTIONS */
306
307// check for Start of Image marker
308bool checkJpegStart(uint8_t* buf) {
309    return buf[0] == MARK && buf[1] == SOI;
310}
311// check for End of Image marker
312bool checkJpegEnd(uint8_t *buf) {
313    return buf[0] == MARK && buf[1] == EOI;
314}
315// check for arbitrary marker, returns marker type (second byte)
316// returns 0 if no marker found. Note: 0x00 is not a valid marker type
317uint8_t checkJpegMarker(uint8_t *buf) {
318    if (buf[0] == MARK && buf[1] > 0 && buf[1] < 0xFF) {
319        return buf[1];
320    }
321    return 0;
322}
323
324// Return the size of the JPEG, 0 indicates failure
325size_t JpegProcessor::findJpegSize(uint8_t* jpegBuffer, size_t maxSize) {
326    size_t size;
327
328    // First check for JPEG transport header at the end of the buffer
329    uint8_t *header = jpegBuffer + (maxSize - sizeof(struct camera2_jpeg_blob));
330    struct camera2_jpeg_blob *blob = (struct camera2_jpeg_blob*)(header);
331    if (blob->jpeg_blob_id == CAMERA2_JPEG_BLOB_ID) {
332        size = blob->jpeg_size;
333        if (size > 0 && size <= maxSize - sizeof(struct camera2_jpeg_blob)) {
334            // Verify SOI and EOI markers
335            size_t offset = size - MARKER_LENGTH;
336            uint8_t *end = jpegBuffer + offset;
337            if (checkJpegStart(jpegBuffer) && checkJpegEnd(end)) {
338                ALOGV("Found JPEG transport header, img size %d", size);
339                return size;
340            } else {
341                ALOGW("Found JPEG transport header with bad Image Start/End");
342            }
343        } else {
344            ALOGW("Found JPEG transport header with bad size %d", size);
345        }
346    }
347
348    // Check Start of Image
349    if ( !checkJpegStart(jpegBuffer) ) {
350        ALOGE("Could not find start of JPEG marker");
351        return 0;
352    }
353
354    // Read JFIF segment markers, skip over segment data
355    size = 0;
356    while (size <= maxSize - MARKER_LENGTH) {
357        segment_t *segment = (segment_t*)(jpegBuffer + size);
358        uint8_t type = checkJpegMarker(segment->marker);
359        if (type == 0) { // invalid marker, no more segments, begin JPEG data
360            ALOGV("JPEG stream found beginning at offset %d", size);
361            break;
362        }
363        if (type == EOI || size > maxSize - sizeof(segment_t)) {
364            ALOGE("Got premature End before JPEG data, offset %d", size);
365            return 0;
366        }
367        size_t length = ntohs(segment->length);
368        ALOGV("JFIF Segment, type %x length %x", type, length);
369        size += length + MARKER_LENGTH;
370    }
371
372    // Find End of Image
373    // Scan JPEG buffer until End of Image (EOI)
374    bool foundEnd = false;
375    for ( ; size <= maxSize - MARKER_LENGTH; size++) {
376        if ( checkJpegEnd(jpegBuffer + size) ) {
377            foundEnd = true;
378            size += MARKER_LENGTH;
379            break;
380        }
381    }
382    if (!foundEnd) {
383        ALOGE("Could not find end of JPEG marker");
384        return 0;
385    }
386
387    if (size > maxSize) {
388        ALOGW("JPEG size %d too large, reducing to maxSize %d", size, maxSize);
389        size = maxSize;
390    }
391    ALOGV("Final JPEG size %d", size);
392    return size;
393}
394
395}; // namespace camera2
396}; // namespace android
397