void setDesiredCameraParameters(Camera camera, boolean safeMode) {
    Camera.Parameters parameters = camera.getParameters();

    if (parameters == null) {
      Log.w(
          TAG,
          "Device error: no camera parameters are available. Proceeding without configuration.");
      return;
    }

    Log.i(TAG, "Initial camera parameters: " + parameters.flatten());

    if (safeMode) {
      Log.w(TAG, "In camera config safe mode -- most settings will not be honored");
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    initializeTorch(parameters, prefs, safeMode);

    String focusMode = null;
    if (prefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true)) {
      if (safeMode || prefs.getBoolean(PreferencesActivity.KEY_DISABLE_CONTINUOUS_FOCUS, false)) {
        focusMode =
            findSettableValue(
                parameters.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_AUTO);
      } else {
        focusMode =
            findSettableValue(
                parameters.getSupportedFocusModes(),
                "continuous-picture", // Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE in 4.0+
                "continuous-video", // Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO in 4.0+
                Camera.Parameters.FOCUS_MODE_AUTO);
      }
    }
    // Maybe selected auto-focus but not available, so fall through here:
    if (!safeMode && focusMode == null) {
      focusMode =
          findSettableValue(
              parameters.getSupportedFocusModes(),
              Camera.Parameters.FOCUS_MODE_MACRO,
              "edof"); // Camera.Parameters.FOCUS_MODE_EDOF in 2.2+
    }
    if (focusMode != null) {
      parameters.setFocusMode(focusMode);
    }

    if (prefs.getBoolean(PreferencesActivity.KEY_INVERT_SCAN, false)) {
      String colorMode =
          findSettableValue(
              parameters.getSupportedColorEffects(), Camera.Parameters.EFFECT_NEGATIVE);
      if (colorMode != null) {
        parameters.setColorEffect(colorMode);
      }
    }

    parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
    camera.setParameters(parameters);
  }
  public int setCameraProperty(String key, String value) {
    if (mCamera == null) {
      return MAAPI_consts.MA_CAMERA_RES_FAILED;
    }
    try {
      Camera.Parameters param = getCurrentParameters();
      if (key.equals(MAAPI_consts.MA_CAMERA_IMAGE_FORMAT)) {
        if (value.equals(MAAPI_consts.MA_CAMERA_IMAGE_RAW)) {
          rawMode = true;
        } else {
          // default mode is jpeg
          rawMode = false;
        }
      } else if (key.equals(MAAPI_consts.MA_CAMERA_FOCUS_MODE)) {
        if (value.equals(MAAPI_consts.MA_CAMERA_FOCUS_AUTO)) {
          if (false == param.getSupportedFocusModes().contains(value)) {

            return MAAPI_consts.MA_CAMERA_RES_VALUE_NOTSUPPORTED;
          }

          mCamera.autoFocus(autoFocusCallback);
        } else if (value.equals(MAAPI_consts.MA_CAMERA_FOCUS_MACRO)) {

          if (false == param.getSupportedFocusModes().contains(value)) {
            return MAAPI_consts.MA_CAMERA_RES_VALUE_NOTSUPPORTED;
          }
          mCamera.autoFocus(autoFocusCallback);
        } else if (false == param.getSupportedFocusModes().contains(value)) {
          mCamera.cancelAutoFocus();
          return MAAPI_consts.MA_CAMERA_RES_VALUE_NOTSUPPORTED;
        } else mCamera.cancelAutoFocus();

        param.setFocusMode(value);
      } else if (key.equals(MAAPI_consts.MA_CAMERA_FLASH_MODE)) {
        if (true == param.getSupportedFlashModes().contains(value)) {
          param.setFlashMode(value);
        } else {
          return MAAPI_consts.MA_CAMERA_RES_VALUE_NOTSUPPORTED;
        }
      } else {
        param.set(key, value);
      }
      mCamera.setParameters(param);
    } catch (Exception e) {
      return MAAPI_consts.MA_CAMERA_RES_FAILED;
    }
    return MAAPI_consts.MA_CAMERA_RES_OK;
  }
예제 #3
0
  // Called when holder has changed
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

    Camera.Parameters parameters = camera.getParameters();
    List<String> focusModes = parameters.getSupportedFocusModes();
    if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
      Log.d("camera", "focus_mode_auto");
      parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    } else {
      Log.d("camera", "focus_mode_macro");
      parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
    }
    Log.d("camera", "orientation: " + getResources().getConfiguration().orientation);
    int orientation = getResources().getConfiguration().orientation;
    switch (orientation) {
      case Surface.ROTATION_0:
        Log.d("camera", "ROTATION_0");
        camera.setDisplayOrientation(180);
        break;
      case Surface.ROTATION_90:
        Log.d("camera", "ROTATION_90");
        camera.setDisplayOrientation(90);
        break;
      case Surface.ROTATION_180:
        Log.d("camera", "ROTATION_180");
        camera.setDisplayOrientation(0);
        break;
      case Surface.ROTATION_270:
        Log.d("camera", "ROTATION_270");
        camera.setDisplayOrientation(270);
        break;
    }

    camera.setParameters(parameters);
    camera.startPreview();
  }
예제 #4
0
  @Override
  public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
    Log.e("ok", "surfaceChanged => w=" + i2 + ", h=" + i3);
    // before changing the application orientation, you need to stop the preview, rotate and then
    // start it again
    if (surfaceHolder.getSurface() == null) // check if the surface is ready to receive camera data
    return;

    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // this will happen when you are trying the camera if it's not running
    }

    // now, recreate the camera preview
    try {

      Camera.Parameters parameters = mCamera.getParameters();
      List<String> focusModes = parameters.getSupportedFocusModes();
      if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
      }
      parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
      mCamera.setParameters(parameters);
      mCamera.setDisplayOrientation(90);
      mCamera.startPreview(mHolder);
    } catch (IOException e) {
      Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
    }
  }
  private void initPreview(int width, int height) {
    if (camera != null && previewHolder.getSurface() != null) {
      try {
        camera.setPreviewDisplay(previewHolder);
      } catch (Throwable t) {

      }

      if (!cameraConfigured) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = getBestPreviewSize(width, height, parameters);
        Camera.Size pictureSize = getLargestPictureSize(parameters);

        if (size != null && pictureSize != null) {
          if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO)) {

            // set the focus mode
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
          }
          parameters.setPreviewSize(size.width, size.height);
          parameters.setPictureSize(pictureSize.width, pictureSize.height);
          parameters.setPictureFormat(ImageFormat.JPEG);
          camera.setParameters(parameters);
          cameraConfigured = true;
        }
      }
    }
  }
  @SuppressLint("InlinedApi")
  private static void setDesiredCameraParameters(
      final Camera camera, final Camera.Size cameraResolution, final boolean continuousAutoFocus) {
    final Camera.Parameters parameters = camera.getParameters();
    if (parameters == null) return;

    final List<String> supportedFocusModes = parameters.getSupportedFocusModes();
    final String focusMode =
        continuousAutoFocus
            ? findValue(
                supportedFocusModes,
                Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
                Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
                Camera.Parameters.FOCUS_MODE_AUTO,
                Camera.Parameters.FOCUS_MODE_MACRO)
            : findValue(
                supportedFocusModes,
                Camera.Parameters.FOCUS_MODE_AUTO,
                Camera.Parameters.FOCUS_MODE_MACRO);
    if (focusMode != null) parameters.setFocusMode(focusMode);

    parameters.setPreviewSize(cameraResolution.width, cameraResolution.height);

    camera.setParameters(parameters);
  }
  private void checkRearCamera() {
    Camera camera = null;
    try {
      camera = Camera.open();
      if (camera != null) {
        assertAvailable(PackageManager.FEATURE_CAMERA);

        Camera.Parameters params = camera.getParameters();
        if (params.getSupportedFocusModes().contains(Parameters.FOCUS_MODE_AUTO)) {
          assertAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS);
        } else {
          assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS);
        }

        if (params.getFlashMode() != null) {
          assertAvailable(PackageManager.FEATURE_CAMERA_FLASH);
        } else {
          assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH);
        }
      } else {
        assertNotAvailable(PackageManager.FEATURE_CAMERA);
        assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS);
        assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH);
      }
    } finally {
      if (camera != null) {
        camera.release();
      }
    }
  }
