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