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