예제 #8
0
  public CustomeCamera(
      Activity activity, FrameLayout cameraPreviewLayout, Integer size, Integer quality)
      throws Exception {
    this.activity = activity;
    this.size = size;
    this.quality = quality;

    // Create an instance of Camera
    try {
      mCamera = getCameraInstance();
    } catch (Exception e) {
      throw new Exception(e.getMessage());
    }
    try {
      mCamera.setDisplayOrientation(90);
    } catch (Exception e) {
      Log.d(TAG, e.getMessage());
    }

    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info);
    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    int degrees = 0;
    switch (rotation) {
      case Surface.ROTATION_0:
        degrees = 0;
        break; // Natural orientation
      case Surface.ROTATION_90:
        degrees = 90;
        break; // Landscape left
      case Surface.ROTATION_180:
        degrees = 180;
        break; // Upside down
      case Surface.ROTATION_270:
        degrees = 270;
        break; // Landscape right
    }
    int rotate = (info.orientation - degrees + 360) % 360;

    // STEP #2: Set the 'rotation' parameter
    Camera.Parameters params = mCamera.getParameters();
    params.setRotation(rotate);

    List<String> focusModes = params.getSupportedFocusModes();
    if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
      params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    }
    if (params.getFocusMode() == Camera.Parameters.FOCUS_MODE_AUTO) autoFocusEnabled = true;
    else autoFocusEnabled = false;

    // TODO for the test
    autoFocusEnabled = false;

    mCamera.setParameters(params);

    // Create our Preview view and set it as the content of our activity.
    mPreview = new CameraPreview(activity, mCamera);
    cameraPreviewLayout.addView(mPreview);
  }
예제 #9
0
  private void setIfAutoFocusSupported() {
    // get Camera parameters
    Camera.Parameters params = mCamera.getParameters();

    List<String> focusModes = params.getSupportedFocusModes();
    if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
      params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
      mCamera.setParameters(params);
    }
  }
예제 #10
0
  void setDesiredCameraParameters(Camera camera) {
    Camera.Parameters parameters = camera.getParameters();

    if (parameters == null) {
      Log.w(
          TAG,
          "Device error: no camera parameters are available. Proceeding without configuration.");
      return;
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    initializeTorch(parameters, prefs);
    String focusMode = null;
    if (prefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true)) {
      if (prefs.getBoolean(PreferencesActivity.KEY_DISABLE_CONTINUOUS_FOCUS, false)) {
        focusMode =
            findSettableValue(
                parameters.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_AUTO);
      } else {
        focusMode =
            findSettableValue(
                parameters.getSupportedFocusModes(),
                "continuous-picture", // Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE in 4.0+
                "continuous-video", // Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO in 4.0+
                Camera.Parameters.FOCUS_MODE_AUTO);
      }
    }
    // Maybe selected auto-focus but not available, so fall through here:
    if (focusMode == null) {
      focusMode =
          findSettableValue(
              parameters.getSupportedFocusModes(),
              Camera.Parameters.FOCUS_MODE_MACRO,
              "edof"); // Camera.Parameters.FOCUS_MODE_EDOF in 2.2+
    }
    if (focusMode != null) {
      parameters.setFocusMode(focusMode);
    }

    parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
    camera.setParameters(parameters);
  }
예제 #11
0
  private int hasAutoFocus(Camera.Parameters parameters) {
    final List<String> supportedFocusModes = parameters.getSupportedFocusModes();

    if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
      return 2;
    } else if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
      // auto focus on request only
      return 1;
    }
    return 0;
  }
예제 #12
0
  public synchronized void setupCamera(int width, int height) {
    if (mCamera != null) {
      Log.i(TAG, "Setup Camera - " + width + "x" + height);
      Camera.Parameters params = mCamera.getParameters();
      List<Camera.Size> sizes = params.getSupportedPreviewSizes();
      mFrameWidth = width;
      mFrameHeight = height;

      // selecting optimal camera preview size
      {
        int minDiff = Integer.MAX_VALUE;
        for (Camera.Size size : sizes) {
          if (Math.abs(size.height - height) < minDiff) {
            mFrameWidth = size.width;
            mFrameHeight = size.height;
            minDiff = Math.abs(size.height - height);
          }
        }
      }

      params.setPreviewSize(getFrameWidth(), getFrameHeight());

      List<String> FocusModes = params.getSupportedFocusModes();
      if (FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
        params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
      }

      mCamera.setParameters(params);

      /* Now allocate the buffer */
      params = mCamera.getParameters();
      int size = params.getPreviewSize().width * params.getPreviewSize().height;
      size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
      mBuffer = new byte[size];
      /* The buffer where the current frame will be copied */
      mFrame = new byte[size];
      mCamera.addCallbackBuffer(mBuffer);

      /* Notify that the preview is about to be started and deliver preview size */
      onPreviewStarted(params.getPreviewSize().width, params.getPreviewSize().height);

      try {
        setPreview();
      } catch (IOException e) {
        Log.e(TAG, "mCamera.setPreviewDisplay/setPreviewTexture fails: " + e);
      }

      /* Now we can start a preview */
      mCamera.startPreview();
    }
  }
예제 #13
0
  /** Handles camera opening */
  private void openCamera(int which) {
    if (mCamera != null) {
      mCamera.stopPreview();
      mCamera.release();
      mCamera = null;
    }

    if (mCameraId >= 0) {
      Camera.getCameraInfo(mCameraId, mCameraInfo);
      if (which == FRONT) mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
      else mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);

      params = mCamera.getParameters();
      params.setRotation(0);

      /** set focus mode */
      List<String> FocusModes = params.getSupportedFocusModes();
      if (FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
        params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
      }

      mCamera.setParameters(params);
      try {
        if (mSurfaceTexture != null) {
          mCamera.setPreviewTexture(mSurfaceTexture);
          mCamera.startPreview();
        }
      } catch (Exception ex) {
      }
    }

    if (mCamera == null || mSharedData == null) {
      return;
    }

    int orientation = mCameraInfo.orientation + rot_angle;

    Matrix.setRotateM(mSharedData.mOrientationM, 0, orientation, 0f, 0f, 1f);

    Camera.Size size = mCamera.getParameters().getPreviewSize();
    if (orientation % 90 == 0) {
      int w = size.width;
      size.width = size.height;
      size.height = w;
    }

    mSharedData.mAspectRatioPreview[0] = (float) Math.min(size.width, size.height) / size.width;
    mSharedData.mAspectRatioPreview[1] = (float) Math.min(size.width, size.height) / size.height;
  }
