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