/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.location.Location;
import android.media.CamcorderProfile;
import android.media.CameraProfile;
import android.media.MediaRecorder;
import android.media.AudioManager; // SPRD: add for audio focus related
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.KeyEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.camera.VideoUI;
import com.android.camera.CameraManager.CameraPictureCallback;
import com.android.camera.CameraManager.CameraProxy;
import com.android.camera.app.OrientationManager;
import com.android.camera.exif.ExifInterface;
import com.android.camera.ui.RotateTextToast;
import com.android.camera.util.AccessibilityUtils;
import com.android.camera.util.ApiHelper;
import com.android.camera.util.CameraUtil;
import com.android.camera.util.UsageStatistics;
import com.android.camera2.R;
import com.sprd.camera.AlertDialogPopup;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import android.os.HandlerThread;
import android.os.Environment;
public class VideoModule implements CameraModule,
VideoController,
CameraPreference.OnPreferenceChangedListener,
ShutterButton.OnShutterButtonListener,
MediaRecorder.OnErrorListener,
MediaRecorder.OnInfoListener {
private static final boolean DEBUG = true;
private static final String TAG = "CAM_VideoModule";
private static final int CHECK_DISPLAY_ROTATION = 3;
private static final int CLEAR_SCREEN_DELAY = 4;
private static final int UPDATE_RECORD_TIME = 5;
private static final int ENABLE_SHUTTER_BUTTON = 6;
private static final int SHOW_TAP_TO_SNAPSHOT_TOAST = 7;
private static final int SWITCH_CAMERA = 8;
private static final int SWITCH_CAMERA_START_ANIMATION = 9;
private static final int OPEN_CAMERA_FAIL = 10;
private static final int LOCK_CAMERA = 11;
private static final int CHECK_STORAGE_SPACE = 12;
private static final int SHOW_CONTROLS_UI = 13;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private static final int RECORD_LIMIT_TOAST_SHOW_TIME = 1000; //1s
private static final int RECORD_LIMIT_TIME = 3000; //3s
private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms
private static final long SHOW_CONTROLS_UI_TIMEOUT = 500L; // 500ms
private static final String EXTERNAL = "external";
/**
* An unpublished intent flag requesting to start recording straight away
* and return as soon as recording is stopped.
* TODO: consider publishing by moving into MediaStore.
*/
private static final String EXTRA_QUICK_CAPTURE =
"android.intent.extra.quickCapture";
// module fields
private CameraActivity mActivity;
private boolean mPaused;
private int mCameraId;
private Parameters mParameters;
private boolean mIsInReviewMode;
private boolean mSnapshotInProgress = false;
private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
private ComboPreferences mPreferences;
private PreferenceGroup mPreferenceGroup;
// Preference must be read before starting preview. We check this before starting
// preview.
private boolean mPreferenceRead;
private boolean mIsVideoCaptureIntent;
private boolean mQuickCapture;
private MediaRecorder mMediaRecorder;
private boolean mSwitchingCamera;
private boolean mMediaRecorderRecording = false;
private boolean mPauseRecorderRecording = false;
private long mPauseTime = 0;
private long mResumeTime = 0;
private long mResultTime = 0;
private long mRecordingStartTime;
private boolean mRecordingTimeCountsDown = false;
private long mOnResumeTime;
// The video file that the hardware camera is about to record into
// (or is recording into.)
private String mVideoFilename;
private ParcelFileDescriptor mVideoFileDescriptor;
// The video file that has already been recorded, and that is being
// examined by the user.
private String mCurrentVideoFilename;
private Uri mCurrentVideoUri;
private boolean mCurrentVideoUriFromMediaSaved;
private ContentValues mCurrentVideoValues;
private CamcorderProfile mProfile;
// The video duration limit. 0 menas no limit.
private int mMaxVideoDurationInMs;
// Time Lapse parameters.
private boolean mCaptureTimeLapse = false;
// Default 0. If it is larger than 0, the camcorder is in time lapse mode.
private int mTimeBetweenTimeLapseFrameCaptureMs = 0;
boolean mPreviewing = false; // True if preview is started.
// The display rotation in degrees. This is only valid when mPreviewing is
// true.
private int mDisplayRotation;
private int mCameraDisplayOrientation;
private int mDesiredPreviewWidth;
private int mDesiredPreviewHeight;
private ContentResolver mContentResolver;
private LocationManager mLocationManager;
private OrientationManager mOrientationManager;
private int mPendingSwitchCameraId;
private final Handler mHandler = new MainHandler();
private VideoUI mUI;
private CameraProxy mCameraDevice;
// SPRD: save the state of Module switch view's visibility
private int mModuleViewVisibility;
// The degrees of the device rotated clockwise from its natural orientation.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private int mZoomValue; // The current zoom value.
private Toast mToastFM;
private final MediaSaveService.OnMediaSavedListener mOnVideoSavedListener =
new MediaSaveService.OnMediaSavedListener() {
@Override
public void onMediaSaved(Uri uri) {
if (uri != null) {
mCurrentVideoUri = uri;
mCurrentVideoUriFromMediaSaved = true;
onVideoSaved();
mActivity.notifyNewMedia(uri);
}
}
};
private final MediaSaveService.OnMediaSavedListener mOnPhotoSavedListener =
new MediaSaveService.OnMediaSavedListener() {
@Override
public void onMediaSaved(Uri uri) {
if (uri != null) {
mActivity.notifyNewMedia(uri);
}
}
};
protected class CameraOpenThread extends Thread {
@Override
public void run() {
openCamera();
}
}
private void openCamera() {
if (mCameraDevice == null) {
mCameraDevice = CameraUtil.openCamera(
mActivity, mCameraId, mHandler,
mActivity.getCameraOpenErrorCallback());
}
if (mCameraDevice == null) {
// Error.
mHandler.sendEmptyMessage(OPEN_CAMERA_FAIL);
return;
}
mParameters = mCameraDevice.getParameters();
}
// This Handler is used to post message back onto the main thread of the
// application
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ENABLE_SHUTTER_BUTTON:
mUI.enableShutter(true);
break;
case CLEAR_SCREEN_DELAY: {
mActivity.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case UPDATE_RECORD_TIME: {
updateRecordingTime();
break;
}
case SHOW_CONTROLS_UI: {
if (!mMediaRecorderRecording) {
mUI.showControlsUI();
}
break;
}
case CHECK_DISPLAY_ROTATION: {
// Restart the preview if display rotation has changed.
// Sometimes this happens when the device is held upside
// down and camera app is opened. Rotation animation will
// take some time and the rotation value we have got may be
// wrong. Framework does not have a callback for this now.
if ((CameraUtil.getDisplayRotation(mActivity) != mDisplayRotation)
&& !mMediaRecorderRecording && !mSwitchingCamera) {
startPreview();
}
if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
break;
}
case SHOW_TAP_TO_SNAPSHOT_TOAST: {
showTapToSnapshotToast();
break;
}
case SWITCH_CAMERA: {
switchCamera();
break;
}
case SWITCH_CAMERA_START_ANIMATION: {
//TODO:
//((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
// Enable all camera controls.
mSwitchingCamera = false;
break;
}
case OPEN_CAMERA_FAIL: {
/* SPRD :add VideoCall check toast @{ */
if (mActivity.checkTelephoneVideoCall()) {
CameraUtil.showErrorAndFinish(mActivity,
R.string.in_video_call_is_running);
} else {
CameraUtil.showErrorAndFinish(mActivity,
R.string.cannot_connect_camera);
}
/* }@ */
break;
}
/** SPRD: fixbug258798 add lockCamera after Recoder stop finish @{ */
case LOCK_CAMERA: {
lockCamera();
/** @} */
}
break;
// SPRD: check storage space
case CHECK_STORAGE_SPACE: {
if (mActivity != null) {
mActivity.updateStorageSpaceAndHint();
}
}
break;
default:
Log.v(TAG, "Unhandled message: " + msg.what);
break;
}
}
}
private BroadcastReceiver mReceiver = null;
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
/** SPRD: fixbug258798 add stopVideoRecording handle while remove SD card @{
* @orig:
* stopVideoRecording();
* @} */
String externalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String absoluteFilePath = EXTERNAL + mVideoFilename;
boolean isExternalFilePath = absoluteFilePath.contains(externalPath);
if (mMediaRecorderRecording && mVideoFilename != null&& isExternalFilePath) {
Toast.makeText(mActivity,
mActivity.getResources().getString(R.string.sdcard_remove), Toast.LENGTH_LONG).show();
stopVideoRecordingOnSdCardRemoved();
}
/** @} */
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
Toast.makeText(mActivity,
mActivity.getResources().getString(R.string.wait), Toast.LENGTH_LONG).show();
}
}
}
private String createName(long dateTaken) {
Date date = new Date(dateTaken);
SimpleDateFormat dateFormat = new SimpleDateFormat(
mActivity.getString(R.string.video_file_name_format));
return dateFormat.format(date);
}
private int getPreferredCameraId(ComboPreferences preferences) {
int intentCameraId = CameraUtil.getCameraFacingIntentExtras(mActivity);
if (intentCameraId != -1) {
// Testing purpose. Launch a specific camera through the intent
// extras.
return intentCameraId;
} else {
return CameraSettings.readPreferredCameraId(preferences);
}
}
private void initializeSurfaceView() {
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { // API level < 16
mUI.initializeSurfaceView();
}
}
@Override
public void init(CameraActivity activity, View root) {
mActivity = activity;
mUI = new VideoUI(activity, this, root);
mPreferences = new ComboPreferences(mActivity);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = getPreferredCameraId(mPreferences);
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
mOrientationManager = new OrientationManager(mActivity);
/*
* To reduce startup time, we start the preview in another thread.
* We make sure the preview is started at the end of onCreate.
*/
CameraOpenThread cameraOpenThread = new CameraOpenThread();
cameraOpenThread.start();
mContentResolver = mActivity.getContentResolver();
// Surface texture is from camera screen nail and startPreview needs it.
// This must be done before startPreview.
mIsVideoCaptureIntent = isVideoCaptureIntent();
// SPRD: bug 259245 save the visibility of the Module switch view
mModuleViewVisibility = (mIsVideoCaptureIntent)?View.INVISIBLE:
View.VISIBLE;
// @{ SPRD: bug 258455 begin
if (mIsVideoCaptureIntent)
mActivity.setModuleVisble(View.INVISIBLE);
// SPRD: bug 258455 end @}
initializeSurfaceView();
// Make sure camera device is opened.
try {
cameraOpenThread.join();
if (mCameraDevice == null) {
return;
}
} catch (InterruptedException ex) {
// ignore
}
readVideoPreferences();
mUI.setPrefChangedListener(this);
mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
mLocationManager = new LocationManager(mActivity, null);
mUI.setOrientationIndicator(0, false);
setDisplayOrientation();
mUI.showTimeLapseUI(mCaptureTimeLapse);
initializeVideoSnapshot();
resizeForPreviewAspectRatio();
initializeVideoControl();
mPendingSwitchCameraId = -1;
}
// SingleTapListener
// Preview area is touched. Take a picture.
@Override
public void onSingleTapUp(View view, int x, int y) {
takeASnapshot();
}
public void onVideoCaptureShutterButtonClick() {
Log.e(TAG,"onVideoCaptureShutterButtonClick");
takeASnapshot();
}
private void takeASnapshot() {
// Only take snapshots if video snapshot is supported by device
//SPRD: Bug 268655 NullPointerException
if (mParameters != null && CameraUtil.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
Log.v(TAG, "takeASnapshot isVideoSnapshotSupported="+CameraUtil.isVideoSnapshotSupported(mParameters));
if (!mMediaRecorderRecording || mPaused || mSnapshotInProgress) {
return;
}
MediaSaveService s = mActivity.getMediaSaveService();
if (s == null || s.isQueueFull()) {
return;
}
// Set rotation and gps data.
int rotation = CameraUtil.getJpegRotation(mCameraId, mOrientation);
mParameters.setRotation(rotation);
Location loc = mLocationManager.getCurrentLocation();
CameraUtil.setGpsParameters(mParameters, loc);
mCameraDevice.setParameters(mParameters);
Log.v(TAG, "Video snapshot start");
mCameraDevice.takePicture(mHandler,
null, null, null, new JpegPictureCallback(loc));
showVideoSnapshotUI(true);
mSnapshotInProgress = true;
UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
UsageStatistics.ACTION_CAPTURE_DONE, "VideoSnapshot");
}
}
@Override
public void onStop() {}
private void loadCameraPreferences() {
CameraSettings settings = new CameraSettings(mActivity, mParameters,
mCameraId, CameraHolder.instance().getCameraInfo());
// Remove the video quality preference setting when the quality is given in the intent.
mPreferenceGroup = filterPreferenceScreenByIntent(
settings.getPreferenceGroup(R.xml.video_preferences));
}
private void initializeVideoControl() {
loadCameraPreferences();
mUI.initializePopup(mPreferenceGroup);
mUI.updateControlsTop(mPreferenceGroup);
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
int newOrientation = CameraUtil.roundOrientation(orientation, mOrientation);
if (mOrientation != newOrientation) {
mOrientation = newOrientation;
}
// Show the toast after getting the first orientation changed.
if (mHandler.hasMessages(SHOW_TAP_TO_SNAPSHOT_TOAST)) {
mHandler.removeMessages(SHOW_TAP_TO_SNAPSHOT_TOAST);
showTapToSnapshotToast();
}
}
private void startPlayVideoActivity() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat));
try {
mActivity
.startActivityForResult(intent, CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW);
} catch (ActivityNotFoundException ex) {
Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex);
}
}
@Override
@OnClickAttr
public void onReviewPlayClicked(View v) {
startPlayVideoActivity();
}
@Override
@OnClickAttr
public void onReviewDoneClicked(View v) {
mIsInReviewMode = false;
doReturnToCaller(true);
}
@Override
@OnClickAttr
public void onReviewCancelClicked(View v) {
// TODO: It should be better to not even insert the URI at all before we
// confirm done in review, which means we need to handle temporary video
// files in a quite different way than we currently had.
// Make sure we don't delete the Uri sent from the video capture intent.
if (mCurrentVideoUriFromMediaSaved) {
mContentResolver.delete(mCurrentVideoUri, null, null);
}
mIsInReviewMode = false;
doReturnToCaller(false);
}
/* SPRD: add retake feature in a video capture intent @{ */
@Override
@OnClickAttr
public void onReviewRetakeClicked(View v) {
if (mCurrentVideoUriFromMediaSaved) {
mContentResolver.delete(mCurrentVideoUri, null, null);
}
mIsInReviewMode = false;
mUI.hidePostCaptureAlert();
mUI.updateControlsTop(mPreferenceGroup);
mUI.enableCameraControls(true);
}
/* @} */
@Override
public boolean isInReviewMode() {
return mIsInReviewMode;
}
private void onStopVideoRecording() {
// SPRD: set module switch view display when stopVideoRecording
showSwitcher();
showControls();
boolean recordFail = stopVideoRecording();
if (mIsVideoCaptureIntent) {
if (mQuickCapture) {
doReturnToCaller(!recordFail);
} else if (!recordFail) {
if (mActivity.getIntent().hasExtra(MediaStore.EXTRA_OUTPUT)) {
showCaptureResult();
} else {
showCaptureResultNoThumbnail();
}
} else if (recordFail) {
mHandler.sendEmptyMessageDelayed(
ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT);
}
} else if (!recordFail){
// Start capture animation.
if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
// The capture animation is disabled on ICS because we use SurfaceView
// for preview during recording. When the recording is done, we switch
// back to use SurfaceTexture for preview and we need to stop then start
// the preview. This will cause the preview flicker since the preview
// will not be continuous for a short period of time.
// SPRD: remove animation from customer requirement
// mUI.animateFlash();
mUI.animateCapture();
}
}
}
public void onVideoSaved() {
if (mIsVideoCaptureIntent) {
showCaptureResult();
}
}
public void onProtectiveCurtainClick(View v) {
// Consume clicks
}
@Override
public void onShutterButtonClick() {
if (mUI.collapseCameraControls() || mSwitchingCamera) return;
// SPRD: When not start preview, so current click event ignore
Log.d(TAG, "onShutterButtonClick mPreviewing=" + mPreviewing);
if (!mPreviewing) return;
boolean stop = mMediaRecorderRecording;
if (stop) {
long timePasedAfterRecording = SystemClock.uptimeMillis() - mRecordingStartTime;
Log.d(TAG, "time passed after recording started: " + timePasedAfterRecording);
if (timePasedAfterRecording < RECORD_LIMIT_TIME) {
new RotateTextToast(
mActivity, R.string.notice_record_time_too_short, 0).show(RECORD_LIMIT_TOAST_SHOW_TIME);
return;
} else {
onStopVideoRecording();
}
} else {
// fixed bug 264715 start
if (mActivity.proxyIsAudioRecording()) {
if (mToastFM == null) {
mToastFM =
Toast.makeText(
mActivity,
mActivity.getString(R.string.in_fm_mediarecoder_is_running),
Toast.LENGTH_SHORT);
}
mToastFM.show();
return;
}
// fixed bug 264715 end
startVideoRecording();
}
mUI.enableShutter(false);
// Keep the shutter button disabled when in video capture intent
// mode and recording is stopped. It'll be re-enabled when
// re-take button is clicked.
if (!(mIsVideoCaptureIntent && stop)) {
mHandler.sendEmptyMessageDelayed(
ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT);
}
}
@Override
public void onShutterButtonFocus(boolean pressed) {
mUI.setShutterPressed(pressed);
}
private void readVideoPreferences() {
// The preference stores values from ListPreference and is thus string type for all values.
// We need to convert it to int manually.
String defaultVideoQuality =
mActivity.getResources().getString(R.string.pref_video_quality_default);
String videoQuality =
mPreferences.getString(CameraSettings.KEY_VIDEO_QUALITY, defaultVideoQuality);
if (videoQuality == null) {
// check for highest quality before setting default value
videoQuality =
CameraSettings.getSupportedHighestVideoQuality(mCameraId, defaultVideoQuality);
mPreferences.edit().putString(CameraSettings.KEY_VIDEO_QUALITY, videoQuality);
}
int quality = Integer.valueOf(videoQuality);
Log.d(TAG, "readVideoPreferences video quality=" + quality);
// Set video quality.
Intent intent = mActivity.getIntent();
if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
int extraVideoQuality =
intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
if (extraVideoQuality > 0) {
quality = CamcorderProfile.QUALITY_HIGH;
} else { // 0 is mms.
quality = CamcorderProfile.QUALITY_LOW;
}
}
// Set video duration limit. The limit is read from the preference,
// unless it is specified in the intent.
if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
int seconds =
intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0);
mMaxVideoDurationInMs = 1000 * seconds;
} else {
mMaxVideoDurationInMs = CameraSettings.getMaxVideoDuration(mActivity);
}
// Read time lapse recording interval.
String frameIntervalStr = mPreferences.getString(
CameraSettings.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL,
mActivity.getString(R.string.pref_video_time_lapse_frame_interval_default));
mTimeBetweenTimeLapseFrameCaptureMs = Integer.parseInt(frameIntervalStr);
mCaptureTimeLapse = (mTimeBetweenTimeLapseFrameCaptureMs != 0);
// TODO: This should be checked instead directly +1000.
if (mCaptureTimeLapse) quality += 1000;
mProfile = CamcorderProfile.get(mCameraId, quality);
getDesiredPreviewSize();
mPreferenceRead = true;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void getDesiredPreviewSize() {
if (mCameraDevice == null) {
return;
}
mParameters = mCameraDevice.getParameters();
if (mParameters.getSupportedVideoSizes() == null) {
mDesiredPreviewWidth = mProfile.videoFrameWidth;
mDesiredPreviewHeight = mProfile.videoFrameHeight;
} else { // Driver supports separates outputs for preview and video.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size preferred = mParameters.getPreferredPreviewSizeForVideo();
int product = preferred.width * preferred.height;
Iterator<Size> it = sizes.iterator();
// Remove the preview sizes that are not preferred.
while (it.hasNext()) {
Size size = it.next();
if (size.width * size.height > product) {
it.remove();
}
}
Size optimalSize = CameraUtil.getOptimalPreviewSize(mActivity, sizes,
(double) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
mDesiredPreviewWidth = optimalSize.width;
mDesiredPreviewHeight = optimalSize.height;
}
mUI.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
Log.v(TAG, "mDesiredPreviewWidth=" + mDesiredPreviewWidth +
". mDesiredPreviewHeight=" + mDesiredPreviewHeight);
}
private void resizeForPreviewAspectRatio() {
mUI.setAspectRatio(
(double) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
}
@Override
public void installIntentFilter() {
// install an intent filter to receive SD card related events.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_MEDIA_EJECT);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter.addDataScheme("file");
mReceiver = new MyBroadcastReceiver();
mActivity.registerReceiver(mReceiver, intentFilter);
}
@Override
public void onResumeBeforeSuper() {
mPaused = false;
}
@Override
public void onResumeAfterSuper() {
mUI.enableShutter(false);
mZoomValue = 0;
showVideoSnapshotUI(false);
if (!mPreviewing) {
openCamera();
if (mCameraDevice == null) {
return;
}
readVideoPreferences();
resizeForPreviewAspectRatio();
startPreview();
} else {
// preview already started
mUI.enableShutter(true);
}
mUI.initDisplayChangeListener();
// Initializing it here after the preview is started.
mUI.initializeZoom(mParameters);
keepScreenOnAwhile();
mUI.hidePreviewCover();
mOrientationManager.resume();
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(mPreferences,
mContentResolver);
mLocationManager.recordLocation(recordLocation);
if (mPreviewing) {
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
if (/*mPreviewing && */mHandler != null) {
mHandler.sendEmptyMessage(CHECK_STORAGE_SPACE);
}
/** SPRD: update timeLapseUI in onResume. fixed 276313 @{ */
mUI.showTimeLapseUI(mCaptureTimeLapse);
/** @} */
UsageStatistics.onContentViewChanged(
UsageStatistics.COMPONENT_CAMERA, "VideoModule");
/** SPRD: Add Register for BroadcastReceiver in onResume @{ */
installIntentFilter();
/** @} */
}
private void setDisplayOrientation() {
mDisplayRotation = CameraUtil.getDisplayRotation(mActivity);
mCameraDisplayOrientation = CameraUtil.getDisplayOrientation(mDisplayRotation, mCameraId);
// Change the camera display orientation
if (mCameraDevice != null) {
mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
}
}
@Override
public void updateCameraOrientation() {
if (mMediaRecorderRecording) return;
if (mDisplayRotation != CameraUtil.getDisplayRotation(mActivity)) {
setDisplayOrientation();
}
}
@Override
public int onZoomChanged(int index) {
// Not useful to change zoom value when the activity is paused.
if (mPaused) return index;
mZoomValue = index;
if (mParameters == null || mCameraDevice == null) return index;
// Set zoom parameters asynchronously
mParameters.setZoom(mZoomValue);
mCameraDevice.setParameters(mParameters);
Parameters p = mCameraDevice.getParameters();
if (p != null) return p.getZoom();
return index;
}
private void startPreview() {
Log.v(TAG, "startPreview");
SurfaceTexture surfaceTexture = mUI.getSurfaceTexture();
if (!mPreferenceRead || surfaceTexture == null || mPaused == true ||
mCameraDevice == null) {
return;
}
mCameraDevice.setErrorCallback(mErrorCallback);
if (mPreviewing == true) {
stopPreview();
}
setDisplayOrientation();
mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
setCameraParameters();
try {
mCameraDevice.setPreviewTexture(surfaceTexture);
mCameraDevice.startPreview();
mPreviewing = true;
onPreviewStarted();
} catch (Throwable ex) {
closeCamera();
throw new RuntimeException("startPreview failed", ex);
}
if (mActivity.isAutoCapture()){
mHandler.post(new Runnable() {
@Override
public void run() {
onShutterButtonClick();
}
});
}
}
private void onPreviewStarted() {
mUI.enableShutter(true);
}
@Override
public void stopPreview() {
if (!mPreviewing) return;
mCameraDevice.stopPreview();
mPreviewing = false;
}
private void closeCamera() {
Log.v(TAG, "closeCamera");
if (mCameraDevice == null) {
Log.d(TAG, "already stopped.");
return;
}
mCameraDevice.setZoomChangeListener(null);
mCameraDevice.setErrorCallback(null);
CameraHolder.instance().release();
mCameraDevice = null;
mPreviewing = false;
mSnapshotInProgress = false;
}
private void releasePreviewResources() {
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
mUI.hideSurfaceView();
}
}
@Override
public void onPauseBeforeSuper() {
mPaused = true;
// SPRD: Disable preview cover for preformance.
// mUI.showPreviewCover();
// fixed bug 255422 start
// if we can release camera hardware, so we must release toast object
if (mToastFM != null) {
mToastFM.cancel();
mToastFM = null;
}
// fixed bug 255422 end
if (mMediaRecorderRecording) {
// Camera will be released in onStopVideoRecording.
onStopVideoRecording();
} else {
closeCamera();
releaseMediaRecorder();
}
closeVideoFileDescriptor();
releasePreviewResources();
if (mReceiver != null) {
mActivity.unregisterReceiver(mReceiver);
mReceiver = null;
}
resetScreenOn();
if (mLocationManager != null) mLocationManager.recordLocation(false);
mOrientationManager.pause();
mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
mHandler.removeMessages(SWITCH_CAMERA);
mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
mPendingSwitchCameraId = -1;
mSwitchingCamera = false;
mPreferenceRead = false;
mUI.collapseCameraControls();
mUI.removeDisplayChangeListener();
}
@Override
public void onPauseAfterSuper() {
}
@Override
public void onUserInteraction() {
if (!mMediaRecorderRecording && !mActivity.isFinishing()) {
keepScreenOnAwhile();
}
}
@Override
public boolean onBackPressed() {
if (mPaused) return true;
if (mMediaRecorderRecording) {
long timePasedAfterRecording = SystemClock.uptimeMillis() - mRecordingStartTime;
Log.d(TAG, "onBackPressed time passed after recording started: " + timePasedAfterRecording);
if (timePasedAfterRecording < RECORD_LIMIT_TIME) {
new RotateTextToast(
mActivity, R.string.notice_record_time_too_short, 0).show(RECORD_LIMIT_TOAST_SHOW_TIME);
return true;
} else {
onStopVideoRecording();
}
return true;
} else if (mUI.hidePieRenderer()) {
return true;
} else {
return mUI.removeTopLevelPopup();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Do not handle any key if the activity is paused.
if (mPaused) {
return true;
}
switch (keyCode) {
case KeyEvent.KEYCODE_CAMERA:
if (event.getRepeatCount() == 0) {
mUI.clickShutter();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (event.getRepeatCount() == 0) {
mUI.clickShutter();
return true;
}
break;
case KeyEvent.KEYCODE_MENU:
if (mMediaRecorderRecording) return true;
break;
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_CAMERA:
mUI.pressShutter(false);
return true;
}
return false;
}
@Override
public boolean isVideoCaptureIntent() {
Intent intent = mActivity.getIntent();
String action = intent.getAction();
mActivity.checkIntent(intent);
return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action));
}
private void doReturnToCaller(boolean valid) {
Intent resultIntent = new Intent();
int resultCode;
if (valid) {
resultCode = Activity.RESULT_OK;
resultIntent.setData(mCurrentVideoUri);
} else {
resultCode = Activity.RESULT_CANCELED;
}
mActivity.setResultEx(resultCode, resultIntent);
mActivity.finish();
}
private void cleanupEmptyFile() {
if (mVideoFilename != null) {
File f = new File(mVideoFilename);
if (f.length() == 0 && f.delete()) {
Log.v(TAG, "Empty video file deleted: " + mVideoFilename);
mVideoFilename = null;
}
}
}
private void setupMediaRecorderPreviewDisplay() {
// Nothing to do here if using SurfaceTexture.
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
// We stop the preview here before unlocking the device because we
// need to change the SurfaceTexture to SurfaceView for preview.
stopPreview();
mCameraDevice.setPreviewDisplay(mUI.getSurfaceHolder());
// The orientation for SurfaceTexture is different from that for
// SurfaceView. For SurfaceTexture we don't need to consider the
// display rotation. Just consider the sensor's orientation and we
// will set the orientation correctly when showing the texture.
// Gallery will handle the orientation for the preview. For
// SurfaceView we will have to take everything into account so the
// display rotation is considered.
mCameraDevice.setDisplayOrientation(
CameraUtil.getDisplayOrientation(mDisplayRotation, mCameraId));
mCameraDevice.startPreview();
mPreviewing = true;
mMediaRecorder.setPreviewDisplay(mUI.getSurfaceHolder().getSurface());
}
}
// Prepares media recorder.
private void initializeRecorder() {
Log.v(TAG, "initializeRecorder");
// If the mCameraDevice is null, then this activity is going to finish
if (mCameraDevice == null) return;
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
// Set the SurfaceView to visible so the surface gets created.
// surfaceCreated() is called immediately when the visibility is
// changed to visible. Thus, mSurfaceViewReady should become true
// right after calling setVisibility().
mUI.showSurfaceView();
}
Intent intent = mActivity.getIntent();
Bundle myExtras = intent.getExtras();
long requestedSizeLimit = 0;
closeVideoFileDescriptor();
mCurrentVideoUriFromMediaSaved = false;
if (mIsVideoCaptureIntent && myExtras != null) {
Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
if (saveUri != null) {
try {
mVideoFileDescriptor =
mContentResolver.openFileDescriptor(saveUri, "rw");
mCurrentVideoUri = saveUri;
} catch (java.io.FileNotFoundException ex) {
// invalid uri
Log.e(TAG, ex.toString());
}
}
requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
}
// SPRD: fixed bug 259418 start
int bit64flag = CameraSettings.NOT_FOUND;
if (mPreferences != null) {
String video_quality = mPreferences.getString(CameraSettings.KEY_VIDEO_QUALITY, null);
if (video_quality != null) {
int quality_level = Integer.parseInt(video_quality);
switch (quality_level) {
case CamcorderProfile.QUALITY_720P:
case CamcorderProfile.QUALITY_1080P:
bit64flag = CameraSettings.VALUE_INT_ON;
break;
default :
bit64flag = CameraSettings.VALUE_INT_OFF;
break;
}
}
}
if (CameraSettings.NOT_FOUND == bit64flag) {
bit64flag = CameraSettings.VALUE_INT_OFF;
}
// SPRD: fixed bug 259418 end
// fixed bug 179430 start
String str_encode_type =
mPreferences.getString(
CameraSettings.KEY_VIDEO_ENCODE_TYPE,
mActivity.getString(R.string.pref_video_encode_type_entry_value_h264));
int encodeType = MediaRecorder.VideoEncoder.H264; // default encode type is h264
if (CameraSettings.VAL_VIDEO_ENCODE_TYPE_H264.equals(str_encode_type)) {
encodeType = MediaRecorder.VideoEncoder.H264;
} else if (CameraSettings.VAL_VIDEO_ENCODE_TYPE_MPEG.equals(str_encode_type)) {
encodeType = MediaRecorder.VideoEncoder.MPEG_4_SP;
}
// fixed bug 179430 end
mMediaRecorder = new MediaRecorder();
setupMediaRecorderPreviewDisplay();
// Unlock the camera object before passing it to media recorder.
mCameraDevice.unlock();
mMediaRecorder.setCamera(mCameraDevice.getCamera());
// fixed bug 188360 start
// when we open the slow motion , there will be no sound recording.
if (!mCaptureTimeLapse) {
mMediaRecorder.setAudioSource(CameraSettings.getRecorderAudioSoruceBySlowMotion(mPreferences));
}
// fixed bug 188360 end
Log.v(TAG, "mMediaRecorder initializeRecorder start ......");
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// fixed bug 179430 start
// set video encode type
mProfile.videoCodec = encodeType;
// fixed bug 179430 end
mMediaRecorder.setProfile(mProfile);
mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs);
if (mCaptureTimeLapse) {
double fps = 1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs;
setCaptureRate(mMediaRecorder, fps);
}
// SPRD: fixed bug 259418 start
// set parameter 64bit file offset, 0 is off, 1 is on
//mMediaRecorder.setParam64BitFileOffset(bit64flag);
// SPRD: fixed bug 259418 end
setRecordLocation();
Log.v(TAG, "mMediaRecorder initializeRecorder end");
// Set output file.
// Try Uri in the intent first. If it doesn't exist, use our own
// instead.
if (mVideoFileDescriptor != null) {
mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
} else {
generateVideoFilename(mProfile.fileFormat);
mMediaRecorder.setOutputFile(mVideoFilename);
}
// Set maximum file size.
long maxFileSize = mActivity.getStorageSpaceBytes() - Storage.LOW_STORAGE_THRESHOLD_BYTES;
if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
maxFileSize = requestedSizeLimit;
}
try {
mMediaRecorder.setMaxFileSize(maxFileSize);
} catch (RuntimeException exception) {
// We are going to ignore failure of setMaxFileSize here, as
// a) The composer selected may simply not support it, or
// b) The underlying media framework may not handle 64-bit range
// on the size restriction.
}
// See android.hardware.Camera.Parameters.setRotation for
// documentation.
// Note that mOrientation here is the device orientation, which is the opposite of
// what activity.getWindowManager().getDefaultDisplay().getRotation() would return,
// which is the orientation the graphics need to rotate in order to render correctly.
int rotation = 0;
if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - mOrientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + mOrientation) % 360;
}
}
mMediaRecorder.setOrientationHint(rotation);
try {
mMediaRecorder.prepare();
} catch (IOException e) {
Log.e(TAG, "prepare failed for " + mVideoFilename, e);
releaseMediaRecorder();
throw new RuntimeException(e);
}
mMediaRecorder.setOnErrorListener(this);
mMediaRecorder.setOnInfoListener(this);
}
private static void setCaptureRate(MediaRecorder recorder, double fps) {
recorder.setCaptureRate(fps);
}
private void setRecordLocation() {
Location loc = mLocationManager.getCurrentLocation();
if (loc != null) {
mMediaRecorder.setLocation((float) loc.getLatitude(),
(float) loc.getLongitude());
}
}
private void releaseMediaRecorder() {
Log.v(TAG, "Releasing media recorder.");
if (mMediaRecorder != null) {
cleanupEmptyFile();
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
}
mVideoFilename = null;
}
private void generateVideoFilename(int outputFileFormat) {
long dateTaken = System.currentTimeMillis();
String title = createName(dateTaken);
// Used when emailing.
String filename = title + convertOutputFormatToFileExt(outputFileFormat);
String mime = convertOutputFormatToMimeType(outputFileFormat);
StorageUtil util = StorageUtil.newInstance();
String directory = util.getStorageByMode(CameraUtil.MODE_VIDEO);
// String path = Storage.DIRECTORY + '/' + filename;
String path = directory + '/' + filename;
String tmpPath = path + ".tmp";
mCurrentVideoValues = new ContentValues(9);
mCurrentVideoValues.put(Video.Media.TITLE, title);
mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename);
mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken);
mCurrentVideoValues.put(MediaColumns.DATE_MODIFIED, dateTaken / 1000);
mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime);
mCurrentVideoValues.put(Video.Media.DATA, path);
mCurrentVideoValues.put(Video.Media.RESOLUTION,
Integer.toString(mProfile.videoFrameWidth) + "x" +
Integer.toString(mProfile.videoFrameHeight));
Location loc = mLocationManager.getCurrentLocation();
if (loc != null) {
mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude());
mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude());
}
mVideoFilename = tmpPath;
Log.v(TAG, "New video filename: " + mVideoFilename);
}
private void saveVideo() {
if (mVideoFileDescriptor == null) {
calculatePauseDuration(mPauseRecorderRecording);
long duration =
(SystemClock.uptimeMillis() - mRecordingStartTime - mResultTime);
if (duration > 0) {
if (mCaptureTimeLapse) {
duration = getTimeLapseVideoLength(duration);
}
} else {
Log.w(TAG, "Video duration <= 0 : " + duration);
}
mActivity.getMediaSaveService().addVideo(mCurrentVideoFilename,
duration, mCurrentVideoValues,
mOnVideoSavedListener, mContentResolver);
}
mCurrentVideoValues = null;
}
private void deleteVideoFile(String fileName) {
Log.v(TAG, "Deleting video " + fileName);
File f = new File(fileName);
if (!f.delete()) {
Log.v(TAG, "Could not delete " + fileName);
}
}
private PreferenceGroup filterPreferenceScreenByIntent(
PreferenceGroup screen) {
Intent intent = mActivity.getIntent();
if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
CameraSettings.removePreferenceFromScreen(screen,
CameraSettings.KEY_VIDEO_QUALITY);
}
if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
CameraSettings.removePreferenceFromScreen(screen,
CameraSettings.KEY_VIDEO_QUALITY);
}
return screen;
}
// from MediaRecorder.OnErrorListener
@Override
public void onError(MediaRecorder mr, int what, int extra) {
Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra);
if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
// We may have run out of space on the sdcard.
stopVideoRecording();
mActivity.updateStorageSpaceAndHint();
}
}
// from MediaRecorder.OnInfoListener
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
if (mMediaRecorderRecording) onStopVideoRecording();
} else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
if (mMediaRecorderRecording) onStopVideoRecording();
// Show the toast.
Toast.makeText(mActivity, R.string.video_reach_size_limit,
Toast.LENGTH_LONG).show();
}
}
/*
* Make sure we're not recording music playing in the background, ask the
* MediaPlaybackService to pause playback.
*/
private void pauseAudioPlayback() {
// Shamelessly copied from MediaPlaybackService.java, which
// should be public, but isn't.
/* @orig
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mActivity.sendBroadcast(i);
*/
/* SPRD: fix bug 255700, get audio focus @{ */
AudioManager audioManager = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
/* @} */
}
/* SPRD: fix bug 255700, release audio focus @{ */
private void abandonAudioPlayback() {
AudioManager audioManager = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE);
audioManager.abandonAudioFocus(null);
}
/* @} */
// For testing.
public boolean isRecording() {
return mMediaRecorderRecording;
}
private void startVideoRecording() {
Log.v(TAG, "startVideoRecording isVideoSnapshotSupported="+CameraUtil.isVideoSnapshotSupported(mParameters));
mActivity.updateStorageSpaceAndHint();
if (mActivity.getStorageSpaceBytes() <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
Log.v(TAG, "Storage issue, ignore the start request");
return;
}
// SPRD: set module switch view Invisibility when startVideoRecording
hideSwitcher();
hideControls();
if (!mIsVideoCaptureIntent && CameraUtil.isVideoSnapshotSupported(mParameters)) {
mUI.showVideoCaptureIcon(true);
}
mUI.cancelAnimations();
mUI.setSwipingEnabled(false);
//??
//if (!mCameraDevice.waitDone()) return;
mCurrentVideoUri = null;
initializeRecorder();
if (mMediaRecorder == null) {
Log.e(TAG, "Fail to initialize media recorder");
return;
}
pauseAudioPlayback();
long stime = System.currentTimeMillis();
try {
Log.v(TAG, "mMediaRecorder start ...... starttime=" + stime);
mMediaRecorder.start(); // Recording is now started
Log.v(TAG,
"mMediaRecorder start ...... endtime = "
+ (System.currentTimeMillis() - stime));
} catch (RuntimeException e) {
Log.e(TAG, "Could not start media recorder. ", e);
releaseMediaRecorder();
// If start fails, frameworks will not lock the camera for us.
mCameraDevice.lock();
return;
}
// Make sure the video recording has started before announcing
// this in accessibility.
AccessibilityUtils.makeAnnouncement(mUI.getShutterButton(),
mActivity.getString(R.string.video_recording_started));
// The parameters might have been altered by MediaRecorder already.
// We need to force mCameraDevice to refresh before getting it.
mCameraDevice.refreshParameters();
// The parameters may have been changed by MediaRecorder upon starting
// recording. We need to alter the parameters if we support camcorder
// zoom. To reduce latency when setting the parameters during zoom, we
// update mParameters here once.
mParameters = mCameraDevice.getParameters();
mResultTime = 0;
mUI.enableCameraControls(false);
mMediaRecorderRecording = true;
mOrientationManager.lockOrientation();
mRecordingStartTime = SystemClock.uptimeMillis();
mUI.showRecordingUI(true);
updateRecordingTime();
keepScreenOn();
UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
UsageStatistics.ACTION_CAPTURE_START, "Video");
}
private Bitmap getVideoThumbnail() {
Bitmap bitmap = null;
if (mVideoFileDescriptor != null) {
bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
mDesiredPreviewWidth);
} else if (mCurrentVideoUri != null) {
try {
mVideoFileDescriptor = mContentResolver.openFileDescriptor(mCurrentVideoUri, "r");
if(mVideoFileDescriptor != null){
bitmap = Thumbnail.createVideoThumbnailBitmap(
mVideoFileDescriptor.getFileDescriptor(), mDesiredPreviewWidth);
}
} catch (java.io.FileNotFoundException ex) {
// invalid uri
Log.e(TAG, ex.toString());
}
}
if (bitmap != null) {
// MetadataRetriever already rotates the thumbnail. We should rotate
// it to match the UI orientation (and mirror if it is front-facing camera).
CameraInfo[] info = CameraHolder.instance().getCameraInfo();
boolean mirror = (info[mCameraId].facing == CameraInfo.CAMERA_FACING_FRONT);
bitmap = CameraUtil.rotateAndMirror(bitmap, 0, mirror);
}
return bitmap;
}
private void showCaptureResult() {
mIsInReviewMode = true;
Bitmap bitmap = getVideoThumbnail();
if (bitmap != null) {
mUI.showReviewImage(bitmap);
}
mUI.showReviewControls();
mUI.enableCameraControls(false);
mUI.showTimeLapseUI(false);
}
private void showCaptureResultNoThumbnail() {
mUI.showReviewControls();
mUI.enableCameraControls(false);
mUI.showTimeLapseUI(false);
}
/** SPRD: fixbug258798 add stopVideoRecording handle while remove SD card @{ */
private void stopVideoRecordingOnSdCardRemoved() {
Log.v(TAG, "stopVideoRecordingOnSdCardRemoved");
mUI.setSwipingEnabled(true);
if (mMediaRecorderRecording) {
mUI.showRecordingUI(false);
mUI.enableShutter(false);
if (!mIsVideoCaptureIntent) {
mUI.enableCameraControls(true);
}
mUI.setOrientationIndicator(0, true);
Thread t = new Thread() {
public void run() {
doStopRecording();
mHandler.sendEmptyMessage(LOCK_CAMERA);
}
};
t.start();
}
mMediaRecorderRecording = false;
}
private boolean doStopRecording(){
boolean shouldAddToMediaStoreNow = false;
boolean fail = false;
try {
mMediaRecorder.setOnErrorListener(null);
mMediaRecorder.setOnInfoListener(null);
long beforStopTime = SystemClock.uptimeMillis();
mMediaRecorder.stop();
long afterStopTime = SystemClock.uptimeMillis();
mResultTime += (afterStopTime - beforStopTime);
shouldAddToMediaStoreNow = true;
mCurrentVideoFilename = mVideoFilename;
Log.v(TAG, "stopVideoRecording: Setting current video filename: "
+ mCurrentVideoFilename);
} catch (RuntimeException e) {
Log.e(TAG, "stop fail", e);
fail = true;
}
mMediaRecorderRecording = false;
mOrientationManager.unlockOrientation();
abandonAudioPlayback();
if (mPaused) {
closeCamera();
}
releaseMediaRecorder();
return fail;
}
private void lockCamera() {
if (!mPaused) {
mCameraDevice.lock();
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
stopPreview();
mUI.hideSurfaceView();
// Switch back to use SurfaceTexture for preview.
startPreview();
}
mUI.enableShutter(true);
}
}
/** SPRD: fixbug258798 end @{ */
private boolean stopVideoRecording() {
Log.v(TAG, "stopVideoRecording");
mUI.setSwipingEnabled(true);
mUI.showVideoCaptureIcon(false);
boolean fail = false;
if (mMediaRecorderRecording) {
boolean shouldAddToMediaStoreNow = false;
try {
mMediaRecorder.setOnErrorListener(null);
mMediaRecorder.setOnInfoListener(null);
long beforStopTime = SystemClock.uptimeMillis();
Log.v(TAG, "MediaRecorder.stop ...... starttime = "
+ beforStopTime);
mMediaRecorder.stop();
long afterStopTime = SystemClock.uptimeMillis();
mResultTime += (afterStopTime - beforStopTime);
Log.v(TAG, "MediaRecorder.stop ...... endtime = "
+ (afterStopTime - beforStopTime));
shouldAddToMediaStoreNow = true;
mCurrentVideoFilename = mVideoFilename;
Log.v(TAG, "stopVideoRecording: Setting current video filename: "
+ mCurrentVideoFilename);
AccessibilityUtils.makeAnnouncement(mUI.getShutterButton(),
mActivity.getString(R.string.video_recording_stopped));
} catch (RuntimeException e) {
Log.e(TAG, "stop fail", e);
if (mVideoFilename != null) deleteVideoFile(mVideoFilename);
fail = true;
// SPRD: bug 264094
mUI.enableCameraControls(true);
}
mMediaRecorderRecording = false;
mOrientationManager.unlockOrientation();
abandonAudioPlayback(); // SPRD: fix bug 255700, release audio focus
// If the activity is paused, this means activity is interrupted
// during recording. Release the camera as soon as possible because
// face unlock or other applications may need to use the camera.
if (mPaused) {
closeCamera();
}
mUI.showRecordingUI(false);
if (!mIsVideoCaptureIntent) {
mUI.enableCameraControls(true);
}
// The orientation was fixed during video recording. Now make it
// reflect the device orientation as video recording is stopped.
mUI.setOrientationIndicator(0, true);
keepScreenOnAwhile();
if (shouldAddToMediaStoreNow && !fail) {
if (mVideoFileDescriptor == null) {
saveVideo();
} else if (mIsVideoCaptureIntent) {
// if no file save is needed, we can show the post capture UI now
showCaptureResult();
if (mActivity.isAutoCapture()) {
onReviewDoneClicked(null);
}
}
}
}
// release media recorder
releaseMediaRecorder();
if (!mPaused) {
mCameraDevice.lock();
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
stopPreview();
mUI.hideSurfaceView();
// Switch back to use SurfaceTexture for preview.
startPreview();
}
}
// Update the parameters here because the parameters might have been altered
// by MediaRecorder.
if (!mPaused) mParameters = mCameraDevice.getParameters();
UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
fail ? UsageStatistics.ACTION_CAPTURE_FAIL :
UsageStatistics.ACTION_CAPTURE_DONE, "Video",
SystemClock.uptimeMillis() - mRecordingStartTime);
mPauseRecorderRecording = false;
return fail;
}
private void resetScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void keepScreenOnAwhile() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
private void keepScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
long seconds = milliSeconds / 1000; // round down to compute seconds
long minutes = seconds / 60;
long hours = minutes / 60;
long remainderMinutes = minutes - (hours * 60);
long remainderSeconds = seconds - (minutes * 60);
StringBuilder timeStringBuilder = new StringBuilder();
// Hours
if (hours > 0) {
if (hours < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(hours);
timeStringBuilder.append(':');
}
// Minutes
if (remainderMinutes < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(remainderMinutes);
timeStringBuilder.append(':');
// Seconds
if (remainderSeconds < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(remainderSeconds);
// Centi seconds
if (displayCentiSeconds) {
timeStringBuilder.append('.');
long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
if (remainderCentiSeconds < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(remainderCentiSeconds);
}
return timeStringBuilder.toString();
}
private long getTimeLapseVideoLength(long deltaMs) {
// For better approximation calculate fractional number of frames captured.
// This will update the video time at a higher resolution.
double numberOfFrames = (double) deltaMs / mTimeBetweenTimeLapseFrameCaptureMs;
return (long) (numberOfFrames / mProfile.videoFrameRate * 1000);
}
private void updateRecordingTime() {
if (!mMediaRecorderRecording) {
return;
}
long now = SystemClock.uptimeMillis();
long delta = now - mRecordingStartTime - mResultTime;
// Starting a minute before reaching the max duration
// limit, we'll countdown the remaining time instead.
boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
&& delta >= mMaxVideoDurationInMs - 60000);
long deltaAdjusted = delta;
if (countdownRemainingTime) {
deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
}
String text;
long targetNextUpdateDelay;
if (!mCaptureTimeLapse) {
text = millisecondToTimeString(deltaAdjusted, false);
targetNextUpdateDelay = 1000;
} else {
// The length of time lapse video is different from the length
// of the actual wall clock time elapsed. Display the video length
// only in format hh:mm:ss.dd, where dd are the centi seconds.
text = millisecondToTimeString(getTimeLapseVideoLength(delta), true);
targetNextUpdateDelay = mTimeBetweenTimeLapseFrameCaptureMs;
}
mUI.setRecordingTime(text);
if (mRecordingTimeCountsDown != countdownRemainingTime) {
// Avoid setting the color on every update, do it only
// when it needs changing.
mRecordingTimeCountsDown = countdownRemainingTime;
int color = mActivity.getResources().getColor(countdownRemainingTime
? R.color.recording_time_remaining_text
: R.color.recording_time_elapsed_text);
mUI.setRecordingTimeTextColor(color);
}
long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
mHandler.sendEmptyMessageDelayed(
UPDATE_RECORD_TIME, actualNextUpdateDelay);
}
private static boolean isSupported(String value, List<String> supported) {
return supported == null ? false : supported.indexOf(value) >= 0;
}
@SuppressWarnings("deprecation")
private void setCameraParameters() {
CameraUtil.P(DEBUG, TAG, "setCameraParameters");
mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
int[] fpsRange = CameraUtil.getMaxPreviewFpsRange(mParameters);
if (fpsRange.length > 0) {
mParameters.setPreviewFpsRange(
fpsRange[Parameters.PREVIEW_FPS_MIN_INDEX],
fpsRange[Parameters.PREVIEW_FPS_MAX_INDEX]);
} else {
mParameters.setPreviewFrameRate(mProfile.videoFrameRate);
}
forceFlashOffIfSupported(!mUI.isVisible());
// Set white balance parameter.
String whiteBalance = mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
mActivity.getString(R.string.pref_camera_whitebalance_default));
if (isSupported(whiteBalance,
mParameters.getSupportedWhiteBalance())) {
mParameters.setWhiteBalance(whiteBalance);
} else {
whiteBalance = mParameters.getWhiteBalance();
if (whiteBalance == null) {
whiteBalance = Parameters.WHITE_BALANCE_AUTO;
}
}
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
// Set continuous autofocus.
List<String> supportedFocus = mParameters.getSupportedFocusModes();
if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) {
mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mParameters.set(CameraUtil.RECORDING_HINT, CameraUtil.TRUE);
// Enable video stabilization. Convenience methods not available in API
// level <= 14
String vstabSupported = mParameters.get("video-stabilization-supported");
if ("true".equals(vstabSupported)) {
mParameters.set("video-stabilization", "true");
}
// Set picture size.
// The logic here is different from the logic in still-mode camera.
// There we determine the preview size based on the picture size, but
// here we determine the picture size based on the preview size.
List<Size> supported = mParameters.getSupportedPictureSizes();
Size optimalSize = CameraUtil.getOptimalVideoSnapshotPictureSize(supported,
(double) mDesiredPreviewWidth / mDesiredPreviewHeight);
Size original = mParameters.getPictureSize();
if (!original.equals(optimalSize)) {
mParameters.setPictureSize(optimalSize.width, optimalSize.height);
}
Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" +
optimalSize.height);
// Set JPEG quality.
int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
CameraProfile.QUALITY_HIGH);
mParameters.setJpegQuality(jpegQuality);
/* SPRD: Set Color Effect Value To FW.*/
String colorEffect =
mPreferences.getString(CameraSettings.KEY_VIDEO_COLOR_EFFECT,mActivity.getString(R.string.pref_entry_value_none));
if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
mParameters.setColorEffect(colorEffect);
} else {
colorEffect = mParameters.getColorEffect();
if (colorEffect == null)
colorEffect = Parameters.EFFECT_NONE;
}
// set slow-motion
// String slow_motion =
// mPreferences.getString(CameraSettings.KEY_VIDEO_SLOW_MOTION,mActivity.getString(R.string.pref_entry_value_one));
// if (isSupported(slow_motion, mParameters.getSupportedSlowmotion())) {
// mParameters.setSlowmotion(slow_motion);
// }
mCameraDevice.setParameters(mParameters);
// Keep preview size up to date.
mParameters = mCameraDevice.getParameters();
if (DEBUG) {
String message = mParameters.flatten();
CameraUtil.P(DEBUG, TAG, message);
}
// Update UI based on the new parameters.
mUI.updateOnScreenIndicators(mParameters, mPreferences);
mUI.updateControlTopButton(mParameters);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Do nothing.
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.v(TAG, "onConfigurationChanged");
setDisplayOrientation();
}
@Override
public void onOverriddenPreferencesClicked() {
}
/* SPRD: show a popup window after restore menu clicked @{ */
@Override
public void onRestorePreferencesClicked(AlertDialogPopup popup) {
Log.d(TAG, "onRestorePreferencesClicked()");
if (mPaused) return;
Runnable runnableOk = new Runnable() {
@Override
public void run() {
restorePreferences();
}
};
Runnable runnableCancel = new Runnable() {
@Override
public void run() {
mUI.dismissPopup(true);
}
};
popup.setAlertDialog(
mActivity.getString(R.string.pref_restore_detail),
mActivity.getString(R.string.confirm_restore_message),
mActivity.getString(R.string.dialog_ok), runnableOk,
mActivity.getString(R.string.dialog_cancel), runnableCancel);
mUI.showPopup(popup);
}
/* @} */
/* SPRD:Add for restore @{ */
private void restorePreferences() {
// Reset the zoom. Zoom value is not stored in preference.
if (!mMediaRecorderRecording) {
mZoomValue = 0;
updateCameraParametersZoom();
mUI.initializeZoom(mParameters);
}
if (mUI != null) {
mUI.dismissPopup(false);
Context context = mActivity;
StoragePathPreference pathPreference = StoragePathPreference.getInstance(mActivity);
pathPreference.clear();
CameraSettings.restorePreferences(context, mPreferences, mParameters);
mUI.reloadPreferences();
onSharedPreferenceChanged();
}
StorageUtil utilStorage = StorageUtil.newInstance();
utilStorage.syncThumbnailPath();
mActivity.updateStorageSpaceAndHint();
}
/* @} */
@Override
public void onSharedPreferenceChanged() {
// ignore the events after "onPause()" or preview has not started yet
if (mPaused) {
return;
}
synchronized (mPreferences) {
// If mCameraDevice is not ready then we can set the parameter in
// startPreview().
if (mCameraDevice == null) return;
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
readVideoPreferences();
mUI.showTimeLapseUI(mCaptureTimeLapse);
// We need to restart the preview if preview size is changed.
Size size = mParameters.getPreviewSize();
if (size.width != mDesiredPreviewWidth
|| size.height != mDesiredPreviewHeight) {
stopPreview();
resizeForPreviewAspectRatio();
startPreview(); // Parameters will be set in startPreview().
} else {
setCameraParameters();
}
mUI.updateOnScreenIndicators(mParameters, mPreferences);
mUI.updateControlTopButton(mParameters);
}
ListPreference prefStorage =
mPreferenceGroup.findPreference(CameraSettings.KEY_VIDEO_STORAGE_PATH);
StorageUtil utilStorage = StorageUtil.newInstance();
String patch = utilStorage.getStoragePath(mActivity, CameraUtil.MODE_VIDEO);
if(patch != null){
prefStorage.setStorageValue(patch);
}
}
protected void setCameraId(int cameraId) {
ListPreference pref = mPreferenceGroup.findPreference(CameraSettings.KEY_CAMERA_ID);
pref.setValue("" + cameraId);
}
private void switchCamera() {
if (mPaused) {
return;
}
Log.d(TAG, "Start to switch camera.");
mCameraId = mPendingSwitchCameraId;
mPendingSwitchCameraId = -1;
setCameraId(mCameraId);
closeCamera();
mUI.collapseCameraControls();
// Restart the camera and initialize the UI. From onCreate.
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
openCamera();
readVideoPreferences();
startPreview();
initializeVideoSnapshot();
resizeForPreviewAspectRatio();
initializeVideoControl();
// From onResume
mZoomValue = 0;
mUI.initializeZoom(mParameters);
mUI.setOrientationIndicator(0, false);
// Start switch camera animation. Post a message because
// onFrameAvailable from the old camera may already exist.
mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
mUI.updateOnScreenIndicators(mParameters, mPreferences);
mUI.updateControlTopButton(mParameters);
}
// Preview texture has been copied. Now camera can be released and the
// animation can be started.
@Override
public void onPreviewTextureCopied() {
mHandler.sendEmptyMessage(SWITCH_CAMERA);
}
@Override
public void onCaptureTextureCopied() {
}
private void initializeVideoSnapshot() {
if (mParameters == null) return;
if (CameraUtil.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
// Show the tap to focus toast if this is the first start.
if (mPreferences.getBoolean(
CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, true)) {
// Delay the toast for one second to wait for orientation.
mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_SNAPSHOT_TOAST, 1000);
}
}
}
void showVideoSnapshotUI(boolean enabled) {
if (mParameters == null) return;
if (CameraUtil.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
if (enabled) {
mUI.animateFlash();
mUI.animateCapture();
} else {
mUI.showPreviewBorder(enabled);
}
mUI.enableShutter(!enabled);
}
}
private void forceFlashOffIfSupported(boolean forceOff) {
CameraUtil.P(DEBUG, TAG, "forceFlashOffIfSupported forceOff=" + forceOff);
String flashMode;
if (!forceOff) {
flashMode = mPreferences.getString(
CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE,
mActivity.getString(R.string.pref_camera_video_flashmode_default));
} else {
flashMode = Parameters.FLASH_MODE_OFF;
}
List<String> supportedFlash = mParameters.getSupportedFlashModes();
boolean isSupported = isSupported(flashMode, supportedFlash);
CameraUtil.P(DEBUG, TAG, "forceFlashOffIfSupported flashMode=" + flashMode + ", isSupported=" + isSupported);
if (isSupported) {
mParameters.setFlashMode(flashMode);
ListPreference pref = mPreferenceGroup.findPreference(
CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE);
if (pref != null) {
pref.setValue(flashMode);
}
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = mActivity.getString(
R.string.pref_camera_flashmode_no_flash);
}
}
}
/**
* Used to update the flash mode. Video mode can turn on the flash as torch
* mode, which we would like to turn on and off when we switching in and
* out to the preview.
*
* @param forceOff whether we want to force the flash off.
*/
private void forceFlashOff(boolean forceOff) {
if (!mPreviewing || mParameters.getFlashMode() == null) {
return;
}
forceFlashOffIfSupported(forceOff);
mCameraDevice.setParameters(mParameters);
mUI.updateOnScreenIndicators(mParameters, mPreferences);
mUI.updateControlTopButton(mParameters);
}
@Override
public void onPreviewFocusChanged(boolean previewFocused) {
mUI.onPreviewFocusChanged(previewFocused);
forceFlashOff(!previewFocused);
}
@Override
public boolean arePreviewControlsVisible() {
return mUI.arePreviewControlsVisible();
}
private final class JpegPictureCallback implements CameraPictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
@Override
public void onPictureTaken(byte [] jpegData, CameraProxy camera) {
Log.v(TAG, "onPictureTaken");
mSnapshotInProgress = false;
showVideoSnapshotUI(false);
storeImage(jpegData, mLocation);
}
}
private void storeImage(final byte[] data, Location loc) {
long dateTaken = System.currentTimeMillis();
String title = CameraUtil.createJpegName(dateTaken);
ExifInterface exif = Exif.getExif(data);
int orientation = Exif.getOrientation(exif);
mActivity.getMediaSaveService().addImage(
data, title, dateTaken, loc, orientation,
exif, mOnPhotoSavedListener, mContentResolver,CameraUtil.MODE_VIDEO);
}
private String convertOutputFormatToMimeType(int outputFileFormat) {
if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
return "video/mp4";
}
return "video/3gpp";
}
private String convertOutputFormatToFileExt(int outputFileFormat) {
if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
return ".mp4";
}
return ".3gp";
}
private void closeVideoFileDescriptor() {
if (mVideoFileDescriptor != null) {
try {
mVideoFileDescriptor.close();
} catch (IOException e) {
Log.e(TAG, "Fail to close fd", e);
}
mVideoFileDescriptor = null;
}
}
private void showTapToSnapshotToast() {
new RotateTextToast(mActivity, R.string.video_snapshot_hint, 0)
.show();
// Clear the preference.
Editor editor = mPreferences.edit();
editor.putBoolean(CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, false);
editor.apply();
}
@Override
public boolean updateStorageHintOnResume() {
return true;
}
// required by OnPreferenceChangedListener
@Override
public void onCameraPickerClicked(int cameraId) {
if (mPaused || mPendingSwitchCameraId != -1) return;
mUI.enableSwitchCameraButton(false);
mPendingSwitchCameraId = cameraId;
Log.d(TAG, "Start to copy texture.");
// We need to keep a preview frame for the animation before
// releasing the camera. This will trigger onPreviewTextureCopied.
// TODO: ((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
// Disable all camera controls.
mSwitchingCamera = true;
switchCamera();
mSwitchingCamera = false;
}
@Override
public void onShowSwitcherPopup() {
mUI.onShowSwitcherPopup();
}
@Override
public void onMediaSaveServiceConnected(MediaSaveService s) {
// do nothing.
}
@Override
public void onPreviewUIReady() {
startPreview();
}
@Override
public void onPreviewUIDestroyed() {
stopPreview();
}
// onClick handler for R.id.btn_switch
public void onSwitchButtonClicked() {
if (mCameraDevice == null)
return;
if (!mMediaRecorderRecording) {
mUI.hideControlsUI();
ListPreference pref = mPreferenceGroup.findPreference(
CameraSettings.KEY_CAMERA_ID);
int index = pref.findIndexOfValue(pref.getValue());
CharSequence[] values = pref.getEntryValues();
index = (index + 1) % values.length;
int newCameraId = Integer.parseInt((String) values[index]);
pref.setValue("" + newCameraId);
onCameraPickerClicked(newCameraId);
mHandler.sendEmptyMessageDelayed(SHOW_CONTROLS_UI, SHOW_CONTROLS_UI_TIMEOUT);
}
}
// onClick handler for R.id.btn_hdr
public void onHdrButtonClicked() {
//video do not support hdr ,so do nothing here
}
// onClick handler for R.id.btn_flash
public void onFlashButtonClicked() {
if (mCameraDevice == null)
return;
//need to do
if (!mMediaRecorderRecording) {
setFlashMode();
mUI.updateControlTopButton(mParameters);
}
}
private void setFlashMode() {
ListPreference pref = mPreferenceGroup.findPreference(
CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE);
if (pref != null) {
int index = pref.findIndexOfValue(pref.getValue());
CharSequence[] values = pref.getEntryValues();
index = (index + 1) % values.length;
pref.setValue("" + values[index]);
}
// Set flash mode.
String flashMode =
mPreferences.getString(
CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE,
mActivity.getString(R.string.pref_camera_flashmode_default));
// if HDR switch is on, so we must reset flash to off
// because camera device is unsupported HDR and flash both on
// if (mHDRController != null && mHDRController.switchOn()) {
// flashMode =
// mActivity.getString(R.string.pref_camera_flashmode_default);
// // if scene mode is burst and flash is on, so we must override
// flash setting
// } else if(mBurstController != null &&
// mBurstController.switchOn()) {
// flashMode =
// mActivity.getString(R.string.pref_camera_flashmode_default);
// }
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = mActivity.getString(R.string.pref_camera_flashmode_no_flash);
}
}
// Set white balance parameter.
String whiteBalance =
mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
mActivity.getString(R.string.pref_camera_whitebalance_default));
if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) {
mParameters.setWhiteBalance(whiteBalance);
} else {
whiteBalance = mParameters.getWhiteBalance();
if (whiteBalance == null) {
whiteBalance = Parameters.WHITE_BALANCE_AUTO;
}
}
mCameraDevice.setParameters(mParameters);
}
public void updateThumbnail(Bitmap bitmap) {
if(mIsVideoCaptureIntent)
bitmap = null;
mUI.updateThumbnail(bitmap);
}
public void onCameraSettingClicked() {
if (!mMediaRecorderRecording) {
mUI.onCameraSettingClicked();
}
}
/* SPRD: click 1st level popup title to dismiss start @{ */
public void onSettingTitleClicked(View v) {
mUI.onSettingTitleClicked(v);
}
/* click 1st level popup title to dismiss end @} */
public void onPauseClicked() {
long timePasedAfterRecording = SystemClock.uptimeMillis()
- mRecordingStartTime;
Log.d(TAG, "time passed after recording started: "
+ timePasedAfterRecording);
if (timePasedAfterRecording < RECORD_LIMIT_TIME) {
new RotateTextToast(
mActivity, R.string.notice_record_time_too_short, 0).show(RECORD_LIMIT_TOAST_SHOW_TIME);
return;
}
if (mMediaRecorderRecording) {
Log.d(TAG, String.format("mMediaRecorder execute %s",
(mMediaRecorderRecording ? "resume" : "pause")));
// current is pause state
if (mPauseRecorderRecording) {
//mMediaRecorder.resume();
calculatePauseDuration(mPauseRecorderRecording);
updateRecordingTime();
}
// current is recording state
else {
mHandler.removeMessages(UPDATE_RECORD_TIME);
//mMediaRecorder.pause();
calculatePauseDuration(mPauseRecorderRecording);
}
// reverse pause state
mPauseRecorderRecording = !mPauseRecorderRecording;
}
mUI.onPauseClicked(mPauseRecorderRecording);
}
public void onStopClicked() {
if (!mMediaRecorderRecording)
return;
onShutterButtonClick();
mUI.onStopClicked();
}
private void calculatePauseDuration(boolean isPause) {
if (isPause) {
mResumeTime = SystemClock.uptimeMillis();
mResultTime += (mResumeTime - mPauseTime);
} else {
mPauseTime = SystemClock.uptimeMillis();
}
}
public void showSwitcher() {
if(isVideoCaptureIntent())
return;
else
mUI.showSwitcher();
}
public void hideSwitcher() {
if(isVideoCaptureIntent())
return;
else
mUI.hideSwitcher();
}
/* SRRD: added 20140107 of 263964 enabled item not enable sometimes @{ */
@Override
public void updateSettingsMutex() {
// nothing to do
}
/* @} */
@Override
public void hideControls() {
mUI.hideControlsUI();
}
@Override
public void showControls() {
if(!mIsInReviewMode)
mUI.showControlsUI();
}
private void updateCameraParametersZoom() {
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
}
}