예제 #14
0
  /**
   * Sets the focus mode.
   *
   * @param mode the focus mode
   * @return {@code true} if the focus mode is set, {@code false} otherwise
   * @see #getFocusMode()
   */
  public boolean setFocusMode(@FocusMode String mode) {
    synchronized (mCameraLock) {
      if (mCamera != null && mode != null) {
        Camera.Parameters parameters = mCamera.getParameters();
        if (parameters.getSupportedFocusModes().contains(mode)) {
          parameters.setFocusMode(mode);
          mCamera.setParameters(parameters);
          mFocusMode = mode;
          return true;
        }
      }

      return false;
    }
  }
예제 #15
0
  private void initCameraParameters() {
    Camera.Parameters parameters = mCamera.getParameters();
    String mod = Build.MODEL;
    if (Build.VERSION.SDK_INT >= 8) {
      // MZ 180, other 90...
      if ("M9".equalsIgnoreCase(mod) || "MX".equalsIgnoreCase(mod)) {
        setDisplayOrientation(mCamera, 180);
      } else {
        setDisplayOrientation(mCamera, 90);
      }
    } else {
      parameters.set("orientation", "portrait");
      parameters.set("rotation", 90);
    }

    if (cameraCurrentlyLocked == CameraInfo.CAMERA_FACING_FRONT) {
      ismCameraCanFlash = false;
    } else {
      ismCameraCanFlash = true;
    }
    if (!ismCameraCanFlash) {
      mBtnFlash1.setVisibility(View.INVISIBLE);
      mBtnFlash2.setVisibility(View.INVISIBLE);
      mBtnFlash3.setVisibility(View.INVISIBLE);
    } else {
      mBtnFlash1.setVisibility(View.VISIBLE);
    }

    List<String> focusModes = parameters.getSupportedFocusModes();
    if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
      // Autofocus mode is supported
      parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    }

    if (parameters.isZoomSupported()) {
      parameters.setZoom(parameters.getZoom()); // 测试通过
    }
    Camera.Size previewSize = getFitParametersSize(parameters.getSupportedPreviewSizes());
    parameters.setPreviewSize(previewSize.width, previewSize.height);
    Camera.Size pictureSize = getFitParametersSize(parameters.getSupportedPictureSizes());
    parameters.setPictureSize(pictureSize.width, pictureSize.height);

    try {
      mCamera.setParameters(parameters);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 private void setCameraFocusMode(Camera.Parameters parameters) {
   // MODE_INFINITY is preferred mode.
   List<String> supportedFocusModes = parameters.getSupportedFocusModes();
   if (supportedFocusModes != null) {
     if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_INFINITY)) {
       parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
       Log.v(TAG, "Set focus mode INFINITY");
     } else if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_FIXED)) {
       parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_FIXED);
       Log.v(TAG, "Set focus mode FIXED");
     } else if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
       parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
       Log.v(TAG, "Set focus mode AUTO");
     }
   }
 }
예제 #17
0
  public void setCamera(Camera camera) {
    mCamera = camera;
    if (mCamera != null) {
      mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
      requestLayout();

      // get Camera parameters
      Camera.Parameters params = mCamera.getParameters();

      List<String> focusModes = params.getSupportedFocusModes();
      if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
        // set the focus mode
        params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        // set Camera parameters
        mCamera.setParameters(params);
      }
    }
  }
