private int tryStartCapture(int width, int height, int frameRate) {
    if (camera == null) {
      Log.e(TAG, "Camera not initialized %d" + id);
      return -1;
    }

    Log.d(
        TAG,
        "tryStartCapture: "
            + width
            + "x"
            + height
            + ", frameRate: "
            + frameRate
            + ", isCaptureRunning: "
            + isCaptureRunning
            + ", isSurfaceReady: "
            + isSurfaceReady
            + ", isCaptureStarted: "
            + isCaptureStarted);

    if (isCaptureRunning || !isCaptureStarted) {
      return 0;
    }

    CaptureCapabilityAndroid currentCapability = new CaptureCapabilityAndroid();
    currentCapability.width = width;
    currentCapability.height = height;
    currentCapability.maxFPS = frameRate;
    PixelFormat.getPixelFormatInfo(PIXEL_FORMAT, pixelFormat);

    Camera.Parameters parameters = camera.getParameters();
    parameters.setPreviewSize(currentCapability.width, currentCapability.height);
    parameters.setPreviewFormat(PIXEL_FORMAT);
    parameters.setPreviewFrameRate(currentCapability.maxFPS);
    try {
      camera.setParameters(parameters);
    } catch (RuntimeException e) {
      Log.e(TAG, "setParameters failed", e);
      return -1;
    }

    int bufSize = width * height * pixelFormat.bitsPerPixel / 8;
    byte[] buffer = null;
    for (int i = 0; i < numCaptureBuffers; i++) {
      buffer = new byte[bufSize];
      camera.addCallbackBuffer(buffer);
    }
    camera.setPreviewCallbackWithBuffer(this);
    ownsBuffers = true;

    camera.startPreview();
    previewBufferLock.lock();
    expectedFrameSize = bufSize;
    isCaptureRunning = true;
    previewBufferLock.unlock();

    return 0;
  }
  // Called by native code.  Returns true if capturer is started.
  //
  // Note that this actually opens the camera, which can be a slow operation and
  // thus might be done on a background thread, but ViE API needs a
  // synchronous success return value so we can't do that.
  private synchronized boolean startCapture(int width, int height, int min_mfps, int max_mfps) {
    Log.d(TAG, "startCapture: " + width + "x" + height + "@" + min_mfps + ":" + max_mfps);
    Throwable error = null;
    try {
      camera = Camera.open(id);

      localPreview = ViERenderer.GetLocalRenderer();
      if (localPreview != null) {
        localPreview.addCallback(this);
        if (localPreview.getSurface() != null && localPreview.getSurface().isValid()) {
          camera.setPreviewDisplay(localPreview);
        }
      } else {
        // No local renderer (we only care about onPreviewFrame() buffers, not a
        // directly-displayed UI element).  Camera won't capture without
        // setPreview{Texture,Display}, so we create a dummy SurfaceTexture and
        // hand it over to Camera, but never listen for frame-ready callbacks,
        // and never call updateTexImage on it.
        try {
          // "42" because http://goo.gl/KaEn8
          dummySurfaceTexture = new SurfaceTexture(42);
          camera.setPreviewTexture(dummySurfaceTexture);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }

      Camera.Parameters parameters = camera.getParameters();
      Log.d(TAG, "isVideoStabilizationSupported: " + parameters.isVideoStabilizationSupported());
      if (parameters.isVideoStabilizationSupported()) {
        parameters.setVideoStabilization(true);
      }
      parameters.setPreviewSize(width, height);
      parameters.setPreviewFpsRange(min_mfps, max_mfps);
      int format = ImageFormat.NV21;
      parameters.setPreviewFormat(format);
      camera.setParameters(parameters);
      int bufSize = width * height * ImageFormat.getBitsPerPixel(format) / 8;
      for (int i = 0; i < numCaptureBuffers; i++) {
        camera.addCallbackBuffer(new byte[bufSize]);
      }
      camera.setPreviewCallbackWithBuffer(this);
      camera.startPreview();
      return true;
    } catch (IOException e) {
      error = e;
    } catch (RuntimeException e) {
      error = e;
    }
    Log.e(TAG, "startCapture failed", error);
    if (camera != null) {
      stopCapture();
    }
    return false;
  }
Exemple #3
0
  private void initializeCamera() {

    Camera.Parameters p = mCamera.getParameters();
    // Hack for Samsung devices (e.g. Nexus 5) ; otherwise callback is never called
    // See http://stackoverflow.com/questions/5788993/use-android-camera-without-surface-view
    try {
      mCameraTexture = new SurfaceTexture(10);
      mCamera.setPreviewTexture(mCameraTexture);
    } catch (Throwable ignored) {

    }

    // Choose smallest preview size available
    List<Camera.Size> sizes = p.getSupportedPictureSizes();
    int bestIndex = -1;
    int pixelCount = Integer.MAX_VALUE;

    for (int i = 0; i < sizes.size(); i++) {
      int w = sizes.get(i).width, h = sizes.get(i).height;
      int count = w * h;
      if (count < pixelCount) {
        bestIndex = i;
        pixelCount = count; // Note pixelCount is reused below
      }
    }

    Camera.Size size = sizes.get(bestIndex);

    mCameraWidth = size.width;
    mCameraHeight = size.height;

    Log.d(TAG, "W:" + mCameraWidth + ",H:" + mCameraHeight + ", num pixels:" + pixelCount);
    mCameraDecodedRGB = new int[pixelCount];

    p.setPreviewSize(mCameraWidth, mCameraHeight);
    p.setPreviewFormat(ImageFormat.NV21);
    mCamera.setParameters(p);

    int bitsPerPixel = ImageFormat.getBitsPerPixel(p.getPreviewFormat());
    int bytes = (pixelCount * bitsPerPixel) / 8;
    // Double Buffer - allow a buffer to be filled with new data while we are using the other one
    mCamera.addCallbackBuffer(new byte[bytes]);
    mCamera.addCallbackBuffer(new byte[bytes]);

    mCamera.setPreviewCallbackWithBuffer(this);
    mPreviewRunning = true;

    mCamera.startPreview();
    Log.d(TAG, "startPreview()");
  }
  @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;
  }
  /**
   * 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;
  }
  // (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();
  }
  // Returns true on success, false otherwise.
  @CalledByNative
  public boolean allocate(int width, int height, int frameRate) {
    Log.d(TAG, "allocate: requested (" + width + "x" + height + ")@" + frameRate + "fps");
    try {
      mCamera = Camera.open(mId);
    } catch (RuntimeException ex) {
      Log.e(TAG, "allocate: Camera.open: " + ex);
      return false;
    }

    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    Camera.getCameraInfo(mId, cameraInfo);
    mCameraOrientation = cameraInfo.orientation;
    mCameraFacing = cameraInfo.facing;
    mDeviceOrientation = getDeviceOrientation();
    Log.d(
        TAG,
        "allocate: orientation dev="
            + mDeviceOrientation
            + ", cam="
            + mCameraOrientation
            + ", facing="
            + mCameraFacing);

    Camera.Parameters parameters = mCamera.getParameters();

    // getSupportedPreviewFpsRange() returns a List with at least one
    // element, but when camera is in bad state, it can return null pointer.
    List<int[]> listFpsRange = parameters.getSupportedPreviewFpsRange();
    if (listFpsRange == null || listFpsRange.size() == 0) {
      Log.e(TAG, "allocate: no fps range found");
      return false;
    }
    int frameRateInMs = frameRate * 1000;
    // Use the first range as default.
    int[] fpsMinMax = listFpsRange.get(0);
    int newFrameRate = (fpsMinMax[0] + 999) / 1000;
    for (int[] fpsRange : listFpsRange) {
      if (fpsRange[0] <= frameRateInMs && frameRateInMs <= fpsRange[1]) {
        fpsMinMax = fpsRange;
        newFrameRate = frameRate;
        break;
      }
    }
    frameRate = newFrameRate;
    Log.d(TAG, "allocate: fps set to " + frameRate);

    // Calculate size.
    List<Camera.Size> listCameraSize = parameters.getSupportedPreviewSizes();
    int minDiff = Integer.MAX_VALUE;
    int matchedWidth = width;
    int matchedHeight = height;
    for (Camera.Size size : listCameraSize) {
      int diff = Math.abs(size.width - width) + Math.abs(size.height - height);
      Log.d(TAG, "allocate: supported (" + size.width + ", " + size.height + "), diff=" + diff);
      // TODO(wjia): Remove this hack (forcing width to be multiple
      // of 32) by supporting stride in video frame buffer.
      // Right now, VideoCaptureController requires compact YV12
      // (i.e., with no padding).
      if (diff < minDiff && (size.width % 32 == 0)) {
        minDiff = diff;
        matchedWidth = size.width;
        matchedHeight = size.height;
      }
    }
    if (minDiff == Integer.MAX_VALUE) {
      Log.e(TAG, "allocate: can not find a multiple-of-32 resolution");
      return false;
    }

    mCaptureFormat =
        new CaptureFormat(matchedWidth, matchedHeight, frameRate, BuggyDeviceHack.getImageFormat());
    // Hack to avoid certain capture resolutions under a minimum one,
    // see http://crbug.com/305294
    BuggyDeviceHack.applyMinDimensions(mCaptureFormat);
    Log.d(TAG, "allocate: matched (" + mCaptureFormat.mWidth + "x" + mCaptureFormat.mHeight + ")");

    if (parameters.isVideoStabilizationSupported()) {
      Log.d(
          TAG,
          "Image stabilization supported, currently: "
              + parameters.getVideoStabilization()
              + ", setting it.");
      parameters.setVideoStabilization(true);
    } else {
      Log.d(TAG, "Image stabilization not supported.");
    }
    parameters.setPreviewSize(mCaptureFormat.mWidth, mCaptureFormat.mHeight);
    parameters.setPreviewFormat(mCaptureFormat.mPixelFormat);
    parameters.setPreviewFpsRange(fpsMinMax[0], fpsMinMax[1]);
    mCamera.setParameters(parameters);

    // Set SurfaceTexture. Android Capture needs a SurfaceTexture even if
    // it is not going to be used.
    mGlTextures = new int[1];
    // Generate one texture pointer and bind it as an external texture.
    GLES20.glGenTextures(1, mGlTextures, 0);
    GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mGlTextures[0]);
    // No mip-mapping with camera source.
    GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
    // Clamp to edge is only option.
    GLES20.glTexParameteri(
        GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
    GLES20.glTexParameteri(
        GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);

    mSurfaceTexture = new SurfaceTexture(mGlTextures[0]);
    mSurfaceTexture.setOnFrameAvailableListener(null);

    try {
      mCamera.setPreviewTexture(mSurfaceTexture);
    } catch (IOException ex) {
      Log.e(TAG, "allocate: " + ex);
      return false;
    }

    int bufSize =
        mCaptureFormat.mWidth
            * mCaptureFormat.mHeight
            * ImageFormat.getBitsPerPixel(mCaptureFormat.mPixelFormat)
            / 8;
    for (int i = 0; i < NUM_CAPTURE_BUFFERS; i++) {
      byte[] buffer = new byte[bufSize];
      mCamera.addCallbackBuffer(buffer);
    }
    mExpectedFrameSize = bufSize;

    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;
  }
  @Override
  public void surfaceCreated(SurfaceHolder arg0) {
    // TODO Auto-generated method stub
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, getActivity(), mLoaderCallback);
    mCamera = Camera.open();
    Camera.Parameters parameters = mCamera.getParameters();

    List<android.hardware.Camera.Size> sizes = parameters.getSupportedPreviewSizes();
    // if portrait frameSize , width is less than height
    Size frameSize =
        calculateCameraFrameSize(sizes, mSurface.getWidth(), mSurface.getHeight(), true);

    parameters.setPreviewSize((int) frameSize.height, (int) frameSize.width);
    parameters.set("orientation", "portrait");
    parameters.setPreviewFormat(ImageFormat.NV21);

    mFrameWidth = (int) frameSize.width;
    mFrameHeight = (int) frameSize.height;

    mCamera.setDisplayOrientation(90);

    try {
      mCamera.setPreviewDisplay(mHolder);
      mCamera.setParameters(parameters);
      mCamera.setPreviewCallback(this);
    } catch (Exception e) {

    }

    mZoomBar.setMax(mCamera.getParameters().getMaxZoom());
    mZoomBar.setProgress(mCamera.getParameters().getZoom());
    mZoomBar.setOnSeekBarChangeListener(
        new OnSeekBarChangeListener() {

          @Override
          public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
            // TODO Auto-generated method stub
            // modify zoom
            Camera.Parameters params = mCamera.getParameters();
            params.setZoom(arg1);
            mCamera.setParameters(params);

            mZoomBar.setProgress(arg1);
          }

          @Override
          public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

          }

          @Override
          public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

          }
        });

    mCamera.startPreview();
    mCamera.autoFocus(mAutoFocusCallback);
  }