我是靠谱客的博主 狂野缘分,最近开发中收集的这篇文章主要介绍Android camera 拍照 流程APP,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

APP

347    /**
348     * Take picture, initiating an auto focus scan if needed.
349     */
350    @Override
351    public void takePicture(final PhotoCaptureParameters params, final CaptureSession session) {
352        // Do not do anything when a picture is already requested.
353        if (mTakePictureWhenLensIsStopped) {
354            return;
355        }
356
357        // Not ready until the picture comes back.
358        broadcastReadyState(false);
359
360        mTakePictureRunnable = new Runnable() {
361            @Override
362            public void run() {
363                takePictureNow(params, session);
364            }
365        };
366        mLastPictureCallback = params.callback;
367        mTakePictureStartMillis = SystemClock.uptimeMillis();
368
369        // This class implements a very simple version of AF, which
370        // only delays capture if the lens is scanning.
371        if (mLastResultAFState == AutoFocusState.ACTIVE_SCAN) {
372            Log.v(TAG, "Waiting until scan is done before taking shot.");
373            mTakePictureWhenLensIsStopped = true;
374        } else {
375            // We could do CONTROL_AF_TRIGGER_START and wait until lens locks,
376            // but this would slow down the capture.
377            takePictureNow(params, session);
378        }
379    }
380
381    /**
382     * Take picture immediately. Parameters passed through from takePicture().
383     */
384    public void takePictureNow(PhotoCaptureParameters params, CaptureSession session) {
385        long dt = SystemClock.uptimeMillis() - mTakePictureStartMillis;
386        Log.v(TAG, "Taking shot with extra AF delay of " + dt + " ms.");
387        try {
388            // JPEG capture.

//TEMPLATE_STILL_CAPTURE 表示当前创建的request是拍照
389            CaptureRequest.Builder builder = mDevice
390                    .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
391            builder.setTag(RequestTag.CAPTURE);
392            addBaselineCaptureKeysToRequest(builder);
393
394            // Enable lens-shading correction for even better DNGs.
395            if (sCaptureImageFormat == ImageFormat.RAW_SENSOR) {
396                builder.set(CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE,
397                        CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE_ON);
398            } else if (sCaptureImageFormat == ImageFormat.JPEG) {
399                builder.set(CaptureRequest.JPEG_QUALITY, JPEG_QUALITY);
400                builder.set(CaptureRequest.JPEG_ORIENTATION,
401                        CameraUtil.getJpegRotation(params.orientation, mCharacteristics));
402            }

//增加surface,一个是预览的surface,一个是ImageReader 的 surface 
404            builder.addTarget(mPreviewSurface);
405            builder.addTarget(mCaptureImageReader.getSurface());
406            CaptureRequest request = builder.build();
407
408            if (DEBUG_WRITE_CAPTURE_DATA) {
409                final String debugDataDir = makeDebugDir(params.debugDataFolder,
410                        "normal_capture_debug");
411                Log.i(TAG, "Writing capture data to: " + debugDataDir);
412                CaptureDataSerializer.toFile("Normal Capture", request, new File(debugDataDir,
413                        "capture.txt"));
414            }
415

//拍照请求添加到Framework
416            mCaptureSession.capture(request, mCaptureCallback, mCameraHandler);
417        } catch (CameraAccessException e) {
418            Log.e(TAG, "Could not access camera for still image capture.");
419            broadcastReadyState(true);
420            params.callback.onPictureTakingFailed();
421            return;
422        }
423        synchronized (mCaptureQueue) {
424            mCaptureQueue.add(new InFlightCapture(params, session));
425        }
426    }

Framework

APP中,通过 mCaptureSession.capture() 调用到 CameraCaptureSessionImpl::capture(),从而进入Framework 执行:

/frameworks/base/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java

/frameworks/base/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java

1044    public int capture(CaptureRequest request, CaptureCallback callback, Executor executor)
1045            throws CameraAccessException {
1046        if (DEBUG) {
1047            Log.d(TAG, "calling capture");
1048        }
1049        List<CaptureRequest> requestList = new ArrayList<CaptureRequest>();
1050        requestList.add(request);
1051        return submitCaptureRequest(requestList, callback, executor, /*streaming*/false);
1052    }

在 CameraDeviceImpl::submitCaptureRequest() 中,检查参数之后,又将通过 mRemoteDevice.submitRequestList() 将请求调用到 CameraService进行处理,剩下的操作和预览时的流程类似。

/frameworks/base/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java

//streaming 是 false
85    public SubmitInfo submitRequestList(CaptureRequest[] requestList, boolean streaming)
86            throws CameraAccessException {
87        try {
88            return mRemoteDevice.submitRequestList(requestList, streaming);
89        } catch (Throwable t) {
90            CameraManager.throwAsPublicException(t);
91            throw new UnsupportedOperationException("Unexpected exception", t);
92        }
93    }

进入CameraService /frameworks/av/services/camera/libcameraservice/api2/CameraDeviceClient.cpp 