예제 #18
0
 public CameraPreview(ImageView CameraPreview) {
   if (mCamera == null) {
     mCamera = Camera.open();
   }
   Camera.Parameters parameters;
   parameters = mCamera.getParameters();
   List<String> af = parameters.getSupportedFocusModes();
   System.out.println(af);
   if (af.contains("continuous-video")) {
     parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
     System.out.println("FocusModeTrue-Auto");
     // TODO log this
   }
   List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
   Camera.Size cs = sizes.get(0);
   PreviewSizeWidth = cs.width;
   PreviewSizeHeight = cs.height;
   MyCameraPreview = CameraPreview;
   bitmap = Bitmap.createBitmap(PreviewSizeWidth, PreviewSizeHeight, Bitmap.Config.ARGB_8888);
   pixels = new int[PreviewSizeWidth * PreviewSizeHeight];
 }
 public static void setFocus(
     Camera.Parameters parameters,
     boolean autoFocus,
     boolean disableContinuous,
     boolean safeMode) {
   List<String> supportedFocusModes = parameters.getSupportedFocusModes();
   String focusMode = null;
   if (autoFocus) {
     if (safeMode || disableContinuous) {
       focusMode =
           findSettableValue("focus mode", supportedFocusModes, Camera.Parameters.FOCUS_MODE_AUTO);
     } else {
       focusMode =
           findSettableValue(
               "focus mode",
               supportedFocusModes,
               Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
               Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
               Camera.Parameters.FOCUS_MODE_AUTO);
     }
   }
   // Maybe selected auto-focus but not available, so fall through here:
   if (!safeMode && focusMode == null) {
     focusMode =
         findSettableValue(
             "focus mode",
             supportedFocusModes,
             Camera.Parameters.FOCUS_MODE_MACRO,
             Camera.Parameters.FOCUS_MODE_EDOF);
   }
   if (focusMode != null) {
     if (focusMode.equals(parameters.getFocusMode())) {
       Log.i(TAG, "Focus mode already set to " + focusMode);
     } else {
       parameters.setFocusMode(focusMode);
     }
   }
 }
  // zoom in and enable flash
  protected boolean initializeCamera(int width, int height) {
    boolean ret = super.initializeCamera(width, height);

    Camera.Parameters params = mCamera.getParameters();

    List<String> FocusModes = params.getSupportedFocusModes();
    if (FocusModes != null && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
      params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
    } else if (FocusModes != null
        && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
      params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
    }

    List<String> FlashModes = params.getSupportedFlashModes();
    if (FlashModes != null && FlashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
      params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
    }

    if (params.isZoomSupported()) enableZoomControls(params);

    mCamera.setParameters(params);

    return ret;
  }
  /**
   * Set the legacy parameters using the {@link LegacyRequest legacy request}.
   *
   * <p>The legacy request's parameters are changed as a side effect of calling this method.
   *
   * @param legacyRequest a non-{@code null} legacy request
   */
  public static void convertRequestMetadata(LegacyRequest legacyRequest) {
    CameraCharacteristics characteristics = legacyRequest.characteristics;
    CaptureRequest request = legacyRequest.captureRequest;
    Size previewSize = legacyRequest.previewSize;
    Camera.Parameters params = legacyRequest.parameters;

    Rect activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);

    /*
     * scaler.cropRegion
     */
    ParameterUtils.ZoomData zoomData;
    {
      zoomData =
          ParameterUtils.convertScalerCropRegion(
              activeArray, request.get(SCALER_CROP_REGION), previewSize, params);

      if (params.isZoomSupported()) {
        params.setZoom(zoomData.zoomIndex);
      } else if (VERBOSE) {
        Log.v(TAG, "convertRequestToMetadata - zoom is not supported");
      }
    }

    /*
     * colorCorrection.*
     */
    // colorCorrection.aberrationMode
    {
      int aberrationMode =
          ParamsUtils.getOrDefault(
              request,
              COLOR_CORRECTION_ABERRATION_MODE,
              /*defaultValue*/ COLOR_CORRECTION_ABERRATION_MODE_FAST);

      if (aberrationMode != COLOR_CORRECTION_ABERRATION_MODE_FAST) {
        Log.w(
            TAG,
            "convertRequestToMetadata - Ignoring unsupported "
                + "colorCorrection.aberrationMode = "
                + aberrationMode);
      }
    }

    /*
     * control.ae*
     */
    // control.aeAntibandingMode
    {
      String legacyMode;
      Integer antiBandingMode = request.get(CONTROL_AE_ANTIBANDING_MODE);
      if (antiBandingMode != null) {
        legacyMode = convertAeAntiBandingModeToLegacy(antiBandingMode);
      } else {
        legacyMode =
            ListUtils.listSelectFirstFrom(
                params.getSupportedAntibanding(),
                new String[] {
                  Parameters.ANTIBANDING_AUTO,
                  Parameters.ANTIBANDING_OFF,
                  Parameters.ANTIBANDING_50HZ,
                  Parameters.ANTIBANDING_60HZ,
                });
      }

      if (legacyMode != null) {
        params.setAntibanding(legacyMode);
      }
    }

    /*
     * control.aeRegions, afRegions
     */
    {
      // aeRegions
      {
        // Use aeRegions if available, fall back to using awbRegions if present
        MeteringRectangle[] aeRegions = request.get(CONTROL_AE_REGIONS);
        if (request.get(CONTROL_AWB_REGIONS) != null) {
          Log.w(
              TAG,
              "convertRequestMetadata - control.awbRegions setting is not "
                  + "supported, ignoring value");
        }
        int maxNumMeteringAreas = params.getMaxNumMeteringAreas();
        List<Camera.Area> meteringAreaList =
            convertMeteringRegionsToLegacy(
                activeArray, zoomData, aeRegions, maxNumMeteringAreas, /*regionName*/ "AE");

        // WAR: for b/17252693, some devices can't handle params.setFocusAreas(null).
        if (maxNumMeteringAreas > 0) {
          params.setMeteringAreas(meteringAreaList);
        }
      }

      // afRegions
      {
        MeteringRectangle[] afRegions = request.get(CONTROL_AF_REGIONS);
        int maxNumFocusAreas = params.getMaxNumFocusAreas();
        List<Camera.Area> focusAreaList =
            convertMeteringRegionsToLegacy(
                activeArray, zoomData, afRegions, maxNumFocusAreas, /*regionName*/ "AF");

        // WAR: for b/17252693, some devices can't handle params.setFocusAreas(null).
        if (maxNumFocusAreas > 0) {
          params.setFocusAreas(focusAreaList);
        }
      }
    }

    // control.aeTargetFpsRange
    Range<Integer> aeFpsRange = request.get(CONTROL_AE_TARGET_FPS_RANGE);
    if (aeFpsRange != null) {
      int[] legacyFps = convertAeFpsRangeToLegacy(aeFpsRange);

      // TODO - Should we enforce that all HAL1 devices must include (30, 30) FPS range?
      boolean supported = false;
      for (int[] range : params.getSupportedPreviewFpsRange()) {
        if (legacyFps[0] == range[0] && legacyFps[1] == range[1]) {
          supported = true;
          break;
        }
      }
      if (supported) {
        params.setPreviewFpsRange(
            legacyFps[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
            legacyFps[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
      } else {
        Log.w(TAG, "Unsupported FPS range set [" + legacyFps[0] + "," + legacyFps[1] + "]");
      }
    }

    /*
     * control
     */

    // control.aeExposureCompensation
    {
      Range<Integer> compensationRange =
          characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE);
      int compensation =
          ParamsUtils.getOrDefault(request, CONTROL_AE_EXPOSURE_COMPENSATION, /*defaultValue*/ 0);

      if (!compensationRange.contains(compensation)) {
        Log.w(
            TAG,
            "convertRequestMetadata - control.aeExposureCompensation "
                + "is out of range, ignoring value");
        compensation = 0;
      }

      params.setExposureCompensation(compensation);
    }

    // control.aeLock
    {
      Boolean aeLock =
          getIfSupported(
              request,
              CONTROL_AE_LOCK, /*defaultValue*/
              false,
              params.isAutoExposureLockSupported(),
              /*allowedValue*/ false);

      if (aeLock != null) {
        params.setAutoExposureLock(aeLock);
      }

      if (VERBOSE) {
        Log.v(TAG, "convertRequestToMetadata - control.aeLock set to " + aeLock);
      }

      // TODO: Don't add control.aeLock to availableRequestKeys if it's not supported
    }

    // control.aeMode, flash.mode
    mapAeAndFlashMode(request, /*out*/ params);

    // control.afMode
    {
      int afMode =
          ParamsUtils.getOrDefault(request, CONTROL_AF_MODE, /*defaultValue*/ CONTROL_AF_MODE_OFF);
      String focusMode =
          LegacyMetadataMapper.convertAfModeToLegacy(afMode, params.getSupportedFocusModes());

      if (focusMode != null) {
        params.setFocusMode(focusMode);
      }

      if (VERBOSE) {
        Log.v(
            TAG, "convertRequestToMetadata - control.afMode " + afMode + " mapped to " + focusMode);
      }
    }

    // control.awbMode
    {
      Integer awbMode =
          getIfSupported(
              request,
              CONTROL_AWB_MODE,
              /*defaultValue*/ CONTROL_AWB_MODE_AUTO,
              params.getSupportedWhiteBalance() != null,
              /*allowedValue*/ CONTROL_AWB_MODE_AUTO);

      String whiteBalanceMode = null;
      if (awbMode != null) { // null iff AWB is not supported by camera1 api
        whiteBalanceMode = convertAwbModeToLegacy(awbMode);
        params.setWhiteBalance(whiteBalanceMode);
      }

      if (VERBOSE) {
        Log.v(
            TAG,
            "convertRequestToMetadata - control.awbMode "
                + awbMode
                + " mapped to "
                + whiteBalanceMode);
      }
    }

    // control.awbLock
    {
      Boolean awbLock =
          getIfSupported(
              request,
              CONTROL_AWB_LOCK, /*defaultValue*/
              false,
              params.isAutoWhiteBalanceLockSupported(),
              /*allowedValue*/ false);

      if (awbLock != null) {
        params.setAutoWhiteBalanceLock(awbLock);
      }

      // TODO: Don't add control.awbLock to availableRequestKeys if it's not supported
    }

    // control.captureIntent
    {
      int captureIntent =
          ParamsUtils.getOrDefault(
              request, CONTROL_CAPTURE_INTENT, /*defaultValue*/ CONTROL_CAPTURE_INTENT_PREVIEW);

      captureIntent = filterSupportedCaptureIntent(captureIntent);

      params.setRecordingHint(
          captureIntent == CONTROL_CAPTURE_INTENT_VIDEO_RECORD
              || captureIntent == CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT);
    }

    // control.videoStabilizationMode
    {
      Integer stabMode =
          getIfSupported(
              request,
              CONTROL_VIDEO_STABILIZATION_MODE,
              /*defaultValue*/ CONTROL_VIDEO_STABILIZATION_MODE_OFF,
              params.isVideoStabilizationSupported(),
              /*allowedValue*/ CONTROL_VIDEO_STABILIZATION_MODE_OFF);

      if (stabMode != null) {
        params.setVideoStabilization(stabMode == CONTROL_VIDEO_STABILIZATION_MODE_ON);
      }
    }

    // lens.focusDistance
    {
      boolean infinityFocusSupported =
          ListUtils.listContains(params.getSupportedFocusModes(), Parameters.FOCUS_MODE_INFINITY);
      Float focusDistance =
          getIfSupported(
              request,
              LENS_FOCUS_DISTANCE,
              /*defaultValue*/ 0f,
              infinityFocusSupported, /*allowedValue*/
              0f);

      if (focusDistance == null || focusDistance != 0f) {
        Log.w(
            TAG,
            "convertRequestToMetadata - Ignoring android.lens.focusDistance "
                + infinityFocusSupported
                + ", only 0.0f is supported");
      }
    }

    // control.sceneMode, control.mode
    {
      // TODO: Map FACE_PRIORITY scene mode to face detection.

      if (params.getSupportedSceneModes() != null) {
        int controlMode =
            ParamsUtils.getOrDefault(request, CONTROL_MODE, /*defaultValue*/ CONTROL_MODE_AUTO);
        String modeToSet;
        switch (controlMode) {
          case CONTROL_MODE_USE_SCENE_MODE:
            {
              int sceneMode =
                  ParamsUtils.getOrDefault(
                      request, CONTROL_SCENE_MODE, /*defaultValue*/ CONTROL_SCENE_MODE_DISABLED);
              String legacySceneMode = LegacyMetadataMapper.convertSceneModeToLegacy(sceneMode);
              if (legacySceneMode != null) {
                modeToSet = legacySceneMode;
              } else {
                modeToSet = Parameters.SCENE_MODE_AUTO;
                Log.w(TAG, "Skipping unknown requested scene mode: " + sceneMode);
              }
              break;
            }
          case CONTROL_MODE_AUTO:
            {
              modeToSet = Parameters.SCENE_MODE_AUTO;
              break;
            }
          default:
            {
              Log.w(TAG, "Control mode " + controlMode + " is unsupported, defaulting to AUTO");
              modeToSet = Parameters.SCENE_MODE_AUTO;
            }
        }
        params.setSceneMode(modeToSet);
      }
    }

    // control.effectMode
    {
      if (params.getSupportedColorEffects() != null) {
        int effectMode =
            ParamsUtils.getOrDefault(
                request, CONTROL_EFFECT_MODE, /*defaultValue*/ CONTROL_EFFECT_MODE_OFF);
        String legacyEffectMode = LegacyMetadataMapper.convertEffectModeToLegacy(effectMode);
        if (legacyEffectMode != null) {
          params.setColorEffect(legacyEffectMode);
        } else {
          params.setColorEffect(Parameters.EFFECT_NONE);
          Log.w(TAG, "Skipping unknown requested effect mode: " + effectMode);
        }
      }
    }

    /*
     * sensor
     */

    // sensor.testPattern
    {
      int testPatternMode =
          ParamsUtils.getOrDefault(
              request, SENSOR_TEST_PATTERN_MODE, /*defaultValue*/ SENSOR_TEST_PATTERN_MODE_OFF);
      if (testPatternMode != SENSOR_TEST_PATTERN_MODE_OFF) {
        Log.w(
            TAG,
            "convertRequestToMetadata - ignoring sensor.testPatternMode "
                + testPatternMode
                + "; only OFF is supported");
      }
    }

    /*
     * jpeg.*
     */

    // jpeg.gpsLocation
    {
      Location location = request.get(JPEG_GPS_LOCATION);
      if (location != null) {
        if (checkForCompleteGpsData(location)) {
          params.setGpsAltitude(location.getAltitude());
          params.setGpsLatitude(location.getLatitude());
          params.setGpsLongitude(location.getLongitude());
          params.setGpsProcessingMethod(location.getProvider().toUpperCase());
          params.setGpsTimestamp(location.getTime());
        } else {
          Log.w(TAG, "Incomplete GPS parameters provided in location " + location);
        }
      } else {
        params.removeGpsData();
      }
    }

    // jpeg.orientation
    {
      Integer orientation = request.get(CaptureRequest.JPEG_ORIENTATION);
      params.setRotation(
          ParamsUtils.getOrDefault(
              request, JPEG_ORIENTATION, (orientation == null) ? 0 : orientation));
    }

    // jpeg.quality
    {
      params.setJpegQuality(
          0xFF & ParamsUtils.getOrDefault(request, JPEG_QUALITY, DEFAULT_JPEG_QUALITY));
    }

    // jpeg.thumbnailQuality
    {
      params.setJpegThumbnailQuality(
          0xFF & ParamsUtils.getOrDefault(request, JPEG_THUMBNAIL_QUALITY, DEFAULT_JPEG_QUALITY));
    }

    // jpeg.thumbnailSize
    {
      List<Camera.Size> sizes = params.getSupportedJpegThumbnailSizes();

      if (sizes != null && sizes.size() > 0) {
        Size s = request.get(JPEG_THUMBNAIL_SIZE);
        boolean invalidSize =
            (s == null) ? false : !ParameterUtils.containsSize(sizes, s.getWidth(), s.getHeight());
        if (invalidSize) {
          Log.w(TAG, "Invalid JPEG thumbnail size set " + s + ", skipping thumbnail...");
        }
        if (s == null || invalidSize) {
          // (0,0) = "no thumbnail" in Camera API 1
          params.setJpegThumbnailSize(/*width*/ 0, /*height*/ 0);
        } else {
          params.setJpegThumbnailSize(s.getWidth(), s.getHeight());
        }
      }
    }

    /*
     * noiseReduction.*
     */
    // noiseReduction.mode
    {
      int mode =
          ParamsUtils.getOrDefault(
              request, NOISE_REDUCTION_MODE, /*defaultValue*/ NOISE_REDUCTION_MODE_FAST);

      if (mode != NOISE_REDUCTION_MODE_FAST) {
        Log.w(
            TAG,
            "convertRequestToMetadata - Ignoring unsupported " + "noiseReduction.mode = " + mode);
      }
    }
  }
  // (Re)start preview with the closest supported format to |width| x |height| @ |framerate|.
  private void startPreviewOnCameraThread(int width, int height, int framerate) {
    checkIsOnCameraThread();
    Logging.d(
        TAG, "startPreviewOnCameraThread requested: " + width + "x" + height + "@" + framerate);
    if (camera == null) {
      Logging.e(TAG, "Calling startPreviewOnCameraThread on stopped camera.");
      return;
    }

    requestedWidth = width;
    requestedHeight = height;
    requestedFramerate = framerate;

    // Find closest supported format for |width| x |height| @ |framerate|.
    final Camera.Parameters parameters = camera.getParameters();
    final int[] range = CameraEnumerationAndroid.getFramerateRange(parameters, framerate * 1000);
    final Camera.Size previewSize =
        CameraEnumerationAndroid.getClosestSupportedSize(
            parameters.getSupportedPreviewSizes(), width, height);
    final CaptureFormat captureFormat =
        new CaptureFormat(
            previewSize.width,
            previewSize.height,
            range[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
            range[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);

    // Check if we are already using this capture format, then we don't need to do anything.
    if (captureFormat.equals(this.captureFormat)) {
      return;
    }

    // Update camera parameters.
    Logging.d(TAG, "isVideoStabilizationSupported: " + parameters.isVideoStabilizationSupported());
    if (parameters.isVideoStabilizationSupported()) {
      parameters.setVideoStabilization(true);
    }
    // Note: setRecordingHint(true) actually decrease frame rate on N5.
    // parameters.setRecordingHint(true);
    if (captureFormat.maxFramerate > 0) {
      parameters.setPreviewFpsRange(captureFormat.minFramerate, captureFormat.maxFramerate);
    }
    parameters.setPreviewSize(captureFormat.width, captureFormat.height);
    parameters.setPreviewFormat(captureFormat.imageFormat);
    // Picture size is for taking pictures and not for preview/video, but we need to set it anyway
    // as a workaround for an aspect ratio problem on Nexus 7.
    final Camera.Size pictureSize =
        CameraEnumerationAndroid.getClosestSupportedSize(
            parameters.getSupportedPictureSizes(), width, height);
    parameters.setPictureSize(pictureSize.width, pictureSize.height);

    // Temporarily stop preview if it's already running.
    if (this.captureFormat != null) {
      camera.stopPreview();
      dropNextFrame = true;
      // Calling |setPreviewCallbackWithBuffer| with null should clear the internal camera buffer
      // queue, but sometimes we receive a frame with the old resolution after this call anyway.
      camera.setPreviewCallbackWithBuffer(null);
    }

    // (Re)start preview.
    Logging.d(TAG, "Start capturing: " + captureFormat);
    this.captureFormat = captureFormat;

    List<String> focusModes = parameters.getSupportedFocusModes();
    if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
      parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
    }

    camera.setParameters(parameters);
    if (!isCapturingToTexture) {
      videoBuffers.queueCameraBuffers(captureFormat.frameSize(), camera);
      camera.setPreviewCallbackWithBuffer(this);
    }
    camera.startPreview();
  }
예제 #23
0
  @TargetApi(11)
  protected boolean initializeCamera(int width, int height) {
    Log.d(TAG, "Initialize java camera");
    boolean result = true;
    synchronized (this) {
      mCamera = null;

      if (mCameraIndex == -1) {
        Log.d(TAG, "Trying to open camera with old open()");
        try {
          mCamera = Camera.open();
        } catch (Exception e) {
          Log.e(
              TAG,
              "Camera is not available (in use or does not exist): " + e.getLocalizedMessage());
        }

        if (mCamera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          boolean connected = false;
          for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
            Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")");
            try {
              mCamera = Camera.open(camIdx);
              connected = true;
            } catch (RuntimeException e) {
              Log.e(TAG, "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage());
            }
            if (connected) break;
          }
        }
      } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(mCameraIndex) + ")");
          try {
            mCamera = Camera.open(mCameraIndex);
          } catch (RuntimeException e) {
            Log.e(TAG, "Camera #" + mCameraIndex + "failed to open: " + e.getLocalizedMessage());
          }
        }
      }

      if (mCamera == null) return false;

      /* Now set camera parameters */
      try {
        Camera.Parameters params = mCamera.getParameters();
        Log.d(TAG, "getSupportedPreviewSizes()");
        List<android.hardware.Camera.Size> sizes = params.getSupportedPreviewSizes();

        if (sizes != null) {
          /* Select the size that fits surface considering maximum size allowed */
          Size frameSize =
              calculateCameraFrameSize(sizes, new JavaCameraSizeAccessor(), width, height);

          params.setPreviewFormat(ImageFormat.NV21);
          Log.d(
              TAG,
              "Set preview size to "
                  + Integer.valueOf((int) frameSize.width)
                  + "x"
                  + Integer.valueOf((int) frameSize.height));
          params.setPreviewSize((int) frameSize.width, (int) frameSize.height);

          List<String> FocusModes = params.getSupportedFocusModes();
          if (FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
          }

          mCamera.setParameters(params);
          params = mCamera.getParameters();

          mFrameWidth = params.getPreviewSize().width;
          mFrameHeight = params.getPreviewSize().height;

          if (mFpsMeter != null) {
            mFpsMeter.setResolution(mFrameWidth, mFrameHeight);
          }

          int size = mFrameWidth * mFrameHeight;
          size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
          mBuffer = new byte[size];

          mCamera.addCallbackBuffer(mBuffer);
          mCamera.setPreviewCallbackWithBuffer(this);

          mBaseMat = new Mat(mFrameHeight + (mFrameHeight / 2), mFrameWidth, CvType.CV_8UC1);

          mFrameChain = new Mat[2];
          mFrameChain[0] = new Mat();
          mFrameChain[1] = new Mat();

          AllocateCache();

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mSurfaceTexture = new SurfaceTexture(MAGIC_TEXTURE_ID);
            getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            mCamera.setPreviewTexture(mSurfaceTexture);
          } else mCamera.setPreviewDisplay(null);

          /* Finally we are ready to start the preview */
          Log.d(TAG, "startPreview");
          mCamera.startPreview();
        } else result = false;
      } catch (Exception e) {
        result = false;
        e.printStackTrace();
      }
    }

    return result;
  }
