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