187binder::Status CameraDeviceClient::submitRequestList(
188        const std::vector<hardware::camera2::CaptureRequest>& requests,
189        bool streaming,
190        /*out*/
191        hardware::camera2::utils::SubmitInfo *submitInfo) {
。。。。
。。。。
406    } else {

//拍照走这条路,调用到 Camera3Device 的 captureList()
407        err = mDevice->captureList(metadataRequestList, surfaceMapList,
408                &(submitInfo->mLastFrameNumber));

。。。。
。。。。
422}
949status_t Camera3Device::submitRequestsHelper(
950        const List<const PhysicalCameraSettingsList> &requests,
951        const std::list<const SurfaceMap> &surfaceMaps,
952        bool repeating,
953        /*out*/
954        int64_t *lastFrameNumber) {

。。。。
。。。。
//转换信息,并指定 surface id
967    res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
968            repeating, /*out*/&requestList);
969    if (res != OK) {
970        // error logged by previous call
971        return res;
972    }
973
974    if (repeating) {
975        res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
976    } else {

//添加信息到 mRequestThread 线程的 mRequestQueue 队列, 
//该线程在open camera时已经运行,在该函数中,将调用
//Camera3Device::RequestThread::unpauseForNewRequests() 
//函数发送信号量告知 mRequestThread 线程
977        res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
。。。。
。。。。
994}
4257bool Camera3Device::RequestThread::threadLoop() {

......
......

// Prepare a batch of HAL requests and output buffers.
//处理请求并申请output buffer,以待 HAL 填充图像数据
4323    res = prepareHalRequests();

......
......

//发送请求到 HAL
4366    submitRequestSuccess = sendRequestsBatch();

......
......
4383}
bool Camera3Device::RequestThread::sendRequestsBatch() {
4070    ATRACE_CALL();
4071    status_t res;
4072    size_t batchSize = mNextRequests.size();
4073    std::vector<camera3_capture_request_t*> requests(batchSize);
4074    uint32_t numRequestProcessed = 0;
4075    for (size_t i = 0; i < batchSize; i++) {
4076        requests[i] = &mNextRequests.editItemAt(i).halRequest;
4077        ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
4078    }

//将请求信息传递到 CameraProvider 处理
4080    res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
......
......
}

在 mRequestThread 线程中,获取请求信息之后,经过CameraProvider提交请求信息到 HAL

/hardware/interfaces/camera/device/3.2/default/CameraDeviceSession.cpp

Return<void> CameraDeviceSession::processCaptureRequest(
1138        const hidl_vec<CaptureRequest>& requests,
1139        const hidl_vec<BufferCache>& cachesToRemove,
1140        ICameraDeviceSession::processCaptureRequest_cb _hidl_cb)  {
1141    updateBufferCaches(cachesToRemove);
1142
1143    uint32_t numRequestProcessed = 0;
1144    Status s = Status::OK;
1145    for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
1146        s = processOneCaptureRequest(requests[i]);
1147        if (s != Status::OK) {
1148            break;
1149        }
1150    }
1151
1152    if (s == Status::OK && requests.size() > 1) {
1153        mResultBatcher.registerBatch(requests[0].frameNumber, requests.size());
1154    }
1155
1156    _hidl_cb(s, numRequestProcessed);
1157    return Void();
}



Status CameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request)  {
......
......

//将调用 HAL 的process_capture_request() 函数,将请求添加到 HAL 队列
1256    ATRACE_ASYNC_BEGIN("frame capture", request.frameNumber);
1257    ATRACE_BEGIN("camera3->process_capture_request");
1258    status_t ret = mDevice->ops->process_capture_request(mDevice, &halRequest);
1259    ATRACE_END();

......
......
}

拍照请求返回

在APP中

mCaptureSession.capture(request, mCaptureCallback, mCameraHandler);

mCaptureCallback为 CameraCaptureSession.CaptureCallback 对象。

当拍照完成,会调用onCaptureCompleted

224                @Override
225                public void onCaptureCompleted(CameraCaptureSession session,
226                        CaptureRequest request, TotalCaptureResult result) {
227                    autofocusStateChangeDispatcher(result);
228                    // This checks for a HAL implementation error where
229                    // TotalCaptureResult
230                    // is missing CONTROL_AF_STATE. This should not happen.
231                    if (result.get(CaptureResult.CONTROL_AF_STATE) == null) {
232                        AutoFocusHelper.checkControlAfState(result);
233                    }
234                    if (DEBUG_FOCUS_LOG) {
235                        AutoFocusHelper.logExtraFocusInfo(result);
236                    }
237
238                    Float diopter = result.get(CaptureResult.LENS_FOCUS_DISTANCE);
239                    if (diopter != null && mFocusDistanceListener != null) {
240                        mFocusDistanceListener.onFocusDistance(diopter, mLensRange);
241                    }
242

//CAPTURE 时,将进行下面的操作
243                    if (request.getTag() == RequestTag.CAPTURE) {
244                        // Add the capture result to the latest in-flight
245                        // capture. If all the data for that capture is
246                        // complete, store the image on disk.
247                        InFlightCapture capture = null;
248                        synchronized (mCaptureQueue) {
249                            if (mCaptureQueue.getFirst().setCaptureResult(result)
250                                    .isCaptureComplete()) {
251                                capture = mCaptureQueue.removeFirst();
252                            }
253                        }
254                        if (capture != null) {
255                            OneCameraImpl.this.onCaptureCompleted(capture);
256                        }
257                    }
258                    super.onCaptureCompleted(session, request, result);
259                }
260            };

最后

以上就是狂野缘分为你收集整理的Android camera 拍照 流程APP的全部内容,希望文章能够帮你解决Android camera 拍照 流程APP所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部