예제 #24
0
  void setDesiredCameraParameters(Camera camera, boolean safeMode) {
    Camera.Parameters parameters = camera.getParameters();

    if (parameters == null) {
      Log.w(
          TAG,
          "Device error: no camera parameters are available. Proceeding without configuration.");
      return;
    }

    Log.i(TAG, "Initial camera parameters: " + parameters.flatten());

    if (safeMode) {
      Log.w(TAG, "In camera config safe mode -- most settings will not be honored");
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    initializeTorch(parameters, prefs, safeMode);

    String focusMode = null;
    if (prefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true)) {
      if (safeMode || prefs.getBoolean(PreferencesActivity.KEY_DISABLE_CONTINUOUS_FOCUS, false)) {
        focusMode =
            findSettableValue(
                parameters.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_AUTO);
      } else {
        focusMode =
            findSettableValue(
                parameters.getSupportedFocusModes(),
                Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
                Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
                Camera.Parameters.FOCUS_MODE_AUTO);
      }
    }
    // Maybe selected auto-focus but not available, so fall through here:
    if (!safeMode && focusMode == null) {
      focusMode =
          findSettableValue(
              parameters.getSupportedFocusModes(),
              Camera.Parameters.FOCUS_MODE_MACRO,
              Camera.Parameters.FOCUS_MODE_EDOF);
    }
    if (focusMode != null) {
      parameters.setFocusMode(focusMode);
    }

    if (prefs.getBoolean(PreferencesActivity.KEY_INVERT_SCAN, false)) {
      String colorMode =
          findSettableValue(
              parameters.getSupportedColorEffects(), Camera.Parameters.EFFECT_NEGATIVE);
      if (colorMode != null) {
        parameters.setColorEffect(colorMode);
      }
    }

    parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
    camera.setParameters(parameters);

    Camera.Parameters afterParameters = camera.getParameters();
    Camera.Size afterSize = afterParameters.getPreviewSize();
    if (afterSize != null
        && (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) {
      Log.w(
          TAG,
          "Camera said it supported preview size "
              + cameraResolution.x
              + 'x'
              + cameraResolution.y
              + ", but after setting it, preview size is "
              + afterSize.width
              + 'x'
              + afterSize.height);
      cameraResolution.x = afterSize.width;
      cameraResolution.y = afterSize.height;
    }
  }
예제 #25
0
  /**
   * This is called immediately after any structural changes (format or size) have been made to the
   * surface. You should at this point update the imagery in the surface. This method is always
   * called at least once, after surfaceCreated(SurfaceHolder).
   *
   * @param holder The surface holder
   * @param format Format for the surface
   * @param w The width
   * @param h The height
   */
  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Check if the preview is running, if it is stop the preview
    if (mPreviewRunning) {
      mCamera.stopPreview();
    }

    String sizePref = "";
    sizePref = prefs.getString("resolution", "Not Present");
    String prevSizePref = "";
    prevSizePref = prefs.getString("previewresolution", "Not Present");

    Camera.Parameters p = mCamera.getParameters();
    // If no camera size is found in the shared preferences get the largest
    // supported size and set the picture size to that size
    if (sizePref.equals("Not Present")) {
      List<Size> sizes = p.getSupportedPictureSizes();
      Size s = sizes.get(0);
      for (Size size : sizes) {
        if (size.width > s.width) {
          s = size;
        }
      }
      p.setPictureSize(s.width, s.height);
    } else {
      // Set to the users specified camera size
      String[] userResolution = sizePref.split(":");
      p.setPictureSize(Integer.valueOf(userResolution[0]), Integer.valueOf(userResolution[1]));
    }

    // If no preview size is found in the shared preferences get the first
    // supported size and set the preview size to that size
    if (prevSizePref.equals("Not Present")) {
      // Use the first supported preview size
      List<Size> previewSizes = p.getSupportedPreviewSizes();
      p.setPreviewSize(previewSizes.get(0).width, previewSizes.get(0).height);
    } else {
      // Set to the users specified preview size
      String[] userResolution = prevSizePref.split(":");
      p.setPreviewSize(Integer.valueOf(userResolution[0]), Integer.valueOf(userResolution[1]));
    }

    // Set the focus mode to infinity
    List<String> focusModes = p.getSupportedFocusModes();
    for (String str : focusModes) {
      if (str.equalsIgnoreCase("infinity")) {
        p.setFocusMode(str);
      }
    }

    try {
      // Set the camera parameters
      mCamera.setParameters(p);
    } catch (Exception e) {
      Toast.makeText(ctx, "Error occurred while setting parameters...", Toast.LENGTH_SHORT).show();
    }
    try {
      // Set the preview to the holder
      mCamera.setPreviewDisplay(holder);
    } catch (IOException e) {
      e.printStackTrace();
    }
    // Start the preview
    mCamera.startPreview();
    mPreviewRunning = true;
  }
