VideoModule.java revision 01725fad5b5b881ccbdb95ff6e6cd4ac3ec720e0
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.camera; 18 19import android.annotation.TargetApi; 20import android.app.Activity; 21import android.content.ActivityNotFoundException; 22import android.content.BroadcastReceiver; 23import android.content.ContentResolver; 24import android.content.ContentValues; 25import android.content.Context; 26import android.content.Intent; 27import android.content.IntentFilter; 28import android.content.SharedPreferences.Editor; 29import android.content.res.Configuration; 30import android.graphics.Bitmap; 31import android.hardware.Camera.CameraInfo; 32import android.hardware.Camera.Parameters; 33import android.hardware.Camera.PictureCallback; 34import android.hardware.Camera.Size; 35import android.location.Location; 36import android.media.CamcorderProfile; 37import android.media.CameraProfile; 38import android.media.MediaRecorder; 39import android.net.Uri; 40import android.os.Build; 41import android.os.Bundle; 42import android.os.Handler; 43import android.os.Message; 44import android.os.ParcelFileDescriptor; 45import android.os.SystemClock; 46import android.provider.MediaStore; 47import android.provider.MediaStore.Video; 48import android.util.Log; 49import android.view.KeyEvent; 50import android.view.LayoutInflater; 51import android.view.MotionEvent; 52import android.view.OrientationEventListener; 53import android.view.SurfaceHolder; 54import android.view.View; 55import android.view.ViewGroup; 56import android.view.WindowManager; 57import android.widget.ImageView; 58import android.widget.LinearLayout; 59import android.widget.TextView; 60import android.widget.Toast; 61 62import com.android.camera.ui.CameraPicker; 63import com.android.camera.ui.IndicatorControlContainer; 64import com.android.camera.ui.PopupManager; 65import com.android.camera.ui.PreviewSurfaceView; 66import com.android.camera.ui.Rotatable; 67import com.android.camera.ui.RotateImageView; 68import com.android.camera.ui.RotateLayout; 69import com.android.camera.ui.RotateTextToast; 70import com.android.camera.ui.TwoStateImageView; 71import com.android.camera.ui.ZoomControl; 72import com.android.gallery3d.common.ApiHelper; 73 74import java.io.File; 75import java.io.IOException; 76import java.text.SimpleDateFormat; 77import java.util.Date; 78import java.util.Iterator; 79import java.util.List; 80 81public class VideoModule implements CameraModule, 82 CameraPreference.OnPreferenceChangedListener, 83 ShutterButton.OnShutterButtonListener, 84 MediaRecorder.OnErrorListener, 85 MediaRecorder.OnInfoListener, 86 EffectsRecorder.EffectsListener { 87 88 private static final String TAG = "CAM_VideoModule"; 89 90 // We number the request code from 1000 to avoid collision with Gallery. 91 private static final int REQUEST_EFFECT_BACKDROPPER = 1000; 92 93 private static final int CHECK_DISPLAY_ROTATION = 3; 94 private static final int CLEAR_SCREEN_DELAY = 4; 95 private static final int UPDATE_RECORD_TIME = 5; 96 private static final int ENABLE_SHUTTER_BUTTON = 6; 97 private static final int SHOW_TAP_TO_SNAPSHOT_TOAST = 7; 98 private static final int SWITCH_CAMERA = 8; 99 private static final int SWITCH_CAMERA_START_ANIMATION = 9; 100 private static final int HIDE_SURFACE_VIEW = 10; 101 102 private static final int SCREEN_DELAY = 2 * 60 * 1000; 103 104 private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms 105 106 /** 107 * An unpublished intent flag requesting to start recording straight away 108 * and return as soon as recording is stopped. 109 * TODO: consider publishing by moving into MediaStore. 110 */ 111 private static final String EXTRA_QUICK_CAPTURE = 112 "android.intent.extra.quickCapture"; 113 114 private static final int MIN_THUMB_SIZE = 64; 115 // module fields 116 private CameraActivity mActivity; 117 private View mRootView; 118 private boolean mPaused; 119 private int mCameraId; 120 private Parameters mParameters; 121 122 private boolean mSnapshotInProgress = false; 123 124 private static final String EFFECT_BG_FROM_GALLERY = "gallery"; 125 126 private final CameraErrorCallback mErrorCallback = new CameraErrorCallback(); 127 128 private ComboPreferences mPreferences; 129 private PreferenceGroup mPreferenceGroup; 130 131 private PreviewFrameLayout mPreviewFrameLayout; 132 private boolean mSurfaceViewReady; 133 private SurfaceHolder.Callback mSurfaceViewCallback; 134 private PreviewSurfaceView mPreviewSurfaceView; 135 private CameraScreenNail.OnFrameDrawnListener mFrameDrawnListener; 136 private View mReviewControl; 137 private RotateDialogController mRotateDialog; 138 139 // An review image having same size as preview. It is displayed when 140 // recording is stopped in capture intent. 141 private ImageView mReviewImage; 142 private Rotatable mReviewCancelButton; 143 private Rotatable mReviewDoneButton; 144 private RotateImageView mReviewPlayButton; 145 private View mReviewRetakeButton; 146 private ShutterButton mShutterButton; 147 private TextView mRecordingTimeView; 148 private RotateLayout mBgLearningMessageRotater; 149 private View mBgLearningMessageFrame; 150 private LinearLayout mLabelsLinearLayout; 151 152 private boolean mIsVideoCaptureIntent; 153 private boolean mQuickCapture; 154 155 private MediaRecorder mMediaRecorder; 156 private EffectsRecorder mEffectsRecorder; 157 private boolean mEffectsDisplayResult; 158 159 private int mEffectType = EffectsRecorder.EFFECT_NONE; 160 private Object mEffectParameter = null; 161 private String mEffectUriFromGallery = null; 162 private String mPrefVideoEffectDefault; 163 private boolean mResetEffect = true; 164 165 private boolean mSwitchingCamera; 166 private boolean mMediaRecorderRecording = false; 167 private long mRecordingStartTime; 168 private boolean mRecordingTimeCountsDown = false; 169 private RotateLayout mRecordingTimeRect; 170 private long mOnResumeTime; 171 // The video file that the hardware camera is about to record into 172 // (or is recording into.) 173 private String mVideoFilename; 174 private ParcelFileDescriptor mVideoFileDescriptor; 175 176 // The video file that has already been recorded, and that is being 177 // examined by the user. 178 private String mCurrentVideoFilename; 179 private Uri mCurrentVideoUri; 180 private ContentValues mCurrentVideoValues; 181 182 private CamcorderProfile mProfile; 183 184 // The video duration limit. 0 menas no limit. 185 private int mMaxVideoDurationInMs; 186 187 // Time Lapse parameters. 188 private boolean mCaptureTimeLapse = false; 189 // Default 0. If it is larger than 0, the camcorder is in time lapse mode. 190 private int mTimeBetweenTimeLapseFrameCaptureMs = 0; 191 private View mTimeLapseLabel; 192 193 private int mDesiredPreviewWidth; 194 private int mDesiredPreviewHeight; 195 196 boolean mPreviewing = false; // True if preview is started. 197 // The display rotation in degrees. This is only valid when mPreviewing is 198 // true. 199 private int mDisplayRotation; 200 private int mCameraDisplayOrientation; 201 202 private ContentResolver mContentResolver; 203 204 private LocationManager mLocationManager; 205 206 private VideoNamer mVideoNamer; 207 208 private final Handler mHandler = new MainHandler(); 209 210 private MyOrientationEventListener mOrientationListener; 211 // The degrees of the device rotated clockwise from its natural orientation. 212 private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; 213 // The orientation compensation for icons and thumbnails. Ex: if the value 214 // is 90, the UI components should be rotated 90 degrees counter-clockwise. 215 private int mOrientationCompensation = 0; 216 // The orientation compensation when we start recording. 217 private int mOrientationCompensationAtRecordStart; 218 219 private int mZoomValue; // The current zoom value. 220 private int mZoomMax; 221 private boolean mRestoreFlash; // This is used to check if we need to restore the flash 222 // status when going back from gallery. 223 224 protected class CameraOpenThread extends Thread { 225 @Override 226 public void run() { 227 try { 228 mActivity.mCameraDevice = Util.openCamera(mActivity, mCameraId); 229 mParameters = mActivity.mCameraDevice.getParameters(); 230 } catch (CameraHardwareException e) { 231 mActivity.mOpenCameraFail = true; 232 } catch (CameraDisabledException e) { 233 mActivity.mCameraDisabled = true; 234 } 235 } 236 } 237 238 // This Handler is used to post message back onto the main thread of the 239 // application 240 private class MainHandler extends Handler { 241 @Override 242 public void handleMessage(Message msg) { 243 switch (msg.what) { 244 245 case ENABLE_SHUTTER_BUTTON: 246 mShutterButton.setEnabled(true); 247 break; 248 249 case CLEAR_SCREEN_DELAY: { 250 mActivity.getWindow().clearFlags( 251 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 252 break; 253 } 254 255 case UPDATE_RECORD_TIME: { 256 updateRecordingTime(); 257 break; 258 } 259 260 case CHECK_DISPLAY_ROTATION: { 261 // Restart the preview if display rotation has changed. 262 // Sometimes this happens when the device is held upside 263 // down and camera app is opened. Rotation animation will 264 // take some time and the rotation value we have got may be 265 // wrong. Framework does not have a callback for this now. 266 if ((Util.getDisplayRotation(mActivity) != mDisplayRotation) 267 && !mMediaRecorderRecording && !mSwitchingCamera) { 268 startPreview(); 269 } 270 if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) { 271 mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100); 272 } 273 break; 274 } 275 276 case SHOW_TAP_TO_SNAPSHOT_TOAST: { 277 showTapToSnapshotToast(); 278 break; 279 } 280 281 case SWITCH_CAMERA: { 282 switchCamera(); 283 break; 284 } 285 286 case SWITCH_CAMERA_START_ANIMATION: { 287 ((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera(); 288 289 // Enable all camera controls. 290 mSwitchingCamera = false; 291 break; 292 } 293 294 case HIDE_SURFACE_VIEW: { 295 mPreviewSurfaceView.setVisibility(View.GONE); 296 break; 297 } 298 299 default: 300 Log.v(TAG, "Unhandled message: " + msg.what); 301 break; 302 } 303 } 304 } 305 306 private BroadcastReceiver mReceiver = null; 307 308 private class MyBroadcastReceiver extends BroadcastReceiver { 309 @Override 310 public void onReceive(Context context, Intent intent) { 311 String action = intent.getAction(); 312 if (action.equals(Intent.ACTION_MEDIA_EJECT)) { 313 stopVideoRecording(); 314 } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { 315 Toast.makeText(mActivity, 316 mActivity.getResources().getString(R.string.wait), Toast.LENGTH_LONG).show(); 317 } 318 } 319 } 320 321 private String createName(long dateTaken) { 322 Date date = new Date(dateTaken); 323 SimpleDateFormat dateFormat = new SimpleDateFormat( 324 mActivity.getString(R.string.video_file_name_format)); 325 326 return dateFormat.format(date); 327 } 328 329 private int getPreferredCameraId(ComboPreferences preferences) { 330 int intentCameraId = Util.getCameraFacingIntentExtras(mActivity); 331 if (intentCameraId != -1) { 332 // Testing purpose. Launch a specific camera through the intent 333 // extras. 334 return intentCameraId; 335 } else { 336 return CameraSettings.readPreferredCameraId(preferences); 337 } 338 } 339 340 private void initializeSurfaceView() { 341 mPreviewSurfaceView = (PreviewSurfaceView) mRootView.findViewById(R.id.preview_surface_view); 342 if (!ApiHelper.HAS_SURFACE_TEXTURE) { // API level < 11 343 if (mSurfaceViewCallback == null) { 344 mSurfaceViewCallback = new SurfaceViewCallback(); 345 } 346 mPreviewSurfaceView.getHolder().addCallback(mSurfaceViewCallback); 347 mPreviewSurfaceView.setVisibility(View.VISIBLE); 348 } else if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { // API level < 16 349 if (mSurfaceViewCallback == null) { 350 mSurfaceViewCallback = new SurfaceViewCallback(); 351 mFrameDrawnListener = new CameraScreenNail.OnFrameDrawnListener() { 352 @Override 353 public void onFrameDrawn(CameraScreenNail c) { 354 mHandler.sendEmptyMessage(HIDE_SURFACE_VIEW); 355 } 356 }; 357 } 358 mPreviewSurfaceView.getHolder().addCallback(mSurfaceViewCallback); 359 } 360 } 361 362 @Override 363 public void init(CameraActivity activity, View root, boolean reuseScreenNail) { 364 mActivity = activity; 365 mRootView = root; 366 mPreferences = new ComboPreferences(mActivity); 367 CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal()); 368 mCameraId = getPreferredCameraId(mPreferences); 369 370 mPreferences.setLocalId(mActivity, mCameraId); 371 CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); 372 373 mActivity.mNumberOfCameras = CameraHolder.instance().getNumberOfCameras(); 374 mPrefVideoEffectDefault = mActivity.getString(R.string.pref_video_effect_default); 375 resetEffect(); 376 377 /* 378 * To reduce startup time, we start the preview in another thread. 379 * We make sure the preview is started at the end of onCreate. 380 */ 381 CameraOpenThread cameraOpenThread = new CameraOpenThread(); 382 cameraOpenThread.start(); 383 384 mContentResolver = mActivity.getContentResolver(); 385 386 mActivity.getLayoutInflater().inflate(R.layout.video_module, (ViewGroup) mRootView); 387 388 // Surface texture is from camera screen nail and startPreview needs it. 389 // This must be done before startPreview. 390 mIsVideoCaptureIntent = isVideoCaptureIntent(); 391 if (reuseScreenNail) { 392 mActivity.reuseCameraScreenNail(!mIsVideoCaptureIntent); 393 } else { 394 mActivity.createCameraScreenNail(!mIsVideoCaptureIntent); 395 } 396 initializeSurfaceView(); 397 398 // Make sure camera device is opened. 399 try { 400 cameraOpenThread.join(); 401 if (mActivity.mOpenCameraFail) { 402 Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera); 403 return; 404 } else if (mActivity.mCameraDisabled) { 405 Util.showErrorAndFinish(mActivity, R.string.camera_disabled); 406 return; 407 } 408 } catch (InterruptedException ex) { 409 // ignore 410 } 411 412 Thread startPreviewThread = new Thread(new Runnable() { 413 @Override 414 public void run() { 415 readVideoPreferences(); 416 startPreview(); 417 } 418 }); 419 startPreviewThread.start(); 420 421 initializeControlByIntent(); 422 initializeMiscControls(); 423 424 mRotateDialog = new RotateDialogController(mActivity, R.layout.rotate_dialog); 425 mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); 426 mOrientationListener = new MyOrientationEventListener(mActivity); 427 mLocationManager = new LocationManager(mActivity, null); 428 429 // Make sure preview is started. 430 try { 431 startPreviewThread.join(); 432 if (mActivity.mOpenCameraFail) { 433 Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera); 434 return; 435 } else if (mActivity.mCameraDisabled) { 436 Util.showErrorAndFinish(mActivity, R.string.camera_disabled); 437 return; 438 } 439 } catch (InterruptedException ex) { 440 // ignore 441 } 442 443 showTimeLapseUI(mCaptureTimeLapse); 444 initializeVideoSnapshot(); 445 resizeForPreviewAspectRatio(); 446 447 initializeIndicatorControl(); 448 } 449 450 @Override 451 public void onStop() {} 452 453 private void loadCameraPreferences() { 454 CameraSettings settings = new CameraSettings(mActivity, mParameters, 455 mCameraId, CameraHolder.instance().getCameraInfo()); 456 // Remove the video quality preference setting when the quality is given in the intent. 457 mPreferenceGroup = filterPreferenceScreenByIntent( 458 settings.getPreferenceGroup(R.xml.video_preferences)); 459 } 460 461 @Override 462 public boolean collapseCameraControls() { 463 return false; 464 } 465 466 private void enableCameraControls(boolean enable) { 467 } 468 469 private void initializeIndicatorControl() { 470 loadCameraPreferences(); 471 472 final String[] SETTING_KEYS = { 473 CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE, 474 CameraSettings.KEY_WHITE_BALANCE, 475 CameraSettings.KEY_VIDEO_EFFECT, 476 CameraSettings.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL, 477 CameraSettings.KEY_VIDEO_QUALITY}; 478 final String[] OTHER_SETTING_KEYS = { 479 CameraSettings.KEY_RECORD_LOCATION}; 480 481 482 if (effectsActive()) { 483// mIndicatorControlContainer.overrideSettings( 484// CameraSettings.KEY_VIDEO_QUALITY, 485// Integer.toString(getLowVideoQuality())); 486 } 487 } 488 489 @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) 490 private static int getLowVideoQuality() { 491 if (ApiHelper.HAS_FINE_RESOLUTION_QUALITY_LEVELS) { 492 return CamcorderProfile.QUALITY_480P; 493 } else { 494 return CamcorderProfile.QUALITY_LOW; 495 } 496 } 497 498 private class MyOrientationEventListener 499 extends OrientationEventListener { 500 public MyOrientationEventListener(Context context) { 501 super(context); 502 } 503 504 @Override 505 public void onOrientationChanged(int orientation) { 506 // We keep the last known orientation. So if the user first orient 507 // the camera then point the camera to floor or sky, we still have 508 // the correct orientation. 509 if (orientation == ORIENTATION_UNKNOWN) return; 510 int newOrientation = Util.roundOrientation(orientation, mOrientation); 511 512 if (mOrientation != newOrientation) { 513 mOrientation = newOrientation; 514 // The input of effects recorder is affected by 515 // android.hardware.Camera.setDisplayOrientation. Its value only 516 // compensates the camera orientation (no Display.getRotation). 517 // So the orientation hint here should only consider sensor 518 // orientation. 519 if (effectsActive()) { 520 mEffectsRecorder.setOrientationHint(mOrientation); 521 } 522 } 523 524 // When the screen is unlocked, display rotation may change. Always 525 // calculate the up-to-date orientationCompensation. 526 int orientationCompensation = 527 (mOrientation + Util.getDisplayRotation(mActivity)) % 360; 528 529 if (mOrientationCompensation != orientationCompensation) { 530 mOrientationCompensation = orientationCompensation; 531 // Do not rotate the icons during recording because the video 532 // orientation is fixed after recording. 533 if (!mMediaRecorderRecording) { 534 setOrientationIndicator(mOrientationCompensation, true); 535 } 536 } 537 538 // Show the toast after getting the first orientation changed. 539 if (mHandler.hasMessages(SHOW_TAP_TO_SNAPSHOT_TOAST)) { 540 mHandler.removeMessages(SHOW_TAP_TO_SNAPSHOT_TOAST); 541 showTapToSnapshotToast(); 542 } 543 } 544 } 545 546 private void setOrientationIndicator(int orientation, boolean animation) { 547 Rotatable[] indicators = { 548 //mActivity.mThumbnailView, mModePicker, 549 mBgLearningMessageRotater, 550 mReviewDoneButton, mReviewPlayButton, mRotateDialog}; 551 for (Rotatable indicator : indicators) { 552 if (indicator != null) indicator.setOrientation(orientation, animation); 553 } 554 555 // We change the orientation of the review cancel button only for tablet 556 // UI because there's a label along with the X icon. For phone UI, we 557 // don't change the orientation because there's only a symmetrical X 558 // icon. 559 if (mReviewCancelButton instanceof RotateLayout) { 560 mReviewCancelButton.setOrientation(orientation, animation); 561 } 562 563 // We change the orientation of the linearlayout only for phone UI because when in portrait 564 // the width is not enough. 565 if (mLabelsLinearLayout != null) { 566 if (((orientation / 90) & 1) == 0) { 567 mLabelsLinearLayout.setOrientation(LinearLayout.VERTICAL); 568 } else { 569 mLabelsLinearLayout.setOrientation(LinearLayout.HORIZONTAL); 570 } 571 } 572 mRecordingTimeRect.setOrientation(mOrientationCompensation, animation); 573 } 574 575 private void startPlayVideoActivity() { 576 Intent intent = new Intent(Intent.ACTION_VIEW); 577 intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat)); 578 try { 579 mActivity.startActivity(intent); 580 } catch (ActivityNotFoundException ex) { 581 Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); 582 } 583 } 584 585 @OnClickAttr 586 public void onThumbnailClicked(View v) { 587 if (!mMediaRecorderRecording && mActivity.mThumbnail != null 588 && !mSwitchingCamera) { 589 mActivity.gotoGallery(); 590 } 591 } 592 593 @OnClickAttr 594 public void onReviewRetakeClicked(View v) { 595 deleteCurrentVideo(); 596 hideAlert(); 597 } 598 599 @OnClickAttr 600 public void onReviewPlayClicked(View v) { 601 startPlayVideoActivity(); 602 } 603 604 @OnClickAttr 605 public void onReviewDoneClicked(View v) { 606 doReturnToCaller(true); 607 } 608 609 @OnClickAttr 610 public void onReviewCancelClicked(View v) { 611 stopVideoRecording(); 612 doReturnToCaller(false); 613 } 614 615 private void onStopVideoRecording() { 616 mEffectsDisplayResult = true; 617 boolean recordFail = stopVideoRecording(); 618 if (mIsVideoCaptureIntent) { 619 if (!effectsActive()) { 620 if (mQuickCapture) { 621 doReturnToCaller(!recordFail); 622 } else if (!recordFail) { 623 showAlert(); 624 } 625 } 626 } else if (!recordFail){ 627 // Start capture animation. 628 if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { 629 // The capture animation is disabled on ICS because we use SurfaceView 630 // for preview during recording. When the recording is done, we switch 631 // back to use SurfaceTexture for preview and we need to stop then start 632 // the preview. This will cause the preview flicker since the preview 633 // will not be continuous for a short period of time. 634 ((CameraScreenNail) mActivity.mCameraScreenNail).animateCapture(getCameraRotation()); 635 } 636 if (!effectsActive()) getThumbnail(); 637 } 638 } 639 640 private int getCameraRotation() { 641 return (mOrientationCompensation - mDisplayRotation + 360) % 360; 642 } 643 644 public void onProtectiveCurtainClick(View v) { 645 // Consume clicks 646 } 647 648 @Override 649 public void onShutterButtonClick() { 650 if (collapseCameraControls() || mSwitchingCamera) return; 651 652 boolean stop = mMediaRecorderRecording; 653 654 if (stop) { 655 onStopVideoRecording(); 656 } else { 657 startVideoRecording(); 658 } 659 mShutterButton.setEnabled(false); 660 661 // Keep the shutter button disabled when in video capture intent 662 // mode and recording is stopped. It'll be re-enabled when 663 // re-take button is clicked. 664 if (!(mIsVideoCaptureIntent && stop)) { 665 mHandler.sendEmptyMessageDelayed( 666 ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT); 667 } 668 } 669 670 @Override 671 public void onShutterButtonFocus(boolean pressed) { 672 // Do nothing (everything happens in onShutterButtonClick). 673 } 674 675 private void readVideoPreferences() { 676 // The preference stores values from ListPreference and is thus string type for all values. 677 // We need to convert it to int manually. 678 String defaultQuality = CameraSettings.getDefaultVideoQuality(mCameraId, 679 mActivity.getResources().getString(R.string.pref_video_quality_default)); 680 String videoQuality = 681 mPreferences.getString(CameraSettings.KEY_VIDEO_QUALITY, 682 defaultQuality); 683 int quality = Integer.valueOf(videoQuality); 684 685 // Set video quality. 686 Intent intent = mActivity.getIntent(); 687 if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { 688 int extraVideoQuality = 689 intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); 690 if (extraVideoQuality > 0) { 691 quality = CamcorderProfile.QUALITY_HIGH; 692 } else { // 0 is mms. 693 quality = CamcorderProfile.QUALITY_LOW; 694 } 695 } 696 697 // Set video duration limit. The limit is read from the preference, 698 // unless it is specified in the intent. 699 if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) { 700 int seconds = 701 intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0); 702 mMaxVideoDurationInMs = 1000 * seconds; 703 } else { 704 mMaxVideoDurationInMs = CameraSettings.DEFAULT_VIDEO_DURATION; 705 } 706 707 // Set effect 708 mEffectType = CameraSettings.readEffectType(mPreferences); 709 if (mEffectType != EffectsRecorder.EFFECT_NONE) { 710 mEffectParameter = CameraSettings.readEffectParameter(mPreferences); 711 // Set quality to be no higher than 480p. 712 CamcorderProfile profile = CamcorderProfile.get(mCameraId, quality); 713 if (profile.videoFrameHeight > 480) { 714 quality = getLowVideoQuality(); 715 } 716 // On initial startup, can get here before indicator control is 717 // enabled. In that case, UI quality override handled in 718 // initializeIndicatorControl. 719// if (mIndicatorControlContainer != null) { 720// mIndicatorControlContainer.overrideSettings( 721// CameraSettings.KEY_VIDEO_QUALITY, 722// Integer.toString(getLowVideoQuality())); 723// } 724 } else { 725 mEffectParameter = null; 726// if (mIndicatorControlContainer != null) { 727// mIndicatorControlContainer.overrideSettings( 728// CameraSettings.KEY_VIDEO_QUALITY, 729// null); 730// } 731 } 732 // Read time lapse recording interval. 733 if (ApiHelper.HAS_TIME_LAPSE_RECORDING) { 734 String frameIntervalStr = mPreferences.getString( 735 CameraSettings.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL, 736 mActivity.getString(R.string.pref_video_time_lapse_frame_interval_default)); 737 mTimeBetweenTimeLapseFrameCaptureMs = Integer.parseInt(frameIntervalStr); 738 mCaptureTimeLapse = (mTimeBetweenTimeLapseFrameCaptureMs != 0); 739 } 740 // TODO: This should be checked instead directly +1000. 741 if (mCaptureTimeLapse) quality += 1000; 742 mProfile = CamcorderProfile.get(mCameraId, quality); 743 getDesiredPreviewSize(); 744 } 745 746 private void writeDefaultEffectToPrefs() { 747 ComboPreferences.Editor editor = mPreferences.edit(); 748 editor.putString(CameraSettings.KEY_VIDEO_EFFECT, 749 mActivity.getString(R.string.pref_video_effect_default)); 750 editor.apply(); 751 } 752 753 @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) 754 private void getDesiredPreviewSize() { 755 mParameters = mActivity.mCameraDevice.getParameters(); 756 if (ApiHelper.HAS_GET_SUPPORTED_VIDEO_SIZE) { 757 if (mParameters.getSupportedVideoSizes() == null || effectsActive()) { 758 mDesiredPreviewWidth = mProfile.videoFrameWidth; 759 mDesiredPreviewHeight = mProfile.videoFrameHeight; 760 } else { // Driver supports separates outputs for preview and video. 761 List<Size> sizes = mParameters.getSupportedPreviewSizes(); 762 Size preferred = mParameters.getPreferredPreviewSizeForVideo(); 763 int product = preferred.width * preferred.height; 764 Iterator<Size> it = sizes.iterator(); 765 // Remove the preview sizes that are not preferred. 766 while (it.hasNext()) { 767 Size size = it.next(); 768 if (size.width * size.height > product) { 769 it.remove(); 770 } 771 } 772 Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes, 773 (double) mProfile.videoFrameWidth / mProfile.videoFrameHeight); 774 mDesiredPreviewWidth = optimalSize.width; 775 mDesiredPreviewHeight = optimalSize.height; 776 } 777 } else { 778 mDesiredPreviewWidth = mProfile.videoFrameWidth; 779 mDesiredPreviewHeight = mProfile.videoFrameHeight; 780 } 781 Log.v(TAG, "mDesiredPreviewWidth=" + mDesiredPreviewWidth + 782 ". mDesiredPreviewHeight=" + mDesiredPreviewHeight); 783 } 784 785 private void resizeForPreviewAspectRatio() { 786 mPreviewFrameLayout.setAspectRatio( 787 (double) mProfile.videoFrameWidth / mProfile.videoFrameHeight); 788 } 789 790 @Override 791 public void installIntentFilter() { 792 // install an intent filter to receive SD card related events. 793 IntentFilter intentFilter = 794 new IntentFilter(Intent.ACTION_MEDIA_EJECT); 795 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); 796 intentFilter.addDataScheme("file"); 797 mReceiver = new MyBroadcastReceiver(); 798 mActivity.registerReceiver(mReceiver, intentFilter); 799 } 800 801 @Override 802 public void onResumeBeforeSuper() { 803 mPaused = false; 804 } 805 806 @Override 807 public void onResumeAfterSuper() { 808 if (mActivity.mOpenCameraFail || mActivity.mCameraDisabled) 809 return; 810 811 mZoomValue = 0; 812 813 showVideoSnapshotUI(false); 814 815 // Start orientation listener as soon as possible because it takes 816 // some time to get first orientation. 817 mOrientationListener.enable(); 818 if (!mPreviewing) { 819 if (resetEffect()) { 820 mBgLearningMessageFrame.setVisibility(View.GONE); 821// mIndicatorControlContainer.reloadPreferences(); 822 } 823 CameraOpenThread cameraOpenThread = new CameraOpenThread(); 824 cameraOpenThread.start(); 825 try { 826 cameraOpenThread.join(); 827 if (mActivity.mOpenCameraFail) { 828 Util.showErrorAndFinish(mActivity, 829 R.string.cannot_connect_camera); 830 return; 831 } else if (mActivity.mCameraDisabled) { 832 Util.showErrorAndFinish(mActivity, R.string.camera_disabled); 833 return; 834 } 835 } catch (InterruptedException ex) { 836 // ignore 837 } 838 839 readVideoPreferences(); 840 resizeForPreviewAspectRatio(); 841 startPreview(); 842 } 843 844 // Initializing it here after the preview is started. 845 initializeZoom(); 846 847 keepScreenOnAwhile(); 848 849 // Initialize location service. 850 boolean recordLocation = RecordLocationPreference.get(mPreferences, 851 mContentResolver); 852 mLocationManager.recordLocation(recordLocation); 853 854 if (!mIsVideoCaptureIntent) { 855 mActivity.getLastThumbnail(); 856 } 857 858 if (mPreviewing) { 859 mOnResumeTime = SystemClock.uptimeMillis(); 860 mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100); 861 } 862 // Dismiss open menu if exists. 863 PopupManager.getInstance(mActivity).notifyShowPopup(null); 864 865 mVideoNamer = new VideoNamer(); 866 } 867 868 private void setDisplayOrientation() { 869 mDisplayRotation = Util.getDisplayRotation(mActivity); 870 if (ApiHelper.HAS_SURFACE_TEXTURE) { 871 // The display rotation is handled by gallery. 872 mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId); 873 } else { 874 // We need to consider display rotation ourselves. 875 mCameraDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId); 876 } 877 } 878 879 private void startPreview() { 880 Log.v(TAG, "startPreview"); 881 882 mActivity.mCameraDevice.setErrorCallback(mErrorCallback); 883 if (mPreviewing == true) { 884 stopPreview(); 885 if (effectsActive() && mEffectsRecorder != null) { 886 mEffectsRecorder.release(); 887 mEffectsRecorder = null; 888 } 889 } 890 891 setDisplayOrientation(); 892 mActivity.mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation); 893 setCameraParameters(); 894 895 try { 896 if (!effectsActive()) { 897 if (ApiHelper.HAS_SURFACE_TEXTURE) { 898 mActivity.mCameraDevice.setPreviewTextureAsync( 899 ((CameraScreenNail) mActivity.mCameraScreenNail).getSurfaceTexture()); 900 } else { 901 mActivity.mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder()); 902 } 903 mActivity.mCameraDevice.startPreviewAsync(); 904 } else { 905 initializeEffectsPreview(); 906 mEffectsRecorder.startPreview(); 907 } 908 } catch (Throwable ex) { 909 closeCamera(); 910 throw new RuntimeException("startPreview failed", ex); 911 } 912 913 mPreviewing = true; 914 } 915 916 private void stopPreview() { 917 mActivity.mCameraDevice.stopPreview(); 918 mPreviewing = false; 919 } 920 921 // Closing the effects out. Will shut down the effects graph. 922 private void closeEffects() { 923 Log.v(TAG, "Closing effects"); 924 mEffectType = EffectsRecorder.EFFECT_NONE; 925 if (mEffectsRecorder == null) { 926 Log.d(TAG, "Effects are already closed. Nothing to do"); 927 return; 928 } 929 // This call can handle the case where the camera is already released 930 // after the recording has been stopped. 931 mEffectsRecorder.release(); 932 mEffectsRecorder = null; 933 } 934 935 // By default, we want to close the effects as well with the camera. 936 private void closeCamera() { 937 closeCamera(true); 938 } 939 940 // In certain cases, when the effects are active, we may want to shutdown 941 // only the camera related parts, and handle closing the effects in the 942 // effectsUpdate callback. 943 // For example, in onPause, we want to make the camera available to 944 // outside world immediately, however, want to wait till the effects 945 // callback to shut down the effects. In such a case, we just disconnect 946 // the effects from the camera by calling disconnectCamera. That way 947 // the effects can handle that when shutting down. 948 // 949 // @param closeEffectsAlso - indicates whether we want to close the 950 // effects also along with the camera. 951 private void closeCamera(boolean closeEffectsAlso) { 952 Log.v(TAG, "closeCamera"); 953 if (mActivity.mCameraDevice == null) { 954 Log.d(TAG, "already stopped."); 955 return; 956 } 957 958 if (mEffectsRecorder != null) { 959 // Disconnect the camera from effects so that camera is ready to 960 // be released to the outside world. 961 mEffectsRecorder.disconnectCamera(); 962 } 963 if (closeEffectsAlso) closeEffects(); 964 mActivity.mCameraDevice.setZoomChangeListener(null); 965 mActivity.mCameraDevice.setErrorCallback(null); 966 CameraHolder.instance().release(); 967 mActivity.mCameraDevice = null; 968 mPreviewing = false; 969 mSnapshotInProgress = false; 970 } 971 972 private void releasePreviewResources() { 973 if (ApiHelper.HAS_SURFACE_TEXTURE) { 974 CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; 975 if (screenNail.getSurfaceTexture() != null) { 976 screenNail.releaseSurfaceTexture(); 977 } 978 if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { 979 mHandler.removeMessages(HIDE_SURFACE_VIEW); 980 mPreviewSurfaceView.setVisibility(View.GONE); 981 } 982 } 983 } 984 985 @Override 986 public void onPauseBeforeSuper() { 987 mPaused = true; 988 989 if (mMediaRecorderRecording) { 990 // Camera will be released in onStopVideoRecording. 991 onStopVideoRecording(); 992 } else { 993 closeCamera(); 994 if (!effectsActive()) releaseMediaRecorder(); 995 } 996 if (effectsActive()) { 997 // If the effects are active, make sure we tell the graph that the 998 // surfacetexture is not valid anymore. Disconnect the graph from 999 // the display. This should be done before releasing the surface 1000 // texture. 1001 mEffectsRecorder.disconnectDisplay(); 1002 } else { 1003 // Close the file descriptor and clear the video namer only if the 1004 // effects are not active. If effects are active, we need to wait 1005 // till we get the callback from the Effects that the graph is done 1006 // recording. That also needs a change in the stopVideoRecording() 1007 // call to not call closeCamera if the effects are active, because 1008 // that will close down the effects are well, thus making this if 1009 // condition invalid. 1010 closeVideoFileDescriptor(); 1011 clearVideoNamer(); 1012 } 1013 1014 releasePreviewResources(); 1015 1016 if (mReceiver != null) { 1017 mActivity.unregisterReceiver(mReceiver); 1018 mReceiver = null; 1019 } 1020 resetScreenOn(); 1021 1022 if (mOrientationListener != null) mOrientationListener.disable(); 1023 if (mLocationManager != null) mLocationManager.recordLocation(false); 1024 1025 mHandler.removeMessages(CHECK_DISPLAY_ROTATION); 1026 mHandler.removeMessages(SWITCH_CAMERA); 1027 mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION); 1028 mActivity.mPendingSwitchCameraId = -1; 1029 mSwitchingCamera = false; 1030 // Call onPause after stopping video recording. So the camera can be 1031 // released as soon as possible. 1032 } 1033 1034 @Override 1035 public void onPauseAfterSuper() { 1036 } 1037 1038 @Override 1039 public void onUserInteraction() { 1040 if (!mMediaRecorderRecording && !mActivity.isFinishing()) { 1041 keepScreenOnAwhile(); 1042 } 1043 } 1044 1045 @Override 1046 public boolean onBackPressed() { 1047 if (mPaused) return true; 1048 if (mMediaRecorderRecording) { 1049 onStopVideoRecording(); 1050 return true; 1051 } else { 1052 return collapseCameraControls(); 1053 } 1054 } 1055 1056 @Override 1057 public boolean onKeyDown(int keyCode, KeyEvent event) { 1058 // Do not handle any key if the activity is paused. 1059 if (mPaused) { 1060 return true; 1061 } 1062 1063 switch (keyCode) { 1064 case KeyEvent.KEYCODE_CAMERA: 1065 if (event.getRepeatCount() == 0) { 1066 mShutterButton.performClick(); 1067 return true; 1068 } 1069 break; 1070 case KeyEvent.KEYCODE_DPAD_CENTER: 1071 if (event.getRepeatCount() == 0) { 1072 mShutterButton.performClick(); 1073 return true; 1074 } 1075 break; 1076 case KeyEvent.KEYCODE_MENU: 1077 if (mMediaRecorderRecording) return true; 1078 break; 1079 } 1080 return false; 1081 } 1082 1083 @Override 1084 public boolean onKeyUp(int keyCode, KeyEvent event) { 1085 switch (keyCode) { 1086 case KeyEvent.KEYCODE_CAMERA: 1087 mShutterButton.setPressed(false); 1088 return true; 1089 } 1090 return false; 1091 } 1092 1093 private boolean isVideoCaptureIntent() { 1094 String action = mActivity.getIntent().getAction(); 1095 return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); 1096 } 1097 1098 private void doReturnToCaller(boolean valid) { 1099 Intent resultIntent = new Intent(); 1100 int resultCode; 1101 if (valid) { 1102 resultCode = Activity.RESULT_OK; 1103 resultIntent.setData(mCurrentVideoUri); 1104 } else { 1105 resultCode = Activity.RESULT_CANCELED; 1106 } 1107 mActivity.setResultEx(resultCode, resultIntent); 1108 mActivity.finish(); 1109 } 1110 1111 private void cleanupEmptyFile() { 1112 if (mVideoFilename != null) { 1113 File f = new File(mVideoFilename); 1114 if (f.length() == 0 && f.delete()) { 1115 Log.v(TAG, "Empty video file deleted: " + mVideoFilename); 1116 mVideoFilename = null; 1117 } 1118 } 1119 } 1120 1121 private void setupMediaRecorderPreviewDisplay() { 1122 // Nothing to do here if using SurfaceTexture. 1123 if (!ApiHelper.HAS_SURFACE_TEXTURE) { 1124 mMediaRecorder.setPreviewDisplay(mPreviewSurfaceView.getHolder().getSurface()); 1125 } else if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { 1126 // We stop the preview here before unlocking the device because we 1127 // need to change the SurfaceTexture to SurfaceView for preview. 1128 stopPreview(); 1129 mActivity.mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder()); 1130 // The orientation for SurfaceTexture is different from that for 1131 // SurfaceView. For SurfaceTexture we don't need to consider the 1132 // display rotation. Just consider the sensor's orientation and we 1133 // will set the orientation correctly when showing the texture. 1134 // Gallery will handle the orientation for the preview. For 1135 // SurfaceView we will have to take everything into account so the 1136 // display rotation is considered. 1137 mActivity.mCameraDevice.setDisplayOrientation( 1138 Util.getDisplayOrientation(mDisplayRotation, mCameraId)); 1139 mActivity.mCameraDevice.startPreviewAsync(); 1140 mPreviewing = true; 1141 mMediaRecorder.setPreviewDisplay(mPreviewSurfaceView.getHolder().getSurface()); 1142 } 1143 } 1144 1145 // Prepares media recorder. 1146 private void initializeRecorder() { 1147 Log.v(TAG, "initializeRecorder"); 1148 // If the mCameraDevice is null, then this activity is going to finish 1149 if (mActivity.mCameraDevice == null) return; 1150 1151 if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING && ApiHelper.HAS_SURFACE_TEXTURE) { 1152 // Set the SurfaceView to visible so the surface gets created. 1153 // surfaceCreated() is called immediately when the visibility is 1154 // changed to visible. Thus, mSurfaceViewReady should become true 1155 // right after calling setVisibility(). 1156 mPreviewSurfaceView.setVisibility(View.VISIBLE); 1157 if (!mSurfaceViewReady) return; 1158 } 1159 1160 Intent intent = mActivity.getIntent(); 1161 Bundle myExtras = intent.getExtras(); 1162 1163 long requestedSizeLimit = 0; 1164 closeVideoFileDescriptor(); 1165 if (mIsVideoCaptureIntent && myExtras != null) { 1166 Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 1167 if (saveUri != null) { 1168 try { 1169 mVideoFileDescriptor = 1170 mContentResolver.openFileDescriptor(saveUri, "rw"); 1171 mCurrentVideoUri = saveUri; 1172 } catch (java.io.FileNotFoundException ex) { 1173 // invalid uri 1174 Log.e(TAG, ex.toString()); 1175 } 1176 } 1177 requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT); 1178 } 1179 mMediaRecorder = new MediaRecorder(); 1180 1181 setupMediaRecorderPreviewDisplay(); 1182 // Unlock the camera object before passing it to media recorder. 1183 mActivity.mCameraDevice.unlock(); 1184 mMediaRecorder.setCamera(mActivity.mCameraDevice.getCamera()); 1185 if (!mCaptureTimeLapse) { 1186 mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); 1187 } 1188 mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); 1189 mMediaRecorder.setProfile(mProfile); 1190 mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs); 1191 if (mCaptureTimeLapse) { 1192 double fps = 1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs; 1193 setCaptureRate(mMediaRecorder, fps); 1194 } 1195 1196 setRecordLocation(); 1197 1198 // Set output file. 1199 // Try Uri in the intent first. If it doesn't exist, use our own 1200 // instead. 1201 if (mVideoFileDescriptor != null) { 1202 mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor()); 1203 } else { 1204 generateVideoFilename(mProfile.fileFormat); 1205 mMediaRecorder.setOutputFile(mVideoFilename); 1206 } 1207 1208 // Set maximum file size. 1209 long maxFileSize = mActivity.getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD; 1210 if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) { 1211 maxFileSize = requestedSizeLimit; 1212 } 1213 1214 try { 1215 mMediaRecorder.setMaxFileSize(maxFileSize); 1216 } catch (RuntimeException exception) { 1217 // We are going to ignore failure of setMaxFileSize here, as 1218 // a) The composer selected may simply not support it, or 1219 // b) The underlying media framework may not handle 64-bit range 1220 // on the size restriction. 1221 } 1222 1223 // See android.hardware.Camera.Parameters.setRotation for 1224 // documentation. 1225 // Note that mOrientation here is the device orientation, which is the opposite of 1226 // what activity.getWindowManager().getDefaultDisplay().getRotation() would return, 1227 // which is the orientation the graphics need to rotate in order to render correctly. 1228 int rotation = 0; 1229 if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) { 1230 CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; 1231 if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 1232 rotation = (info.orientation - mOrientation + 360) % 360; 1233 } else { // back-facing camera 1234 rotation = (info.orientation + mOrientation) % 360; 1235 } 1236 } 1237 mMediaRecorder.setOrientationHint(rotation); 1238 mOrientationCompensationAtRecordStart = mOrientationCompensation; 1239 1240 try { 1241 mMediaRecorder.prepare(); 1242 } catch (IOException e) { 1243 Log.e(TAG, "prepare failed for " + mVideoFilename, e); 1244 releaseMediaRecorder(); 1245 throw new RuntimeException(e); 1246 } 1247 1248 mMediaRecorder.setOnErrorListener(this); 1249 mMediaRecorder.setOnInfoListener(this); 1250 } 1251 1252 @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) 1253 private static void setCaptureRate(MediaRecorder recorder, double fps) { 1254 recorder.setCaptureRate(fps); 1255 } 1256 1257 @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH) 1258 private void setRecordLocation() { 1259 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 1260 Location loc = mLocationManager.getCurrentLocation(); 1261 if (loc != null) { 1262 mMediaRecorder.setLocation((float) loc.getLatitude(), 1263 (float) loc.getLongitude()); 1264 } 1265 } 1266 } 1267 1268 private void initializeEffectsPreview() { 1269 Log.v(TAG, "initializeEffectsPreview"); 1270 // If the mCameraDevice is null, then this activity is going to finish 1271 if (mActivity.mCameraDevice == null) return; 1272 1273 boolean inLandscape = (mActivity.getResources().getConfiguration().orientation 1274 == Configuration.ORIENTATION_LANDSCAPE); 1275 1276 CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; 1277 1278 mEffectsDisplayResult = false; 1279 mEffectsRecorder = new EffectsRecorder(mActivity); 1280 1281 // TODO: Confirm none of the following need to go to initializeEffectsRecording() 1282 // and none of these change even when the preview is not refreshed. 1283 mEffectsRecorder.setCameraDisplayOrientation(mCameraDisplayOrientation); 1284 mEffectsRecorder.setCamera(mActivity.mCameraDevice); 1285 mEffectsRecorder.setCameraFacing(info.facing); 1286 mEffectsRecorder.setProfile(mProfile); 1287 mEffectsRecorder.setEffectsListener(this); 1288 mEffectsRecorder.setOnInfoListener(this); 1289 mEffectsRecorder.setOnErrorListener(this); 1290 1291 // The input of effects recorder is affected by 1292 // android.hardware.Camera.setDisplayOrientation. Its value only 1293 // compensates the camera orientation (no Display.getRotation). So the 1294 // orientation hint here should only consider sensor orientation. 1295 int orientation = 0; 1296 if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) { 1297 orientation = mOrientation; 1298 } 1299 mEffectsRecorder.setOrientationHint(orientation); 1300 1301 mOrientationCompensationAtRecordStart = mOrientationCompensation; 1302 1303 CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; 1304 mEffectsRecorder.setPreviewSurfaceTexture(screenNail.getSurfaceTexture(), 1305 screenNail.getWidth(), screenNail.getHeight()); 1306 1307 if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER && 1308 ((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) { 1309 mEffectsRecorder.setEffect(mEffectType, mEffectUriFromGallery); 1310 } else { 1311 mEffectsRecorder.setEffect(mEffectType, mEffectParameter); 1312 } 1313 } 1314 1315 private void initializeEffectsRecording() { 1316 Log.v(TAG, "initializeEffectsRecording"); 1317 1318 Intent intent = mActivity.getIntent(); 1319 Bundle myExtras = intent.getExtras(); 1320 1321 long requestedSizeLimit = 0; 1322 closeVideoFileDescriptor(); 1323 if (mIsVideoCaptureIntent && myExtras != null) { 1324 Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 1325 if (saveUri != null) { 1326 try { 1327 mVideoFileDescriptor = 1328 mContentResolver.openFileDescriptor(saveUri, "rw"); 1329 mCurrentVideoUri = saveUri; 1330 } catch (java.io.FileNotFoundException ex) { 1331 // invalid uri 1332 Log.e(TAG, ex.toString()); 1333 } 1334 } 1335 requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT); 1336 } 1337 1338 mEffectsRecorder.setProfile(mProfile); 1339 // important to set the capture rate to zero if not timelapsed, since the 1340 // effectsrecorder object does not get created again for each recording 1341 // session 1342 if (mCaptureTimeLapse) { 1343 mEffectsRecorder.setCaptureRate((1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs)); 1344 } else { 1345 mEffectsRecorder.setCaptureRate(0); 1346 } 1347 1348 // Set output file 1349 if (mVideoFileDescriptor != null) { 1350 mEffectsRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor()); 1351 } else { 1352 generateVideoFilename(mProfile.fileFormat); 1353 mEffectsRecorder.setOutputFile(mVideoFilename); 1354 } 1355 1356 // Set maximum file size. 1357 long maxFileSize = mActivity.getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD; 1358 if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) { 1359 maxFileSize = requestedSizeLimit; 1360 } 1361 mEffectsRecorder.setMaxFileSize(maxFileSize); 1362 mEffectsRecorder.setMaxDuration(mMaxVideoDurationInMs); 1363 } 1364 1365 1366 private void releaseMediaRecorder() { 1367 Log.v(TAG, "Releasing media recorder."); 1368 if (mMediaRecorder != null) { 1369 cleanupEmptyFile(); 1370 mMediaRecorder.reset(); 1371 mMediaRecorder.release(); 1372 mMediaRecorder = null; 1373 } 1374 mVideoFilename = null; 1375 } 1376 1377 private void releaseEffectsRecorder() { 1378 Log.v(TAG, "Releasing effects recorder."); 1379 if (mEffectsRecorder != null) { 1380 cleanupEmptyFile(); 1381 mEffectsRecorder.release(); 1382 mEffectsRecorder = null; 1383 } 1384 mEffectType = EffectsRecorder.EFFECT_NONE; 1385 mVideoFilename = null; 1386 } 1387 1388 private void generateVideoFilename(int outputFileFormat) { 1389 long dateTaken = System.currentTimeMillis(); 1390 String title = createName(dateTaken); 1391 // Used when emailing. 1392 String filename = title + convertOutputFormatToFileExt(outputFileFormat); 1393 String mime = convertOutputFormatToMimeType(outputFileFormat); 1394 String path = Storage.DIRECTORY + '/' + filename; 1395 String tmpPath = path + ".tmp"; 1396 mCurrentVideoValues = new ContentValues(7); 1397 mCurrentVideoValues.put(Video.Media.TITLE, title); 1398 mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename); 1399 mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken); 1400 mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime); 1401 mCurrentVideoValues.put(Video.Media.DATA, path); 1402 mCurrentVideoValues.put(Video.Media.RESOLUTION, 1403 Integer.toString(mProfile.videoFrameWidth) + "x" + 1404 Integer.toString(mProfile.videoFrameHeight)); 1405 Location loc = mLocationManager.getCurrentLocation(); 1406 if (loc != null) { 1407 mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude()); 1408 mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude()); 1409 } 1410 mVideoNamer.prepareUri(mContentResolver, mCurrentVideoValues); 1411 mVideoFilename = tmpPath; 1412 Log.v(TAG, "New video filename: " + mVideoFilename); 1413 } 1414 1415 private boolean addVideoToMediaStore() { 1416 boolean fail = false; 1417 if (mVideoFileDescriptor == null) { 1418 mCurrentVideoValues.put(Video.Media.SIZE, 1419 new File(mCurrentVideoFilename).length()); 1420 long duration = SystemClock.uptimeMillis() - mRecordingStartTime; 1421 if (duration > 0) { 1422 if (mCaptureTimeLapse) { 1423 duration = getTimeLapseVideoLength(duration); 1424 } 1425 mCurrentVideoValues.put(Video.Media.DURATION, duration); 1426 } else { 1427 Log.w(TAG, "Video duration <= 0 : " + duration); 1428 } 1429 try { 1430 mCurrentVideoUri = mVideoNamer.getUri(); 1431 mActivity.addSecureAlbumItemIfNeeded(true, mCurrentVideoUri); 1432 1433 // Rename the video file to the final name. This avoids other 1434 // apps reading incomplete data. We need to do it after the 1435 // above mVideoNamer.getUri() call, so we are certain that the 1436 // previous insert to MediaProvider is completed. 1437 String finalName = mCurrentVideoValues.getAsString( 1438 Video.Media.DATA); 1439 if (new File(mCurrentVideoFilename).renameTo(new File(finalName))) { 1440 mCurrentVideoFilename = finalName; 1441 } 1442 1443 mContentResolver.update(mCurrentVideoUri, mCurrentVideoValues 1444 , null, null); 1445 mActivity.sendBroadcast(new Intent(Util.ACTION_NEW_VIDEO, 1446 mCurrentVideoUri)); 1447 } catch (Exception e) { 1448 // We failed to insert into the database. This can happen if 1449 // the SD card is unmounted. 1450 Log.e(TAG, "failed to add video to media store", e); 1451 mCurrentVideoUri = null; 1452 mCurrentVideoFilename = null; 1453 fail = true; 1454 } finally { 1455 Log.v(TAG, "Current video URI: " + mCurrentVideoUri); 1456 } 1457 } 1458 mCurrentVideoValues = null; 1459 return fail; 1460 } 1461 1462 private void deleteCurrentVideo() { 1463 // Remove the video and the uri if the uri is not passed in by intent. 1464 if (mCurrentVideoFilename != null) { 1465 deleteVideoFile(mCurrentVideoFilename); 1466 mCurrentVideoFilename = null; 1467 if (mCurrentVideoUri != null) { 1468 mContentResolver.delete(mCurrentVideoUri, null, null); 1469 mCurrentVideoUri = null; 1470 } 1471 } 1472 mActivity.updateStorageSpaceAndHint(); 1473 } 1474 1475 private void deleteVideoFile(String fileName) { 1476 Log.v(TAG, "Deleting video " + fileName); 1477 File f = new File(fileName); 1478 if (!f.delete()) { 1479 Log.v(TAG, "Could not delete " + fileName); 1480 } 1481 } 1482 1483 private PreferenceGroup filterPreferenceScreenByIntent( 1484 PreferenceGroup screen) { 1485 Intent intent = mActivity.getIntent(); 1486 if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { 1487 CameraSettings.removePreferenceFromScreen(screen, 1488 CameraSettings.KEY_VIDEO_QUALITY); 1489 } 1490 1491 if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) { 1492 CameraSettings.removePreferenceFromScreen(screen, 1493 CameraSettings.KEY_VIDEO_QUALITY); 1494 } 1495 return screen; 1496 } 1497 1498 // from MediaRecorder.OnErrorListener 1499 @Override 1500 public void onError(MediaRecorder mr, int what, int extra) { 1501 Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra); 1502 if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { 1503 // We may have run out of space on the sdcard. 1504 stopVideoRecording(); 1505 mActivity.updateStorageSpaceAndHint(); 1506 } 1507 } 1508 1509 // from MediaRecorder.OnInfoListener 1510 @Override 1511 public void onInfo(MediaRecorder mr, int what, int extra) { 1512 if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { 1513 if (mMediaRecorderRecording) onStopVideoRecording(); 1514 } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { 1515 if (mMediaRecorderRecording) onStopVideoRecording(); 1516 1517 // Show the toast. 1518 Toast.makeText(mActivity, R.string.video_reach_size_limit, 1519 Toast.LENGTH_LONG).show(); 1520 } 1521 } 1522 1523 /* 1524 * Make sure we're not recording music playing in the background, ask the 1525 * MediaPlaybackService to pause playback. 1526 */ 1527 private void pauseAudioPlayback() { 1528 // Shamelessly copied from MediaPlaybackService.java, which 1529 // should be public, but isn't. 1530 Intent i = new Intent("com.android.music.musicservicecommand"); 1531 i.putExtra("command", "pause"); 1532 1533 mActivity.sendBroadcast(i); 1534 } 1535 1536 // For testing. 1537 public boolean isRecording() { 1538 return mMediaRecorderRecording; 1539 } 1540 1541 private void startVideoRecording() { 1542 Log.v(TAG, "startVideoRecording"); 1543 mActivity.setSwipingEnabled(false); 1544 mActivity.hideSwitcher(); 1545 1546 mActivity.updateStorageSpaceAndHint(); 1547 if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) { 1548 Log.v(TAG, "Storage issue, ignore the start request"); 1549 return; 1550 } 1551 1552 mCurrentVideoUri = null; 1553 if (effectsActive()) { 1554 initializeEffectsRecording(); 1555 if (mEffectsRecorder == null) { 1556 Log.e(TAG, "Fail to initialize effect recorder"); 1557 return; 1558 } 1559 } else { 1560 initializeRecorder(); 1561 if (mMediaRecorder == null) { 1562 Log.e(TAG, "Fail to initialize media recorder"); 1563 return; 1564 } 1565 } 1566 1567 pauseAudioPlayback(); 1568 1569 if (effectsActive()) { 1570 try { 1571 mEffectsRecorder.startRecording(); 1572 } catch (RuntimeException e) { 1573 Log.e(TAG, "Could not start effects recorder. ", e); 1574 releaseEffectsRecorder(); 1575 return; 1576 } 1577 } else { 1578 try { 1579 mMediaRecorder.start(); // Recording is now started 1580 } catch (RuntimeException e) { 1581 Log.e(TAG, "Could not start media recorder. ", e); 1582 releaseMediaRecorder(); 1583 // If start fails, frameworks will not lock the camera for us. 1584 mActivity.mCameraDevice.lock(); 1585 return; 1586 } 1587 } 1588 1589 // The parameters may have been changed by MediaRecorder upon starting 1590 // recording. We need to alter the parameters if we support camcorder 1591 // zoom. To reduce latency when setting the parameters during zoom, we 1592 // update mParameters here once. 1593 if (ApiHelper.HAS_ZOOM_WHEN_RECORDING) { 1594 mParameters = mActivity.mCameraDevice.getParameters(); 1595 } 1596 1597 enableCameraControls(false); 1598 1599 mMediaRecorderRecording = true; 1600 mRecordingStartTime = SystemClock.uptimeMillis(); 1601 showRecordingUI(true); 1602 1603 updateRecordingTime(); 1604 keepScreenOn(); 1605 } 1606 1607 private void showRecordingUI(boolean recording) { 1608 if (recording) { 1609 if (mActivity.mThumbnailView != null) mActivity.mThumbnailView.setEnabled(false); 1610// mShutterButton.setImageResource(R.drawable.btn_shutter_video_recording); 1611 mRecordingTimeView.setText(""); 1612 mRecordingTimeView.setVisibility(View.VISIBLE); 1613 if (mReviewControl != null) mReviewControl.setVisibility(View.GONE); 1614 if (mCaptureTimeLapse) { 1615// mIndicatorControlContainer.startTimeLapseAnimation( 1616// mTimeBetweenTimeLapseFrameCaptureMs, 1617// mRecordingStartTime); 1618 } 1619 // The camera is not allowed to be accessed in older api levels during 1620 // recording. It is therefore necessary to hide the zoom UI on older 1621 // platforms. 1622 // See the documentation of android.media.MediaRecorder.start() for 1623 // further explanation. 1624 if (!ApiHelper.HAS_ZOOM_WHEN_RECORDING 1625 && mParameters.isZoomSupported()) { 1626// mZoomControl.setVisibility(View.GONE); 1627 } 1628 } else { 1629 if (mActivity.mThumbnailView != null) mActivity.mThumbnailView.setEnabled(true); 1630// mShutterButton.setImageResource(R.drawable.btn_shutter_video); 1631 mRecordingTimeView.setVisibility(View.GONE); 1632 if (mReviewControl != null) mReviewControl.setVisibility(View.VISIBLE); 1633 if (mCaptureTimeLapse) { 1634// mIndicatorControlContainer.stopTimeLapseAnimation(); 1635 } 1636 if (!ApiHelper.HAS_ZOOM_WHEN_RECORDING 1637 && mParameters.isZoomSupported()) { 1638// mZoomControl.setVisibility(View.VISIBLE); 1639 } 1640 } 1641 mShutterButton.setActivated(recording); 1642 } 1643 1644 private void getThumbnail() { 1645 if (mCurrentVideoUri != null) { 1646 Bitmap videoFrame = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename, 1647 Math.max(mActivity.mThumbnailViewWidth, MIN_THUMB_SIZE)); 1648 if (videoFrame != null) { 1649 mActivity.mThumbnail = Thumbnail.createThumbnail(mCurrentVideoUri, videoFrame, 0); 1650 if (mActivity.mThumbnailView != null) { 1651 mActivity.mThumbnailView.setBitmap(mActivity.mThumbnail.getBitmap()); 1652 } 1653 } 1654 } 1655 } 1656 1657 private void showAlert() { 1658 Bitmap bitmap = null; 1659 if (mVideoFileDescriptor != null) { 1660 bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(), 1661 mPreviewFrameLayout.getWidth()); 1662 } else if (mCurrentVideoFilename != null) { 1663 bitmap = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename, 1664 mPreviewFrameLayout.getWidth()); 1665 } 1666 if (bitmap != null) { 1667 // MetadataRetriever already rotates the thumbnail. We should rotate 1668 // it to match the UI orientation (and mirror if it is front-facing camera). 1669 CameraInfo[] info = CameraHolder.instance().getCameraInfo(); 1670 boolean mirror = (info[mCameraId].facing == CameraInfo.CAMERA_FACING_FRONT); 1671 bitmap = Util.rotateAndMirror(bitmap, -mOrientationCompensationAtRecordStart, 1672 mirror); 1673 mReviewImage.setImageBitmap(bitmap); 1674 mReviewImage.setVisibility(View.VISIBLE); 1675 } 1676 1677 Util.fadeOut(mShutterButton); 1678 1679 Util.fadeIn(mReviewRetakeButton); 1680 Util.fadeIn((View) mReviewDoneButton); 1681 Util.fadeIn(mReviewPlayButton); 1682 1683 showTimeLapseUI(false); 1684 } 1685 1686 private void hideAlert() { 1687 mReviewImage.setVisibility(View.GONE); 1688 mShutterButton.setEnabled(true); 1689 enableCameraControls(true); 1690 1691 Util.fadeOut((View) mReviewDoneButton); 1692 Util.fadeOut(mReviewRetakeButton); 1693 Util.fadeOut(mReviewPlayButton); 1694 1695 Util.fadeIn(mShutterButton); 1696 1697 if (mCaptureTimeLapse) { 1698 showTimeLapseUI(true); 1699 } 1700 } 1701 1702 private boolean stopVideoRecording() { 1703 Log.v(TAG, "stopVideoRecording"); 1704 mActivity.setSwipingEnabled(true); 1705 mActivity.showSwitcher(); 1706 1707 boolean fail = false; 1708 if (mMediaRecorderRecording) { 1709 boolean shouldAddToMediaStoreNow = false; 1710 1711 try { 1712 if (effectsActive()) { 1713 // This is asynchronous, so we can't add to media store now because thumbnail 1714 // may not be ready. In such case addVideoToMediaStore is called later 1715 // through a callback from the MediaEncoderFilter to EffectsRecorder, 1716 // and then to the VideoCamera. 1717 mEffectsRecorder.stopRecording(); 1718 } else { 1719 mMediaRecorder.setOnErrorListener(null); 1720 mMediaRecorder.setOnInfoListener(null); 1721 mMediaRecorder.stop(); 1722 shouldAddToMediaStoreNow = true; 1723 } 1724 mCurrentVideoFilename = mVideoFilename; 1725 Log.v(TAG, "stopVideoRecording: Setting current video filename: " 1726 + mCurrentVideoFilename); 1727 } catch (RuntimeException e) { 1728 Log.e(TAG, "stop fail", e); 1729 if (mVideoFilename != null) deleteVideoFile(mVideoFilename); 1730 fail = true; 1731 } 1732 mMediaRecorderRecording = false; 1733 1734 // If the activity is paused, this means activity is interrupted 1735 // during recording. Release the camera as soon as possible because 1736 // face unlock or other applications may need to use the camera. 1737 // However, if the effects are active, then we can only release the 1738 // camera and cannot release the effects recorder since that will 1739 // stop the graph. It is possible to separate out the Camera release 1740 // part and the effects release part. However, the effects recorder 1741 // does hold on to the camera, hence, it needs to be "disconnected" 1742 // from the camera in the closeCamera call. 1743 if (mPaused) { 1744 // Closing only the camera part if effects active. Effects will 1745 // be closed in the callback from effects. 1746 boolean closeEffects = !effectsActive(); 1747 closeCamera(closeEffects); 1748 } 1749 1750 showRecordingUI(false); 1751 if (!mIsVideoCaptureIntent) { 1752 enableCameraControls(true); 1753 } 1754 // The orientation was fixed during video recording. Now make it 1755 // reflect the device orientation as video recording is stopped. 1756 setOrientationIndicator(mOrientationCompensation, true); 1757 keepScreenOnAwhile(); 1758 if (shouldAddToMediaStoreNow) { 1759 if (addVideoToMediaStore()) fail = true; 1760 } 1761 } 1762 // always release media recorder if no effects running 1763 if (!effectsActive()) { 1764 releaseMediaRecorder(); 1765 if (!mPaused) { 1766 mActivity.mCameraDevice.lock(); 1767 if (ApiHelper.HAS_SURFACE_TEXTURE && 1768 !ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { 1769 stopPreview(); 1770 // Switch back to use SurfaceTexture for preview. 1771 ((CameraScreenNail) mActivity.mCameraScreenNail).setOneTimeOnFrameDrawnListener( 1772 mFrameDrawnListener); 1773 startPreview(); 1774 } 1775 } 1776 } 1777 // Update the parameters here because the parameters might have been altered 1778 // by MediaRecorder. 1779 if (!mPaused) mParameters = mActivity.mCameraDevice.getParameters(); 1780 return fail; 1781 } 1782 1783 private void resetScreenOn() { 1784 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 1785 mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1786 } 1787 1788 private void keepScreenOnAwhile() { 1789 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 1790 mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1791 mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); 1792 } 1793 1794 private void keepScreenOn() { 1795 mHandler.removeMessages(CLEAR_SCREEN_DELAY); 1796 mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1797 } 1798 1799 private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) { 1800 long seconds = milliSeconds / 1000; // round down to compute seconds 1801 long minutes = seconds / 60; 1802 long hours = minutes / 60; 1803 long remainderMinutes = minutes - (hours * 60); 1804 long remainderSeconds = seconds - (minutes * 60); 1805 1806 StringBuilder timeStringBuilder = new StringBuilder(); 1807 1808 // Hours 1809 if (hours > 0) { 1810 if (hours < 10) { 1811 timeStringBuilder.append('0'); 1812 } 1813 timeStringBuilder.append(hours); 1814 1815 timeStringBuilder.append(':'); 1816 } 1817 1818 // Minutes 1819 if (remainderMinutes < 10) { 1820 timeStringBuilder.append('0'); 1821 } 1822 timeStringBuilder.append(remainderMinutes); 1823 timeStringBuilder.append(':'); 1824 1825 // Seconds 1826 if (remainderSeconds < 10) { 1827 timeStringBuilder.append('0'); 1828 } 1829 timeStringBuilder.append(remainderSeconds); 1830 1831 // Centi seconds 1832 if (displayCentiSeconds) { 1833 timeStringBuilder.append('.'); 1834 long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10; 1835 if (remainderCentiSeconds < 10) { 1836 timeStringBuilder.append('0'); 1837 } 1838 timeStringBuilder.append(remainderCentiSeconds); 1839 } 1840 1841 return timeStringBuilder.toString(); 1842 } 1843 1844 private long getTimeLapseVideoLength(long deltaMs) { 1845 // For better approximation calculate fractional number of frames captured. 1846 // This will update the video time at a higher resolution. 1847 double numberOfFrames = (double) deltaMs / mTimeBetweenTimeLapseFrameCaptureMs; 1848 return (long) (numberOfFrames / mProfile.videoFrameRate * 1000); 1849 } 1850 1851 private void updateRecordingTime() { 1852 if (!mMediaRecorderRecording) { 1853 return; 1854 } 1855 long now = SystemClock.uptimeMillis(); 1856 long delta = now - mRecordingStartTime; 1857 1858 // Starting a minute before reaching the max duration 1859 // limit, we'll countdown the remaining time instead. 1860 boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0 1861 && delta >= mMaxVideoDurationInMs - 60000); 1862 1863 long deltaAdjusted = delta; 1864 if (countdownRemainingTime) { 1865 deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999; 1866 } 1867 String text; 1868 1869 long targetNextUpdateDelay; 1870 if (!mCaptureTimeLapse) { 1871 text = millisecondToTimeString(deltaAdjusted, false); 1872 targetNextUpdateDelay = 1000; 1873 } else { 1874 // The length of time lapse video is different from the length 1875 // of the actual wall clock time elapsed. Display the video length 1876 // only in format hh:mm:ss.dd, where dd are the centi seconds. 1877 text = millisecondToTimeString(getTimeLapseVideoLength(delta), true); 1878 targetNextUpdateDelay = mTimeBetweenTimeLapseFrameCaptureMs; 1879 } 1880 1881 mRecordingTimeView.setText(text); 1882 1883 if (mRecordingTimeCountsDown != countdownRemainingTime) { 1884 // Avoid setting the color on every update, do it only 1885 // when it needs changing. 1886 mRecordingTimeCountsDown = countdownRemainingTime; 1887 1888 int color = mActivity.getResources().getColor(countdownRemainingTime 1889 ? R.color.recording_time_remaining_text 1890 : R.color.recording_time_elapsed_text); 1891 1892 mRecordingTimeView.setTextColor(color); 1893 } 1894 1895 long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay); 1896 mHandler.sendEmptyMessageDelayed( 1897 UPDATE_RECORD_TIME, actualNextUpdateDelay); 1898 } 1899 1900 private static boolean isSupported(String value, List<String> supported) { 1901 return supported == null ? false : supported.indexOf(value) >= 0; 1902 } 1903 1904 @SuppressWarnings("deprecation") 1905 private void setCameraParameters() { 1906 mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight); 1907 mParameters.setPreviewFrameRate(mProfile.videoFrameRate); 1908 1909 // Set flash mode. 1910 String flashMode; 1911 if (mActivity.mShowCameraAppView) { 1912 flashMode = mPreferences.getString( 1913 CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE, 1914 mActivity.getString(R.string.pref_camera_video_flashmode_default)); 1915 } else { 1916 flashMode = Parameters.FLASH_MODE_OFF; 1917 } 1918 List<String> supportedFlash = mParameters.getSupportedFlashModes(); 1919 if (isSupported(flashMode, supportedFlash)) { 1920 mParameters.setFlashMode(flashMode); 1921 } else { 1922 flashMode = mParameters.getFlashMode(); 1923 if (flashMode == null) { 1924 flashMode = mActivity.getString( 1925 R.string.pref_camera_flashmode_no_flash); 1926 } 1927 } 1928 1929 // Set white balance parameter. 1930 String whiteBalance = mPreferences.getString( 1931 CameraSettings.KEY_WHITE_BALANCE, 1932 mActivity.getString(R.string.pref_camera_whitebalance_default)); 1933 if (isSupported(whiteBalance, 1934 mParameters.getSupportedWhiteBalance())) { 1935 mParameters.setWhiteBalance(whiteBalance); 1936 } else { 1937 whiteBalance = mParameters.getWhiteBalance(); 1938 if (whiteBalance == null) { 1939 whiteBalance = Parameters.WHITE_BALANCE_AUTO; 1940 } 1941 } 1942 1943 // Set zoom. 1944 if (mParameters.isZoomSupported()) { 1945 mParameters.setZoom(mZoomValue); 1946 } 1947 1948 // Set continuous autofocus. 1949 List<String> supportedFocus = mParameters.getSupportedFocusModes(); 1950 if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) { 1951 mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); 1952 } 1953 1954 mParameters.set(Util.RECORDING_HINT, Util.TRUE); 1955 1956 // Enable video stabilization. Convenience methods not available in API 1957 // level <= 14 1958 String vstabSupported = mParameters.get("video-stabilization-supported"); 1959 if ("true".equals(vstabSupported)) { 1960 mParameters.set("video-stabilization", "true"); 1961 } 1962 1963 // Set picture size. 1964 // The logic here is different from the logic in still-mode camera. 1965 // There we determine the preview size based on the picture size, but 1966 // here we determine the picture size based on the preview size. 1967 List<Size> supported = mParameters.getSupportedPictureSizes(); 1968 Size optimalSize = Util.getOptimalVideoSnapshotPictureSize(supported, 1969 (double) mDesiredPreviewWidth / mDesiredPreviewHeight); 1970 Size original = mParameters.getPictureSize(); 1971 if (!original.equals(optimalSize)) { 1972 mParameters.setPictureSize(optimalSize.width, optimalSize.height); 1973 } 1974 Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" + 1975 optimalSize.height); 1976 1977 // Set JPEG quality. 1978 int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, 1979 CameraProfile.QUALITY_HIGH); 1980 mParameters.setJpegQuality(jpegQuality); 1981 1982 mActivity.mCameraDevice.setParameters(mParameters); 1983 // Keep preview size up to date. 1984 mParameters = mActivity.mCameraDevice.getParameters(); 1985 1986 updateCameraScreenNailSize(mDesiredPreviewWidth, mDesiredPreviewHeight); 1987 } 1988 1989 private void updateCameraScreenNailSize(int width, int height) { 1990 if (!ApiHelper.HAS_SURFACE_TEXTURE) return; 1991 1992 if (mCameraDisplayOrientation % 180 != 0) { 1993 int tmp = width; 1994 width = height; 1995 height = tmp; 1996 } 1997 1998 CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; 1999 int oldWidth = screenNail.getWidth(); 2000 int oldHeight = screenNail.getHeight(); 2001 2002 if (oldWidth != width || oldHeight != height) { 2003 screenNail.setSize(width, height); 2004 mActivity.notifyScreenNailChanged(); 2005 } 2006 2007 if (screenNail.getSurfaceTexture() == null) { 2008 screenNail.acquireSurfaceTexture(); 2009 } 2010 } 2011 2012 @Override 2013 public void onActivityResult(int requestCode, int resultCode, Intent data) { 2014 switch (requestCode) { 2015 case REQUEST_EFFECT_BACKDROPPER: 2016 if (resultCode == Activity.RESULT_OK) { 2017 // onActivityResult() runs before onResume(), so this parameter will be 2018 // seen by startPreview from onResume() 2019 mEffectUriFromGallery = data.getData().toString(); 2020 Log.v(TAG, "Received URI from gallery: " + mEffectUriFromGallery); 2021 mResetEffect = false; 2022 } else { 2023 mEffectUriFromGallery = null; 2024 Log.w(TAG, "No URI from gallery"); 2025 mResetEffect = true; 2026 } 2027 break; 2028 } 2029 } 2030 2031 @Override 2032 public void onEffectsUpdate(int effectId, int effectMsg) { 2033 Log.v(TAG, "onEffectsUpdate. Effect Message = " + effectMsg); 2034 if (effectMsg == EffectsRecorder.EFFECT_MSG_EFFECTS_STOPPED) { 2035 // Effects have shut down. Hide learning message if any, 2036 // and restart regular preview. 2037 mBgLearningMessageFrame.setVisibility(View.GONE); 2038 checkQualityAndStartPreview(); 2039 } else if (effectMsg == EffectsRecorder.EFFECT_MSG_RECORDING_DONE) { 2040 // This follows the codepath from onStopVideoRecording. 2041 if (mEffectsDisplayResult && !addVideoToMediaStore()) { 2042 if (mIsVideoCaptureIntent) { 2043 if (mQuickCapture) { 2044 doReturnToCaller(true); 2045 } else { 2046 showAlert(); 2047 } 2048 } else { 2049 getThumbnail(); 2050 } 2051 } 2052 mEffectsDisplayResult = false; 2053 // In onPause, these were not called if the effects were active. We 2054 // had to wait till the effects recording is complete to do this. 2055 if (mPaused) { 2056 closeVideoFileDescriptor(); 2057 clearVideoNamer(); 2058 } 2059 } else if (effectMsg == EffectsRecorder.EFFECT_MSG_PREVIEW_RUNNING) { 2060 // Enable the shutter button once the preview is complete. 2061 mShutterButton.setEnabled(true); 2062 } else if (effectId == EffectsRecorder.EFFECT_BACKDROPPER) { 2063 switch (effectMsg) { 2064 case EffectsRecorder.EFFECT_MSG_STARTED_LEARNING: 2065 mBgLearningMessageFrame.setVisibility(View.VISIBLE); 2066 break; 2067 case EffectsRecorder.EFFECT_MSG_DONE_LEARNING: 2068 case EffectsRecorder.EFFECT_MSG_SWITCHING_EFFECT: 2069 mBgLearningMessageFrame.setVisibility(View.GONE); 2070 break; 2071 } 2072 } 2073 // In onPause, this was not called if the effects were active. We had to 2074 // wait till the effects completed to do this. 2075 if (mPaused) { 2076 Log.v(TAG, "OnEffectsUpdate: closing effects if activity paused"); 2077 closeEffects(); 2078 } 2079 } 2080 2081 public void onCancelBgTraining(View v) { 2082 // Remove training message 2083 mBgLearningMessageFrame.setVisibility(View.GONE); 2084 // Write default effect out to shared prefs 2085 writeDefaultEffectToPrefs(); 2086 // Tell the indicator controller to redraw based on new shared pref values 2087// mIndicatorControlContainer.reloadPreferences(); 2088 // Tell VideoCamer to re-init based on new shared pref values. 2089 onSharedPreferenceChanged(); 2090 } 2091 2092 @Override 2093 public synchronized void onEffectsError(Exception exception, String fileName) { 2094 // TODO: Eventually we may want to show the user an error dialog, and then restart the 2095 // camera and encoder gracefully. For now, we just delete the file and bail out. 2096 if (fileName != null && new File(fileName).exists()) { 2097 deleteVideoFile(fileName); 2098 } 2099 try { 2100 if (Class.forName("android.filterpacks.videosink.MediaRecorderStopException") 2101 .isInstance(exception)) { 2102 Log.w(TAG, "Problem recoding video file. Removing incomplete file."); 2103 return; 2104 } 2105 } catch (ClassNotFoundException ex) { 2106 Log.w(TAG, ex); 2107 } 2108 throw new RuntimeException("Error during recording!", exception); 2109 } 2110 2111 private void initializeControlByIntent() { 2112 if (mIsVideoCaptureIntent) { 2113 // Cannot use RotateImageView for "done" and "cancel" button because 2114 // the tablet layout uses RotateLayout, which cannot be cast to 2115 // RotateImageView. 2116 mReviewDoneButton = (Rotatable) mRootView.findViewById(R.id.btn_done); 2117 mReviewCancelButton = (Rotatable) mRootView.findViewById(R.id.btn_cancel); 2118 mReviewPlayButton = (RotateImageView) mRootView.findViewById(R.id.btn_play); 2119 mReviewRetakeButton = mRootView.findViewById(R.id.btn_retake); 2120 mRootView.findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE); 2121 2122 // Not grayed out upon disabled, to make the follow-up fade-out 2123 // effect look smooth. Note that the review done button in tablet 2124 // layout is not a TwoStateImageView. 2125 if (mReviewDoneButton instanceof TwoStateImageView) { 2126 ((TwoStateImageView) mReviewDoneButton).enableFilter(false); 2127 } 2128 } else { 2129 mActivity.mThumbnailView = (RotateImageView) mRootView.findViewById(R.id.thumbnail); 2130 if (mActivity.mThumbnailView != null) { 2131 mActivity.mThumbnailView.enableFilter(false); 2132 mActivity.mThumbnailView.setVisibility(View.VISIBLE); 2133 mActivity.mThumbnailViewWidth = mActivity.mThumbnailView.getLayoutParams().width; 2134 } 2135 } 2136 } 2137 2138 private void initializeMiscControls() { 2139 mPreviewFrameLayout = (PreviewFrameLayout) mRootView.findViewById(R.id.frame); 2140 mPreviewFrameLayout.setOnLayoutChangeListener(mActivity); 2141 mReviewImage = (ImageView) mRootView.findViewById(R.id.review_image); 2142 2143 mShutterButton = mActivity.getShutterButton(); 2144 mShutterButton.setImageResource(R.drawable.btn_new_shutter); 2145 mShutterButton.setOnShutterButtonListener(this); 2146 mShutterButton.requestFocus(); 2147 2148 // Disable the shutter button if effects are ON since it might take 2149 // a little more time for the effects preview to be ready. We do not 2150 // want to allow recording before that happens. The shutter button 2151 // will be enabled when we get the message from effectsrecorder that 2152 // the preview is running. This becomes critical when the camera is 2153 // swapped. 2154 if (effectsActive()) { 2155 mShutterButton.setEnabled(false); 2156 } 2157 2158 mRecordingTimeView = (TextView) mRootView.findViewById(R.id.recording_time); 2159 mRecordingTimeRect = (RotateLayout) mRootView.findViewById(R.id.recording_time_rect); 2160 mTimeLapseLabel = mRootView.findViewById(R.id.time_lapse_label); 2161 // The R.id.labels can only be found in phone layout. 2162 // That is, mLabelsLinearLayout should be null in tablet layout. 2163 mLabelsLinearLayout = (LinearLayout) mRootView.findViewById(R.id.labels); 2164 2165 mBgLearningMessageRotater = (RotateLayout) mRootView.findViewById(R.id.bg_replace_message); 2166 mBgLearningMessageFrame = mRootView.findViewById(R.id.bg_replace_message_frame); 2167 } 2168 2169 @Override 2170 public void onConfigurationChanged(Configuration newConfig) { 2171 setDisplayOrientation(); 2172 2173 // Change layout in response to configuration change 2174 LayoutInflater inflater = mActivity.getLayoutInflater(); 2175 LinearLayout appRoot = (LinearLayout) mRootView.findViewById(R.id.camera_app_root); 2176 appRoot.setOrientation( 2177 newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE 2178 ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); 2179 appRoot.removeAllViews(); 2180 inflater.inflate(R.layout.preview_frame_video, appRoot); 2181 inflater.inflate(R.layout.camera_control, appRoot); 2182 2183 // from onCreate() 2184 initializeControlByIntent(); 2185 initializeSurfaceView(); 2186 initializeMiscControls(); 2187 showTimeLapseUI(mCaptureTimeLapse); 2188 initializeVideoSnapshot(); 2189 resizeForPreviewAspectRatio(); 2190 initializeIndicatorControl(); 2191 2192 // from onResume() 2193 showVideoSnapshotUI(false); 2194 initializeZoom(); 2195 if (!mIsVideoCaptureIntent) { 2196 mActivity.updateThumbnailView(); 2197 } 2198 } 2199 2200 @Override 2201 public void onOverriddenPreferencesClicked() { 2202 } 2203 2204 @Override 2205 public void onRestorePreferencesClicked() { 2206 Runnable runnable = new Runnable() { 2207 @Override 2208 public void run() { 2209 restorePreferences(); 2210 } 2211 }; 2212 mRotateDialog.showAlertDialog( 2213 null, 2214 mActivity.getString(R.string.confirm_restore_message), 2215 mActivity.getString(android.R.string.ok), runnable, 2216 mActivity.getString(android.R.string.cancel), null); 2217 } 2218 2219 private void restorePreferences() { 2220 // Reset the zoom. Zoom value is not stored in preference. 2221 if (mParameters.isZoomSupported()) { 2222 mZoomValue = 0; 2223 setCameraParameters(); 2224// mZoomControl.setZoomIndex(0); 2225 } 2226 2227// if (mIndicatorControlContainer != null) { 2228// mIndicatorControlContainer.dismissSettingPopup(); 2229 CameraSettings.restorePreferences(mActivity, mPreferences, 2230 mParameters); 2231// mIndicatorControlContainer.reloadPreferences(); 2232 onSharedPreferenceChanged(); 2233// } 2234 } 2235 2236 private boolean effectsActive() { 2237 return (mEffectType != EffectsRecorder.EFFECT_NONE); 2238 } 2239 2240 @Override 2241 public void onSharedPreferenceChanged() { 2242 // ignore the events after "onPause()" or preview has not started yet 2243 if (mPaused) return; 2244 synchronized (mPreferences) { 2245 // If mCameraDevice is not ready then we can set the parameter in 2246 // startPreview(). 2247 if (mActivity.mCameraDevice == null) return; 2248 2249 boolean recordLocation = RecordLocationPreference.get( 2250 mPreferences, mContentResolver); 2251 mLocationManager.recordLocation(recordLocation); 2252 2253 // Check if the current effects selection has changed 2254 if (updateEffectSelection()) return; 2255 2256 readVideoPreferences(); 2257 showTimeLapseUI(mCaptureTimeLapse); 2258 // We need to restart the preview if preview size is changed. 2259 Size size = mParameters.getPreviewSize(); 2260 if (size.width != mDesiredPreviewWidth 2261 || size.height != mDesiredPreviewHeight) { 2262 if (!effectsActive()) { 2263 stopPreview(); 2264 } else { 2265 mEffectsRecorder.release(); 2266 mEffectsRecorder = null; 2267 } 2268 resizeForPreviewAspectRatio(); 2269 startPreview(); // Parameters will be set in startPreview(). 2270 } else { 2271 setCameraParameters(); 2272 } 2273 } 2274 } 2275 2276 private void switchCamera() { 2277 if (mPaused) return; 2278 2279 Log.d(TAG, "Start to switch camera."); 2280 mCameraId = mActivity.mPendingSwitchCameraId; 2281 mActivity.mPendingSwitchCameraId = -1; 2282 mActivity.mCameraPicker.setCameraId(mCameraId); 2283 2284 closeCamera(); 2285 2286 // Restart the camera and initialize the UI. From onCreate. 2287 mPreferences.setLocalId(mActivity, mCameraId); 2288 CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); 2289 CameraOpenThread cameraOpenThread = new CameraOpenThread(); 2290 cameraOpenThread.start(); 2291 try { 2292 cameraOpenThread.join(); 2293 } catch (InterruptedException ex) { 2294 // ignore 2295 } 2296 readVideoPreferences(); 2297 startPreview(); 2298 initializeVideoSnapshot(); 2299 resizeForPreviewAspectRatio(); 2300 initializeIndicatorControl(); 2301 2302 // From onResume 2303 initializeZoom(); 2304 setOrientationIndicator(mOrientationCompensation, false); 2305 2306 if (ApiHelper.HAS_SURFACE_TEXTURE) { 2307 // Start switch camera animation. Post a message because 2308 // onFrameAvailable from the old camera may already exist. 2309 mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION); 2310 } 2311 } 2312 2313 // Preview texture has been copied. Now camera can be released and the 2314 // animation can be started. 2315 @Override 2316 public void onPreviewTextureCopied() { 2317 mHandler.sendEmptyMessage(SWITCH_CAMERA); 2318 } 2319 2320 private boolean updateEffectSelection() { 2321 int previousEffectType = mEffectType; 2322 Object previousEffectParameter = mEffectParameter; 2323 mEffectType = CameraSettings.readEffectType(mPreferences); 2324 mEffectParameter = CameraSettings.readEffectParameter(mPreferences); 2325 2326 if (mEffectType == previousEffectType) { 2327 if (mEffectType == EffectsRecorder.EFFECT_NONE) return false; 2328 if (mEffectParameter.equals(previousEffectParameter)) return false; 2329 } 2330 Log.v(TAG, "New effect selection: " + mPreferences.getString( 2331 CameraSettings.KEY_VIDEO_EFFECT, "none")); 2332 2333 if (mEffectType == EffectsRecorder.EFFECT_NONE) { 2334 // Stop effects and return to normal preview 2335 mEffectsRecorder.stopPreview(); 2336 mPreviewing = false; 2337 return true; 2338 } 2339 if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER && 2340 ((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) { 2341 // Request video from gallery to use for background 2342 Intent i = new Intent(Intent.ACTION_PICK); 2343 i.setDataAndType(Video.Media.EXTERNAL_CONTENT_URI, 2344 "video/*"); 2345 i.putExtra(Intent.EXTRA_LOCAL_ONLY, true); 2346 mActivity.startActivityForResult(i, REQUEST_EFFECT_BACKDROPPER); 2347 return true; 2348 } 2349 if (previousEffectType == EffectsRecorder.EFFECT_NONE) { 2350 // Stop regular preview and start effects. 2351 stopPreview(); 2352 checkQualityAndStartPreview(); 2353 } else { 2354 // Switch currently running effect 2355 mEffectsRecorder.setEffect(mEffectType, mEffectParameter); 2356 } 2357 return true; 2358 } 2359 2360 // Verifies that the current preview view size is correct before starting 2361 // preview. If not, resets the surface texture and resizes the view. 2362 private void checkQualityAndStartPreview() { 2363 readVideoPreferences(); 2364 showTimeLapseUI(mCaptureTimeLapse); 2365 Size size = mParameters.getPreviewSize(); 2366 if (size.width != mDesiredPreviewWidth 2367 || size.height != mDesiredPreviewHeight) { 2368 resizeForPreviewAspectRatio(); 2369 } 2370 // Start up preview again 2371 startPreview(); 2372 } 2373 2374 private void showTimeLapseUI(boolean enable) { 2375 if (mTimeLapseLabel != null) { 2376 mTimeLapseLabel.setVisibility(enable ? View.VISIBLE : View.GONE); 2377 } 2378 } 2379 2380 @Override 2381 public boolean dispatchTouchEvent(MotionEvent m) { 2382 if (mSwitchingCamera) return true; 2383 return false; 2384 } 2385 2386 private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener { 2387 @Override 2388 public void onZoomValueChanged(int index) { 2389 // Not useful to change zoom value when the activity is paused. 2390 if (mPaused) return; 2391 2392 mZoomValue = index; 2393 2394 // Set zoom parameters asynchronously 2395 mParameters.setZoom(mZoomValue); 2396 mActivity.mCameraDevice.setParametersAsync(mParameters); 2397 } 2398 } 2399 2400 private void initializeZoom() { 2401 if (!mParameters.isZoomSupported()) return; 2402 2403 mZoomMax = mParameters.getMaxZoom(); 2404 // Currently we use immediate zoom for fast zooming to get better UX and 2405 // there is no plan to take advantage of the smooth zoom. 2406 } 2407 2408 private void initializeVideoSnapshot() { 2409 if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) { 2410 mActivity.setSingleTapUpListener(mPreviewFrameLayout); 2411 // Show the tap to focus toast if this is the first start. 2412 if (mPreferences.getBoolean( 2413 CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, true)) { 2414 // Delay the toast for one second to wait for orientation. 2415 mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_SNAPSHOT_TOAST, 1000); 2416 } 2417 } else { 2418 mActivity.setSingleTapUpListener(null); 2419 } 2420 } 2421 2422 void showVideoSnapshotUI(boolean enabled) { 2423 if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) { 2424 mPreviewFrameLayout.showBorder(enabled); 2425// mIndicatorControlContainer.enableZoom(!enabled); 2426 mShutterButton.setEnabled(!enabled); 2427 } 2428 } 2429 2430 // Preview area is touched. Take a picture. 2431 @Override 2432 public void onSingleTapUp(View view, int x, int y) { 2433 if (mMediaRecorderRecording && effectsActive()) { 2434 new RotateTextToast(mActivity, R.string.disable_video_snapshot_hint, 2435 mOrientation).show(); 2436 return; 2437 } 2438 2439 if (mPaused || mSnapshotInProgress 2440 || !mMediaRecorderRecording || effectsActive()) { 2441 return; 2442 } 2443 2444 // Set rotation and gps data. 2445 int rotation = Util.getJpegRotation(mCameraId, mOrientation); 2446 mParameters.setRotation(rotation); 2447 Location loc = mLocationManager.getCurrentLocation(); 2448 Util.setGpsParameters(mParameters, loc); 2449 mActivity.mCameraDevice.setParameters(mParameters); 2450 2451 Log.v(TAG, "Video snapshot start"); 2452 mActivity.mCameraDevice.takePicture(null, null, null, new JpegPictureCallback(loc)); 2453 showVideoSnapshotUI(true); 2454 mSnapshotInProgress = true; 2455 } 2456 2457 @Override 2458 public void updateCameraAppView() { 2459 if (!mPreviewing || mParameters.getFlashMode() == null) return; 2460 2461 // When going to and back from gallery, we need to turn off/on the flash. 2462 if (!mActivity.mShowCameraAppView) { 2463 if (mParameters.getFlashMode().equals(Parameters.FLASH_MODE_OFF)) { 2464 mRestoreFlash = false; 2465 return; 2466 } 2467 mRestoreFlash = true; 2468 setCameraParameters(); 2469 } else if (mRestoreFlash) { 2470 mRestoreFlash = false; 2471 setCameraParameters(); 2472 } 2473 } 2474 2475 @Override 2476 public void onFullScreenChanged(boolean full) { 2477 if (ApiHelper.HAS_SURFACE_TEXTURE) return; 2478 2479 if (full) { 2480 mPreviewSurfaceView.expand(); 2481 } else { 2482 mPreviewSurfaceView.shrink(); 2483 } 2484 } 2485 2486 private final class JpegPictureCallback implements PictureCallback { 2487 Location mLocation; 2488 2489 public JpegPictureCallback(Location loc) { 2490 mLocation = loc; 2491 } 2492 2493 @Override 2494 public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { 2495 Log.v(TAG, "onPictureTaken"); 2496 mSnapshotInProgress = false; 2497 showVideoSnapshotUI(false); 2498 storeImage(jpegData, mLocation); 2499 } 2500 } 2501 2502 private void storeImage(final byte[] data, Location loc) { 2503 long dateTaken = System.currentTimeMillis(); 2504 String title = Util.createJpegName(dateTaken); 2505 int orientation = Exif.getOrientation(data); 2506 Size s = mParameters.getPictureSize(); 2507 Uri uri = Storage.addImage(mContentResolver, title, dateTaken, loc, orientation, data, 2508 s.width, s.height); 2509 if (uri != null) { 2510 // Create a thumbnail whose width is equal or bigger than that of the preview. 2511 int ratio = (int) Math.ceil((double) mParameters.getPictureSize().width 2512 / mPreviewFrameLayout.getWidth()); 2513 int inSampleSize = Integer.highestOneBit(ratio); 2514 mActivity.mThumbnail = Thumbnail.createThumbnail(data, orientation, inSampleSize, uri); 2515 if (mActivity.mThumbnail != null && mActivity.mThumbnailView != null) { 2516 mActivity.mThumbnailView.setBitmap(mActivity.mThumbnail.getBitmap()); 2517 } 2518 Util.broadcastNewPicture(mActivity, uri); 2519 } 2520 } 2521 2522 private boolean resetEffect() { 2523 if (mResetEffect) { 2524 String value = mPreferences.getString(CameraSettings.KEY_VIDEO_EFFECT, 2525 mPrefVideoEffectDefault); 2526 if (!mPrefVideoEffectDefault.equals(value)) { 2527 writeDefaultEffectToPrefs(); 2528 return true; 2529 } 2530 } 2531 mResetEffect = true; 2532 return false; 2533 } 2534 2535 private String convertOutputFormatToMimeType(int outputFileFormat) { 2536 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) { 2537 return "video/mp4"; 2538 } 2539 return "video/3gpp"; 2540 } 2541 2542 private String convertOutputFormatToFileExt(int outputFileFormat) { 2543 if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) { 2544 return ".mp4"; 2545 } 2546 return ".3gp"; 2547 } 2548 2549 private void closeVideoFileDescriptor() { 2550 if (mVideoFileDescriptor != null) { 2551 try { 2552 mVideoFileDescriptor.close(); 2553 } catch (IOException e) { 2554 Log.e(TAG, "Fail to close fd", e); 2555 } 2556 mVideoFileDescriptor = null; 2557 } 2558 } 2559 2560 private void showTapToSnapshotToast() { 2561 new RotateTextToast(mActivity, R.string.video_snapshot_hint, mOrientationCompensation) 2562 .show(); 2563 // Clear the preference. 2564 Editor editor = mPreferences.edit(); 2565 editor.putBoolean(CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, false); 2566 editor.apply(); 2567 } 2568 2569 private void clearVideoNamer() { 2570 if (mVideoNamer != null) { 2571 mVideoNamer.finish(); 2572 mVideoNamer = null; 2573 } 2574 } 2575 2576 private static class VideoNamer extends Thread { 2577 private boolean mRequestPending; 2578 private ContentResolver mResolver; 2579 private ContentValues mValues; 2580 private boolean mStop; 2581 private Uri mUri; 2582 2583 // Runs in main thread 2584 public VideoNamer() { 2585 start(); 2586 } 2587 2588 // Runs in main thread 2589 public synchronized void prepareUri( 2590 ContentResolver resolver, ContentValues values) { 2591 mRequestPending = true; 2592 mResolver = resolver; 2593 mValues = new ContentValues(values); 2594 notifyAll(); 2595 } 2596 2597 // Runs in main thread 2598 public synchronized Uri getUri() { 2599 // wait until the request is done. 2600 while (mRequestPending) { 2601 try { 2602 wait(); 2603 } catch (InterruptedException ex) { 2604 // ignore. 2605 } 2606 } 2607 Uri uri = mUri; 2608 mUri = null; 2609 return uri; 2610 } 2611 2612 // Runs in namer thread 2613 @Override 2614 public synchronized void run() { 2615 while (true) { 2616 if (mStop) break; 2617 if (!mRequestPending) { 2618 try { 2619 wait(); 2620 } catch (InterruptedException ex) { 2621 // ignore. 2622 } 2623 continue; 2624 } 2625 cleanOldUri(); 2626 generateUri(); 2627 mRequestPending = false; 2628 notifyAll(); 2629 } 2630 cleanOldUri(); 2631 } 2632 2633 // Runs in main thread 2634 public synchronized void finish() { 2635 mStop = true; 2636 notifyAll(); 2637 } 2638 2639 // Runs in namer thread 2640 private void generateUri() { 2641 Uri videoTable = Uri.parse("content://media/external/video/media"); 2642 mUri = mResolver.insert(videoTable, mValues); 2643 } 2644 2645 // Runs in namer thread 2646 private void cleanOldUri() { 2647 if (mUri == null) return; 2648 mResolver.delete(mUri, null, null); 2649 mUri = null; 2650 } 2651 } 2652 2653 private class SurfaceViewCallback implements SurfaceHolder.Callback { 2654 public SurfaceViewCallback() {} 2655 2656 @Override 2657 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 2658 Log.v(TAG, "Surface changed. width=" + width + ". height=" + height); 2659 } 2660 2661 @Override 2662 public void surfaceCreated(SurfaceHolder holder) { 2663 Log.v(TAG, "Surface created"); 2664 mSurfaceViewReady = true; 2665 if (mPaused) return; 2666 if (!ApiHelper.HAS_SURFACE_TEXTURE) { 2667 mActivity.mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder()); 2668 if (!mPreviewing) { 2669 startPreview(); 2670 } 2671 } 2672 } 2673 2674 @Override 2675 public void surfaceDestroyed(SurfaceHolder holder) { 2676 Log.v(TAG, "Surface destroyed"); 2677 mSurfaceViewReady = false; 2678 if (mPaused) return; 2679 if (!ApiHelper.HAS_SURFACE_TEXTURE) { 2680 stopVideoRecording(); 2681 stopPreview(); 2682 } 2683 } 2684 } 2685 2686 @Override 2687 public boolean updateStorageHintOnResume() { 2688 return true; 2689 } 2690 2691 // required by OnPreferenceChangedListener 2692 @Override 2693 public void onCameraPickerClicked(int cameraId) { 2694 } 2695 2696} 2697