Android6.0 source code analysis: Capture process analysis under Camera API2.0, android6.0api2.0

Source: Internet
Author: User

Android6.0 source code analysis: Capture process analysis under Camera API2.0, android6.0api2.0

The initialization and preview processes of Camera2 are analyzed in detail. This article will analyze the capture process of Camera2.

 

When preview is analyzed in the previous section, after the preview is successful, ShutterButton can be taken, and the listener event of ShutterButton is located as the onShutterButtonClick method:

// CaptureModule. java @ Overridepublic void onShutterButtonClick () {// if (mCamera = null) {return;} int countDownDuration = mSettingsManager. getInteger (SettingsManager
. SCOPE_GLOBAL, Keys. KEY_COUNTDOWN_DURATION); if (countDownDuration> 0) {// start countdown mAppController. getCameraAppUI (). transitionToCancel (); mAppController. getCameraAppUI (). hideModeOptions (); mUI. setCountdownFinishedListener (this); mUI. startCountdown (countDownDuration); // Will take picture later via listener callback .} else {// take a photo now takePictureNow ();}}

First, read the Camera configuration to determine whether the configuration requires a delayed photograph. Here, we analyze the situations where no latency is required, that is, call the takePictureNow method:

// CaptureModule. javatevate void takePictureNow () {if (mCamera = null) {Log. I (TAG, "Not taking picture since Camera is closed. "); return;} // create a Capture session and enable the session CaptureSession session = createAndStartCaptureSession (); // obtain the direction int orientation = mAppController of Camera. getOrientationManager (). getDeviceOrientation (). getDegrees (); // initialize the Image Parameters. Here, this (CaptureModule) is the implementation of PictureCallback PhotoCaptureParameters params = new PhotoCaptureParameters (session. getTitle (), orientation, session. getLocation (), mContext. getExternalCacheDir (), this, mPictureSaverCallback, mHeadingSensor. getCurrentHeading (), mZoomValue, 0); // assemble Session decorateSessionAtCaptureTime (session); // take a photo of mCamera. takePicture (params, session );}

It first calls createAndStartCaptureSession to create a CaptureSession and start the session. Here, it also sets the initial parameters, for example, setting CaptureModule (here the real Parameter

This is the callback for image processing (which will be analyzed later ):

// CaptureModule. javatevate CaptureSession createAndStartCaptureSession () {// obtain the session time long sessionTime = getSessionTime (); // The current Location location Location = mLocationManager. getCurrentLocation (); // set picture name String title = CameraUtil. instance (). createJpegName (sessionTime); // creates a session CaptureSession session = getServices (). getCaptureSessionManager (). createNewSession (title, sessionTime, location); // enable session. startEmpty (new CaptureStats (mHdrPlusEnabled), new Size (int) mPreviewArea. width (), (int) mPreviewArea. height (); return session ;}

First, obtain the relevant parameters of the Session, including the Session time, the photo name and location information, and then call Session management to create a CaptureSession.

Start. Here, the session is created and started. Therefore, after analyzing the above photo process, it will call the takePicture method of OneCameraImpl to take a photo:

// OneCameraImpl. java @ Overridepublic void takePicture (final PhotoCaptureParameters params, final CaptureSession session ){... // broadcast an unprepared broadcast, that is, wait for the end of this photograph to broadcastReadyState (false); // create a thread mTakePictureRunnable = new Runnable () {@ Override public void run () {// take a photo of takePictureNow (params, session) ;}; // set the callback. This callback will be analyzed later. It is actually CaptureModule, it implements PictureCallback mLastPictureCallback = params. callback; mTakePictureStartMillis = SystemClock. uptimeMillis (); // if You Need to automatically focus on if (mLastResultAFState = AutoFocusState. ACTIVE_SCAN) {mTakePictureWhenLensIsStopped = true;} else {// take a photo of takePictureNow (params, session );}}

When taking a picture, first broadcast an unprepared status broadcast, then perform callback settings for the picture, and determine whether automatic focus exists. If so, set mTakePictureWhenLensIsStopped to true,

The image is immediately stopped; otherwise, the OneCameraImpl takePictureNow method is called to initiate a photo request:

// OneCameraImpl. javapublic void takePictureNow (PhotoCaptureParameters params, CaptureSession session) {long dt = SystemClock. uptimeMillis ()-mTakePictureStartMillis; try {// the request to create a JPEG image. builder builder = mDevice. createCaptureRequest (CameraDevice. TEMPLATE_STILL_CAPTURE); builder. setTag (RequestTag. CAPTURE); addBaselineCaptureKeysToRequest (builder); // Enable lens-shading correction for even better DNGs. if (sCaptureImageFormat = ImageFormat. RAW_SENSOR) {builder. set (CaptureRequest. STATISTICS_LENS_SHADING_MAP_MODE, CaptureRequest. STATISTICS_LENS_SHADING_MAP_MODE_ON);} else if (sCaptureImageFormat = ImageFormat. JPEG) {builder. set (CaptureRequest. required _quality, required _quality );. getJpegRotation (params. orientation, mCharacteristics);} // control builder for preview. addTarget (mPreviewSurface); // control builder used for image display. addTarget (mCaptureImageReader. getSurface (); CaptureRequest request = builder. build (); if (DEBUG_WRITE_CAPTURE_DATA) {final String debugDataDir = makeDebugDir (params. debugDataFolder, "normal_capture_debug"); Log. I (TAG, "Writing capture data to:" + debugDataDir); CaptureDataSerializer. toFile ("Normal Capture", request, new File (debugDataDir, "capture.txt");} // take a photo. mCaptureCallback indicates the callback mCaptureSession. capture (request, mCaptureCallback, mCameraHandler);} catch (CameraAccessException e) {Log. e (TAG, "cocould not access camera for still image capture. "); broadcastReadyState (true); params. callback. onPictureTakingFailed (); return;} synchronized (mCaptureQueue) {mCaptureQueue. add (new InFlightCapture (params, session ));}}

Similar to preview, CaptureRequest is used to communicate with Camera and take photos through session capture,

And set the callback function for the photo to mCaptureCallback:

//CameraCaptureSessionImpl.java@Overridepublic synchronized int capture(CaptureRequest request,CaptureCallback callback,Handler handler)throws CameraAccessException{    ...    handler = checkHandler(handler,callback);    return addPendingSequence(mDeviceImpl.capture(request,createCaptureCallbackProxy(handler,callback),mDeviceHandler));}

The code is similar to that in preview. Requests are added to the request set to be processed. Now let's look at the CaptureCallback callback:

// Response. javatevate final response. CaptureCallback mCaptureCallback = new response. CaptureCallback () {@ Override public void onCaptureStarted (reset session, CaptureRequest request, long timestamp, long frameNumber ){
// Similar to preview, if (request. getTag () = RequestTag. CAPTURE & mLastPictureCallback! = Null) {mLastPictureCallback. onQuickExpose ();}}... @ Override public void onCaptureCompleted (CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {autofocusStateChangeDispatcher (result); if (result. get (CaptureResult. CONTROL_AF_STATE) = null ){
// Check AutoFocusHelper. checkControlAfState (result );}... if (request. getTag () = RequestTag. CAPTURE) {synchronized (mCaptureQueue) {if (mCaptureQueue. getFirst (). setCaptureResult (result ). isCaptureComplete () {capture = mCaptureQueue. removeFirst () ;}} if (capture! = Null ){
// The OneCameraImpl. this. onCaptureCompleted (capture) ;}} super. onCaptureCompleted (session, request, result );}...}

This is the Native layer that calls the corresponding callback when processing the request. For example, the onCaptureStarted will be called back at the beginning of the capture. The specific analysis has been performed in the preview. When the photograph ends, the callback will be made.

The onCaptureCompleted method checks the status of automatic focus based on CaptureResult and determines whether it is the Capture action by TAG,

If yes, the request will be removed because the request has been processed successfully and the OneCameraImpl onCaptureCompleted method will be called for processing:

// OneCameraImpl. javatevate void onCaptureCompleted (InFlightCapture capture) {if (isCaptureImageFormat = ImageFormat. RAW_SENSOR ){... file dngFile = new File (RAW_DIRECTORY, capture. session. getTitle () + ". dng "); writeDngBytesAndClose (capture. image, capture. totalCaptureResult, mCharacteristics, dngFile);} else {// parse the image data in the result byte [] imageBytes = acquirejpegjpegbytesandclose (capture. image); // Save the Jpeg image saveJpegPicture (imageBytes, capture. parameters, capture. session, capture. totalCaptureResult);} broadcastReadyState (true); // call the callback capture. parameters. callback. onPictureTaken (capture. session );}

As shown in the code, first, parse the image data in the result, then call the saveJpegPicture method to save the parsed image data, and then call

The callback (CaptureModule, as described in the previous section during Parameters initialization, it implements the PictureCallbak Interface) of the onPictureTaken method. Therefore,

Next, analyze the saveJpegPicture method:

//OneCameraImpl.javaprivate void saveJpegPicture(byte[] jpegData,final PhotoCaptureParameters captureParams,CaptureSession session,CaptureResult result){    ...    ListenableFuture<Optional<Uri>> futureUri = session.saveAndFinish(jpegData,width,height,rotation,exif);    Futures.addCallback(futureUri,new FutureCallback<Optional<Uri>>(){        @Override        public void onSuccess(Optional<Uri> uriOptional){            captureParams.callback.onPictureSaved(mOptional.orNull());        }                @Override        public void onFailure(Throwable throwable){            captureParams.callback.onPictureSaved(null);        }    });}

It will call back the onPictureSaved method to save the image. Therefore, you need to analyze the onPictureSaved method of CaptureModule:

//CaptureModule.java@Overridepublic void onPictureSaved(Uri uri){    mAppController.notifyNewMedia(uri);}

MAppController is implemented as CameraActivity, so the notifyNewMedia method is analyzed as follows:

// CameraActivity. java @ Overridepublic void yynewmedia (Uri uri) {... if (FilmstripItemUtils. isMimeTypeVideo (mimeType )){
// If the video sendBroadcast (new Intent (CameraUtil. ACTION_NEW_VIDEO, uri); newData = mVideoItemFactory. queryContentUri (uri );...} else if (FilmstripItemUtils. isMimeTypeImage (mimeType )){
// If the image is CameraUtil. broadcastNewPicture (mAppContext, uri); newData = mPhotoItemFactory. queryCotentUri (uri );...} else {return;} new AsyncTask <FilmstripItem, Void, FilmstripItem> () {@ Override protected FilmstripItem doInBackground (FilmstripItem... params) {FilmstripItem data = params [0]; MetadataLoader. loadMetadata (getAndroidContet (), data); return data ;}...}}

The Code shows that there are two types of data processing: video and image. Here we analyze the capture image data.

The input parameter Uri and PhotoItemFactory can query the corresponding photo data, and then enable an asynchronous Task to process the data, that is, through the MetadataLoader's

LoadMetadata to load data and return it. At this point, the capture process is basically analyzed. The timing diagram of the whole process of the capture process is shown below:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.