예제 #26
0
 /**
  * 打印支持的聚焦模式
  *
  * @param params
  */
 public void printSupportFocusMode(Camera.Parameters params) {
   List<String> focusModes = params.getSupportedFocusModes();
   for (String mode : focusModes) {
     Log.i(TAG, "focusModes--" + mode);
   }
 }
예제 #27
0
    @Override
    protected Boolean doInBackground(Void... args) {
      if (opened) return true;

      try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          // Choose the first back-facing camera
          boolean cameraAvailable = false;
          final CameraInfo cameraInfo = new CameraInfo();
          int cameraId = 0;
          while (!cameraAvailable && cameraId < Camera.getNumberOfCameras()) {
            Camera.getCameraInfo(cameraId, cameraInfo);
            if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) cameraAvailable = true;
            else cameraId++;
          }
          if (!cameraAvailable) return false; // No back-facing camera available...
          camera = Camera.open(cameraId);
          cameraOrientation = cameraInfo.orientation;
        } else {
          camera = Camera.open();
          cameraOrientation = 90; // TODO Is this correct?
        }
        if (camera == null) return false; // No camera available...
        final Camera.Parameters params = camera.getParameters();

        // Set the maximum resolution based on the maximum heap size
        final int maxHeapSize =
            ((ActivityManager)
                    context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE))
                .getMemoryClass();
        final int maxResolution =
            Math.min(
                5 * 1024 * 1024,
                maxHeapSize
                    * 1024
                    * 1024
                    / 4
                    / 3); // Each image might take up to 33% of the maximum heap size and 5
                          // megapixels at most
        // System.err.println("max heap size: " + maxHeapSize);
        // System.err.println("max resolution: " + maxResolution);

        // Choose the biggest possible picture size within the limits and the corresponding preview
        // sizes with the same ratio
        pictureSize = null;
        previewSizes = new ArrayList<Size>();
        final List<Size> supportedPictureSizes = params.getSupportedPictureSizes();
        final List<Size> supportedPreviewSizes = params.getSupportedPreviewSizes();
        Collections.sort(supportedPictureSizes, Collections.reverseOrder(sizeComparator));
        for (Size supportedPictureSize : supportedPictureSizes) {
          for (Size supportedPreviewSize : supportedPreviewSizes) {
            if (supportedPictureSize.width * supportedPreviewSize.height
                    == supportedPictureSize.height * supportedPreviewSize.width
                && supportedPictureSize.width * supportedPictureSize.height <= maxResolution) {
              pictureSize = supportedPictureSize;
              previewSizes.add(supportedPreviewSize);
            }
          }
          if (pictureSize != null) break;
        }
        // System.err.println("Selected resolution: " + pictureSize.width + "x" +
        // pictureSize.height);
        Collections.sort(previewSizes, Collections.reverseOrder(sizeComparator));
        if (pictureSize
            == null) { // No picture size ratio and preview size ratio match (shouldn't happen...)
          releaseCamera();
          return false;
        }

        // Set parameters
        final List<String> supportedWhiteBalance = params.getSupportedWhiteBalance();
        final List<String> supportedFlashModes = params.getSupportedFlashModes();
        final List<String> supportedSceneModes = params.getSupportedSceneModes();
        final List<String> supportedFocusModes = params.getSupportedFocusModes();
        params.setPictureSize(pictureSize.width, pictureSize.height);
        params.setPreviewSize(previewSizes.get(0).width, previewSizes.get(0).height);
        if (supportedWhiteBalance != null
            && supportedWhiteBalance.contains(Camera.Parameters.WHITE_BALANCE_AUTO)) {
          params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
        }
        if (supportedFlashModes != null
            && supportedFlashModes.contains(Camera.Parameters.FLASH_MODE_AUTO)) {
          params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
        }
        if (supportedSceneModes != null
            && supportedSceneModes.contains(Camera.Parameters.SCENE_MODE_AUTO)) {
          params.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
        }
        // TODO Decide the preferred focus mode order
        if (supportedFocusModes != null
            && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
          params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
          autofocus = true;
        } else if (supportedFocusModes != null
            && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
          params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
          autofocus = true;
        } else if (supportedFocusModes != null
            && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
          params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
          autofocus = false;
        } else {
          autofocus = false;
        }
        camera.setParameters(params);
      } catch (Exception e) {
        releaseCamera();
        return false; // Some error while opening the camera...
      }

      opened = true;
      return true;
    }
  protected boolean initializeCamera(int width, int height) {
    Log.d(TAG, "Initialize java camera");
    boolean result = true;
    synchronized (this) {
      mCamera = null;

      if (mCameraIndex == CAMERA_ID_ANY) {
        Log.d(TAG, "Trying to open camera with old open()");
        try {
          mCamera = Camera.open();
        } catch (Exception e) {
          Log.e(
              TAG,
              "Camera is not available (in use or does not exist): " + e.getLocalizedMessage());
        }

        if (mCamera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          boolean connected = false;
          for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
            Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")");
            try {
              mCamera = Camera.open(camIdx);
              connected = true;
            } catch (RuntimeException e) {
              Log.e(TAG, "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage());
            }
            if (connected) break;
          }
        }
      } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          int localCameraIndex = mCameraIndex;
          if (mCameraIndex == CAMERA_ID_BACK) {
            Log.i(TAG, "Trying to open back camera");
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
              Camera.getCameraInfo(camIdx, cameraInfo);
              if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                localCameraIndex = camIdx;
                break;
              }
            }
          } else if (mCameraIndex == CAMERA_ID_FRONT) {
            Log.i(TAG, "Trying to open front camera");
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
              Camera.getCameraInfo(camIdx, cameraInfo);
              if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                localCameraIndex = camIdx;
                break;
              }
            }
          }
          if (localCameraIndex == CAMERA_ID_BACK) {
            Log.e(TAG, "Back camera not found!");
          } else if (localCameraIndex == CAMERA_ID_FRONT) {
            Log.e(TAG, "Front camera not found!");
          } else {
            Log.d(
                TAG,
                "Trying to open camera with new open(" + Integer.valueOf(localCameraIndex) + ")");
            try {
              mCamera = Camera.open(localCameraIndex);
            } catch (RuntimeException e) {
              Log.e(
                  TAG,
                  "Camera #" + localCameraIndex + "failed to open: " + e.getLocalizedMessage());
            }
          }
        }
      }

      if (mCamera == null) return false;

      /* Now set camera parameters */
      try {
        Camera.Parameters params = mCamera.getParameters();
        Log.d(TAG, "getSupportedPreviewSizes()");
        List<android.hardware.Camera.Size> sizes = params.getSupportedPreviewSizes();

        if (sizes != null) {
          /* Select the size that fits surface considering maximum size allowed */
          Size frameSize =
              calculateCameraFrameSize(sizes, new JavaCameraSizeAccessor(), width, height);

          params.setPreviewFormat(ImageFormat.NV21);
          Log.d(
              TAG,
              "Set preview size to "
                  + Integer.valueOf((int) frameSize.width)
                  + "x"
                  + Integer.valueOf((int) frameSize.height));
          params.setPreviewSize((int) frameSize.width, (int) frameSize.height);

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
              && !android.os.Build.MODEL.equals("GT-I9100")) params.setRecordingHint(true);

          List<String> FocusModes = params.getSupportedFocusModes();
          if (FocusModes != null
              && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
          }

          mCamera.setParameters(params);
          params = mCamera.getParameters();

          mFrameWidth = params.getPreviewSize().width;
          mFrameHeight = params.getPreviewSize().height;

          if ((getLayoutParams().width == LayoutParams.MATCH_PARENT)
              && (getLayoutParams().height == LayoutParams.MATCH_PARENT))
            mScale = Math.min(((float) height) / mFrameHeight, ((float) width) / mFrameWidth);
          else mScale = 0;

          if (mFpsMeter != null) {
            mFpsMeter.setResolution(mFrameWidth, mFrameHeight);
          }

          int size = mFrameWidth * mFrameHeight;
          size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
          mBuffer = new byte[size];

          mCamera.addCallbackBuffer(mBuffer);
          mCamera.setPreviewCallbackWithBuffer(this);

          mFrameChain = new Mat[2];
          mFrameChain[0] = new Mat(mFrameHeight + (mFrameHeight / 2), mFrameWidth, CvType.CV_8UC1);
          mFrameChain[1] = new Mat(mFrameHeight + (mFrameHeight / 2), mFrameWidth, CvType.CV_8UC1);

          AllocateCache();

          mCameraFrame = new JavaCameraFrame[2];
          mCameraFrame[0] = new JavaCameraFrame(mFrameChain[0], mFrameWidth, mFrameHeight);
          mCameraFrame[1] = new JavaCameraFrame(mFrameChain[1], mFrameWidth, mFrameHeight);

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mSurfaceTexture = new SurfaceTexture(MAGIC_TEXTURE_ID);
            mCamera.setPreviewTexture(mSurfaceTexture);
          } else mCamera.setPreviewDisplay(null);

          /* Finally we are ready to start the preview */
          Log.d(TAG, "startPreview");
          mCamera.startPreview();
        } else result = false;
      } catch (Exception e) {
        result = false;
        e.printStackTrace();
      }
    }

    return result;
  }
예제 #29
0
  /**
   * Opens the camera and applies the user settings.
   *
   * @throws RuntimeException if the method fails
   */
  @SuppressLint("InlinedApi")
  private Camera createCamera() {
    int requestedCameraId = getIdForRequestedCamera(mFacing);
    if (requestedCameraId == -1) {
      throw new RuntimeException(mContext.getString(R.string.no_requested_camera));
    }
    Camera camera = Camera.open(requestedCameraId);

    SizePair sizePair =
        selectSizePair(camera, mRequestedPreviewWidth, mRequestedPreviewHeight, mContext);
    if (sizePair == null) {
      throw new RuntimeException(mContext.getString(R.string.no_suitable_preview_size));
    }
    Size pictureSize = sizePair.pictureSize();
    mPreviewSize = sizePair.previewSize();

    int[] previewFpsRange = selectPreviewFpsRange(camera, mRequestedFps);
    if (previewFpsRange == null) {
      throw new RuntimeException(mContext.getString(R.string.no_suitable_frames_per_second));
    }

    Camera.Parameters parameters = camera.getParameters();

    parameters.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight());
    parameters.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    parameters.setPreviewFpsRange(
        previewFpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
        previewFpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
    parameters.setPreviewFormat(ImageFormat.NV21);

    setRotation(camera, parameters, requestedCameraId);

    if (mFocusMode != null) {
      if (parameters.getSupportedFocusModes().contains(mFocusMode)) {
        parameters.setFocusMode(mFocusMode);
      } else {
        Log.i(
            TAG,
            mContext.getString(R.string.camera_focus_mode)
                + mFocusMode
                + mContext.getString(R.string.not_supported));
      }
    }

    // setting mFocusMode to the one set in the params
    mFocusMode = parameters.getFocusMode();

    if (mFlashMode != null) {
      if (parameters.getSupportedFlashModes().contains(mFlashMode)) {
        parameters.setFlashMode(mFlashMode);
      } else {
        Log.i(
            TAG,
            mContext.getString(R.string.flash_mode)
                + mFlashMode
                + mContext.getString(R.string.not_supported));
      }
    }

    // setting mFlashMode to the one set in the params
    mFlashMode = parameters.getFlashMode();

    camera.setParameters(parameters);

    // Four frame buffers are needed for working with the camera:
    //
    //   one for the frame that is currently being executed upon in doing detection
    //   one for the next pending frame to process immediately upon completing detection
    //   two for the frames that the camera uses to populate future preview images
    camera.setPreviewCallbackWithBuffer(new CameraPreviewCallback());
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));

    return camera;
  }