VideoCFModule.java 32.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
package com.sw.laryngoscope.camera;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.location.Location;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.TextureView;
import android.view.View;

import com.sw.laryngoscope.R;
import com.sw.laryngoscope.activity.fragment.HomeFragment;
import com.sw.laryngoscope.common.InitParam;
import com.sw.laryngoscope.glsurface.GLUtil;
import com.sw.laryngoscope.glsurface.ImageUtil;
import com.sw.laryngoscope.glsurface.RoundCameraGLSurfaceView;
import com.sw.laryngoscope.manager.CameraInfoMg;
import com.sw.laryngoscope.manager.SpManager;
import com.sw.laryngoscope.utils.Exif;
import com.sw.laryngoscope.utils.Logger;
import com.sw.laryngoscope.utils.Storage;
import com.sw.laryngoscope.utils.Thumbnail;
import com.sw.laryngoscope.utils.TimeUtil;
import com.sw.laryngoscope.utils.exif.ExifInterface;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class VideoCFModule extends BaseModule implements MediaRecorder.OnErrorListener,
        MediaRecorder.OnInfoListener {

    private static final String TAG = "VideoCFModule";

    TextureView textureViewFront;
    RoundCameraGLSurfaceView roundCameraGLSurfaceView;

    private MediaRecorder mMediaRecorderFront;
    private CamcorderProfile mProfileFront;
    private String mVideoFilenameFront;

    private ContentValues mCurrentVideoValuesFront;

    private final Handler mHandler = new MainHandler();

    private int previewSizeWidth = 0;
    private int previewSizeHeight = 0;

    private SurfaceTexture mSurfaceTexture = null;
    private Rect cropRect = null;
    private byte[] squareNV21;

    public VideoCFModule() {
    }

    public void init(HomeFragment fragment, VideoUI videoUI, VideoManager videoManager) {
        this.fragment = fragment;
        mUI = videoUI;
        mVideoManager = videoManager;

        initCamera();
    }

    private void startVideoRecordingFront() {

        mRecordingStartTime = SystemClock.uptimeMillis();

        frontCamera.unlock();

        mMediaRecorderFront = new MediaRecorder();
        mMediaRecorderFront.setCamera(frontCamera);

        mMediaRecorderFront.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
        mMediaRecorderFront.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mProfileFront = CamcorderProfile.get(0, getVideoQuality(SpManager.getFrontCameraVideo()));//FACING_FRONT
        mMediaRecorderFront.setProfile(mProfileFront);
        //mMediaRecorderFront.setVideoSize(mProfileFront.videoFrameWidth, mProfileFront.videoFrameHeight);
        mMediaRecorderFront.setVideoSize(previewSizeWidth, previewSizeHeight);
        Logger.d("=======videoFrameWidth=============" + mProfileFront.videoFrameWidth + "==" + mProfileFront.videoFrameHeight);
        Logger.d("=======videoFrameWidth=============" + previewSizeWidth + "==" + previewSizeHeight);

        mMediaRecorderFront.setMaxDuration(mMaxVideoDurationInMs/* - 1000*/);

        /*try {
            mMediaRecorderFront.setMaxFileSize(Storage.getAvailableSpace() - Storage.LOW_STORAGE_THRESHOLD_BYTES);
        } catch (RuntimeException exception) {
        }*/
        mMediaRecorderFront.setOrientationHint(0);//180
        //mMediaRecorder.setVideoFrameRate(25);
        mVideoFilenameFront = generateVideoFilename(FACING_FRONT_ID);
        mMediaRecorderFront.setOutputFile(mVideoFilenameFront);
        Logger.d("====================" + mVideoFilenameFront + "=="
            + Storage.getAvailableSpace());

        mMediaRecorderFront.setOnErrorListener(this);
        mMediaRecorderFront.setOnInfoListener(this);

        try {
            mMediaRecorderFront.prepare();
            Logger.d("===============1=====");
        } catch (IOException e) {
            releaseMediaRecorderFront();
            throw new RuntimeException(e);
        }

        try {
            mMediaRecorderFront.start(); // Recording is now started
            Logger.d("========mMediaRecorderFront=======2=====");
        } catch (RuntimeException e) {
            releaseMediaRecorderFront();
            Logger.d("===============3=====");
            return;
        }

        mMediaRecorderRecording = true;

        mUI.showRecordingUIBack(true);
        updateRecordingTime();
    }


    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
            stopVideoRecordingFront();
        }
    }

    public void setFrontCamera(Camera frontCamera) {
        this.frontCamera = frontCamera;
    }

    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {
        Logger.d("==============5====1=" + what + " " + extra);
        if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
            if ( SystemClock.elapsedRealtime() - stopTime < 5000 ) {
                return ;
            }
            stopTime = SystemClock.elapsedRealtime();
            if (mMediaRecorderRecording) {
                mHandler.removeMessages(MSG_UPDATE_RECORD_TIME);
                String endTime = System.currentTimeMillis() + "";
                if ( !stopVideoRecordingFront() ) {
                    mUI.showRecordingUIBack(false);
                    return ;
                }

                mVideoManager.addVideoToDb(mCurrentVideoValuesFront.getAsString(Video.Media.TITLE),
                        mCurrentVideoValuesFront.getAsString(Video.Media.DISPLAY_NAME),
                        mCurrentVideoValuesFront.getAsString(Video.Media.DATE_TAKEN), endTime,
                        Storage.VIDEO_DIR, "procedure", timeStamp2Date(endTime,"HH:mm"),
                        mCurrentVideoValuesFront.getAsString(Video.Media.TITLE) + Storage.JPEG_POSTFIX,
                        Storage.VIDEO_THUMB,
                        System.currentTimeMillis() - Long.parseLong(mCurrentVideoValuesFront.getAsString(Video.Media.DATE_TAKEN)),
                        InitParam.FILE_VIDEO, InitParam.CAM_FRONT, previewSizeWidth, previewSizeHeight);

                Thumbnail.createVideoThumbnailBitmap(
                        Storage.VIDEO_DIR + "/" + mCurrentVideoValuesFront.getAsString(Video.Media.DISPLAY_NAME),
                        Storage.VIDEO_THUMB + "/" + mCurrentVideoValuesFront.getAsString(Video.Media.TITLE) + Storage.JPEG_POSTFIX,
                        textureViewFront.getBitmap());

                releaseMediaRecorderFront();

                Logger.d("==============5=====");
                startVideoRecordingFront();
            }
        } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
            if (mMediaRecorderRecording) {
                stopVideoRecordingFront();
            }
        }
    }

    private boolean stopVideoRecordingFront() {
        try {
            mMediaRecorderFront.setOnErrorListener(null);
            mMediaRecorderFront.setOnInfoListener(null);
            mMediaRecorderFront.stop();

            saveVideoFile(mVideoFilenameFront, mCurrentVideoValuesFront);
        } catch (RuntimeException e) {
            if (mVideoFilenameFront != null) {
                deleteVideoFile(mVideoFilenameFront);
            }
            mMediaRecorderRecording = false;
            return false;
        }
        mMediaRecorderRecording = false;
        return true;
    }

    private void releaseMediaRecorderFront() {
        if (mMediaRecorderFront != null) {
            cleanupEmptyFile();
            mMediaRecorderFront.reset();
            mMediaRecorderFront.release();
            mMediaRecorderFront = null;
        }
        mVideoFilenameFront = null;
    }

    public synchronized void destoryMediaRecoder() {
        stopVideoRecording();
        releaseMediaRecorderFront();
    }

    private String generateVideoFilename(int cameraType) {
        long dateTaken = System.currentTimeMillis();
        Logger.d("=dateTaken======" + dateTaken);
        Date date = new Date(dateTaken);
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                fragment.getActivity().getString(R.string.video_file_name_format));
        String prefix = cameraType == FACING_BACK_ID ? InitParam.prefixBack : InitParam.prefixFront;
        String title = prefix + dateFormat.format(date);

        String suffix = CameraInfoMg.getInstance(null).data_mirror_model;
        if ( !suffix.isEmpty() ) {
            suffix = "_" + suffix;
        }

        // Used when emailing.
        String filename = title + suffix + ".mp4";
        String path = Storage.VIDEO_DIR + '/' + filename;
        String tmpPath = path + ".tmp";
        {
            mCurrentVideoValuesFront = new ContentValues(9);
            mCurrentVideoValuesFront.put(Video.Media.TITLE, title);
            mCurrentVideoValuesFront.put(Video.Media.DISPLAY_NAME, filename);
            mCurrentVideoValuesFront.put(Video.Media.DATE_TAKEN, dateTaken);
            mCurrentVideoValuesFront.put(MediaColumns.DATE_MODIFIED, dateTaken / 1000);
            mCurrentVideoValuesFront.put(Video.Media.DATA, path);
            mCurrentVideoValuesFront.put(Video.Media.WIDTH, mProfileFront.videoFrameWidth);
            mCurrentVideoValuesFront.put(Video.Media.HEIGHT, mProfileFront.videoFrameHeight);
        }

        return tmpPath;
    }

    private void cleanupEmptyFile() {
        if (mVideoFilenameFront != null) {
            File f = new File(mVideoFilenameFront);
            if (f.length() == 0 && f.delete()) {
                mVideoFilenameFront = null;
            }
        }
    }

    private void updateRecordingTime() {
        if (!mMediaRecorderRecording) {
            return;
        }
        long now = SystemClock.uptimeMillis();
        long delta = now - mRecordingStartTime;
        Log.d(TAG, "===========1====" + mRecordingStartTime + " " + delta);

        boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
                //&& delta >= mMaxVideoDurationInMs - 60000);
                && delta >= 0);

        long deltaAdjusted = delta;
        if (countdownRemainingTime) {
            deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
        }
        String text;

        long targetNextUpdateDelay;

        deltaAdjusted = mMaxVideoDurationInMs - deltaAdjusted;
        text = TimeUtil.millisecondToTimeString(deltaAdjusted, false);
        targetNextUpdateDelay = 1000;

        String txt = TimeUtil.millisecondToTimeString(
                SpManager.get_value_record_totaltime() + deltaAdjusted, false);

        mUI.setRecordingTime(text, txt);

        long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_RECORD_TIME, actualNextUpdateDelay);
    }

    private class MainHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_RECORD_TIME: {
                    updateRecordingTime();
                    break;
                }
                default:
                    break;
            }
        }
    }



    //预览初始化操作
    private void initCamera() {
        //surfaceViewFront = fragment.getRootView().findViewById(R.id.view_camera_2);
        textureViewFront = fragment.getRootView().findViewById(R.id.view_camera_2);
        Logger.d(TAG, "===setPreviewTexture=textureViewFront1=" + textureViewFront);

        //surfaceHolderFront = surfaceViewFront.getHolder();
    }

    public synchronized void initFrontCamera() {
        try {
            closeCamera();
            zoomParam = 0;
            previewSizeWidth = 0;
            previewSizeHeight = 0;
            try {
                if ( frontCamera == null ) {
                    //TMP_CAM_ID = FACING_FRONT;
                    Logger.d(TAG, "====mNumberOfCameras mFrontCameraId=-1" + FACING_FRONT_ID);
                    frontCamera = Camera.open(FACING_FRONT_ID);
                }
            } catch (Exception e) {
            }

            //frontCamera.setDisplayOrientation(0);//180
            Camera.Parameters parameters = frontCamera.getParameters();
            List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
            for(int i = 0; i < previewSizes.size(); i++) {
                Logger.d(TAG, "====saveFinalPhoto==" + String.valueOf(previewSizes.get(i).width)
                    + String.valueOf(previewSizes.get(i).height));
                if ( previewSizeWidth < previewSizes.get(i).width ) {
                    previewSizeWidth = previewSizes.get(i).width;
                    previewSizeHeight = previewSizes.get(i).height;
                }
                /*if ( FACING_FRONT_ID == InitParam.CAM_TYPE_C ) {
                    previewSizeWidth = 640;
                    previewSizeHeight = 480;
                }*/
            }

            fragment.getRootView().findViewById(R.id.camera_gl_surface_view_01).setVisibility(View.GONE);
            fragment.getRootView().findViewById(R.id.camera_gl_surface_view_02).setVisibility(View.GONE);

            parameters.setPreviewSize(previewSizeWidth, previewSizeHeight);
            //parameters.setAutoWhiteBalanceLock(false);
            //parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
            awbParam = 1;//2
            //parameters.setColorEffect();
            //parameters.setColorEffect(Camera.Parameters.EFFECT_NONE);
            frontCamera.setParameters(parameters);
            Logger.d(TAG, "===setPreviewTexture=mSurfaceTexture1=" + mSurfaceTexture);
            //frontCamera.startPreview();   //显示相机
            isShowData = false;
            setCameraShow(View.VISIBLE);
            /*if ( FACING_FRONT_ID != InitParam.CAM_OV6946 ) {
                roundCameraGLSurfaceView.setFragmentShaderCode(GLUtil.FRAG_SHADER_NORMAL);
                roundCameraGLSurfaceView.init(false, 0,
                        previewSizeHeight, previewSizeHeight);
                squareNV21 = new byte[previewSizeHeight * previewSizeHeight * 3 / 2];
                cropRect = new Rect((previewSizeWidth - previewSizeHeight) / 2, 0,
                        (previewSizeWidth - previewSizeHeight) / 2 + previewSizeHeight, previewSizeHeight);
            }*/
            /*frontCamera.setPreviewCallback(new Camera.PreviewCallback() {
                @Override
                public void onPreviewFrame(byte[] data, Camera camera) {
                    try {
                        if ( FACING_FRONT_ID != InitParam.CAM_OV6946 ) {
                            //裁剪指定的图像区域
                            ImageUtil.cropNV21(data, squareNV21, previewSizeWidth, previewSizeHeight, cropRect);
                            //刷新GLSurfaceView
                            roundCameraGLSurfaceView.refreshFrameNV21(squareNV21);
                        }
                    } catch(Exception ex) {
                        Logger.d("Error:" + ex.getMessage());
                    }
                }
            });*/
            if ( mSurfaceTexture != null || textureViewFront.getSurfaceTexture() != null ) {
                mSurfaceTexture = textureViewFront.getSurfaceTexture();
                frontCamera.setPreviewTexture(mSurfaceTexture);
                frontCamera.startPreview();
                Logger.d(TAG, "===setPreviewTexture=mSurfaceTexture=");
            }
            textureViewFront.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
                @Override
                public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
                    startPreview(surfaceTexture);
                    Logger.d(TAG, "===onSurfaceTextureAvailable==");
                }
                @Override
                public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
                    Logger.d(TAG, "===onSurfaceTextureSizeChanged==");
                    startPreview(surfaceTexture);
                }

                @Override
                public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
                    /*frontCamera.stopPreview();
                    frontCamera.release();
                    frontCamera = null;*/
                    Logger.d(TAG, "===onSurfaceTextureDestroyed==");
                    return true;
                }
                @Override
                public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
                    //Logger.d(TAG, "===onSurfaceTextureUpdated==");
                }
            });
            /*surfaceHolderBack.addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    try {
                        frontCamera.setPreviewDisplay(holder);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                }
                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                }
            });*/

            /*new Thread(new Runnable() {
                @Override
                public void run() {
                    while( true ) {
                        try {
                            Thread.sleep(5000);
                            if ( !isShowData ) {
                                Logger.d(TAG, "====mNumberOfCameras isShowData");
                                fragment.getActivity().runOnUiThread(() -> {
                                    closeCamera();
                                    startPreview();
                                });
                            }
                            break;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();*/
        } catch (Exception e) {
            isBackError = true;
            e.printStackTrace();
        }
    }

    public void setCameraShow(int visibility) {
        /*if ( FACING_FRONT_ID == InitParam.CAM_TYPE_C ) {
            roundCameraGLSurfaceView = fragment.getRootView().findViewById(R.id.camera_gl_surface_view_01);
            roundCameraGLSurfaceView.setVisibility(visibility);
        } else if ( FACING_FRONT_ID == InitParam.CAM_OV9734 ) {
            roundCameraGLSurfaceView = fragment.getRootView().findViewById(R.id.camera_gl_surface_view_02);
            roundCameraGLSurfaceView.setVisibility(visibility);
        }*/
    }

    boolean isShowData = false;

    public synchronized void startPreview(SurfaceTexture surfaceTexture) {
        try {
            if ( frontCamera != null /*&& mSurfaceTexture == null*/ ) {
                frontCamera.setPreviewTexture(surfaceTexture);
                frontCamera.startPreview();
                mSurfaceTexture = surfaceTexture;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized void closeCamera() {
        if ( textureViewFront != null ) {
            Logger.d(TAG,"closeCamera : textureViewFront");
            /*textureViewFront.destroyDrawingCache();
            textureViewFront.requestFocus();*/
            //textureViewFront.setSurfaceTexture(new SurfaceTexture(true));
            /*Bitmap bmp = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(bmp);
            c.drawColor(Color.BLACK);
            textureViewFront.draw(c);*/
        }
        if (frontCamera != null) {
            frontCamera.setPreviewCallbackWithBuffer(null);
            frontCamera.setPreviewCallback(null);
            frontCamera.stopPreview();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            frontCamera.release();
            frontCamera = null;
            /*fragment.getActivity().runOnUiThread(() -> {
                (fragment.getRootView().findViewById(R.id.img_cam_fg_2)).setBackgroundResource(R.drawable.bg_black);
            });*/
        }
        Logger.d(TAG,"closeCamera : textureViewFront finish");
        /*if ( is720Cam ) {
            squareNV21 = new byte[previewSizeHeight * previewSizeHeight * 3 / 2];
            Arrays.fill(squareNV21, (byte)127);
            roundCameraGLSurfaceView.refreshFrameNV21(squareNV21);
        }*/
    }

    public synchronized void startVideoRecording() {
            startVideoRecordingFront();
    }

    public synchronized boolean stopVideoRecordingDelay() {
        if ( mMediaRecorderRecording ) {
            if ( System.currentTimeMillis() -
                    Long.parseLong(mCurrentVideoValuesFront.getAsString(Video.Media.DATE_TAKEN)) <= 1000L) {//2000
                return false;
            } else {
                stopVideoRecording();
                return true;
            }
        }
        return true;
    }

    public void stopVideoRecording() {
        if ( mMediaRecorderRecording ) {
            mUI.showRecordingUIBack(false);
            boolean ret = stopVideoRecordingFront();
            if ( !ret ) {
                return ;
            }

            String endTime = System.currentTimeMillis() + "";
            mVideoManager.addVideoToDb(mCurrentVideoValuesFront.getAsString(Video.Media.TITLE),
                    mCurrentVideoValuesFront.getAsString(Video.Media.DISPLAY_NAME),
                    mCurrentVideoValuesFront.getAsString(Video.Media.DATE_TAKEN), endTime,
                    Storage.VIDEO_DIR, "procedure", timeStamp2Date(endTime,"HH:mm"),
                    mCurrentVideoValuesFront.getAsString(Video.Media.TITLE) + Storage.JPEG_POSTFIX,
                    Storage.VIDEO_THUMB,
                    System.currentTimeMillis() - Long.parseLong(mCurrentVideoValuesFront.getAsString(Video.Media.DATE_TAKEN)),
                    InitParam.FILE_VIDEO, InitParam.CAM_FRONT, previewSizeWidth, previewSizeHeight);

            Thumbnail.createVideoThumbnailBitmap(
                    Storage.VIDEO_DIR + "/" + mCurrentVideoValuesFront.getAsString(Video.Media.DISPLAY_NAME),
                    Storage.VIDEO_THUMB + "/" + mCurrentVideoValuesFront.getAsString(Video.Media.TITLE) + Storage.JPEG_POSTFIX,
                    textureViewFront.getBitmap());
        }
    }

    public synchronized boolean isRecording() {
        return mMediaRecorderRecording;
    }

    public boolean isOpenCamera() {
        return frontCamera != null;
    }

    public void startPreview() {
        initFrontCamera();
    }

    public boolean burstcapture() {
        if ( frontCamera != null ) {
            frontCamera.takePicture(null, null, new JpegPictureCallback(mOnPhotoSavedListener));
        }
        return true;
    }

    /*public boolean burstIcecapture(OnMediaSavedListener listener) {
        if ( frontCamera != null ) {
            isIcePhoto = true;
            frontCamera.takePicture(null, null, new JpegPictureCallback(listener));
        }
        return true;
    }*/
    //boolean isIcePhoto = false;

    String preDate = "";
    int mIndex = 0;

    private final class JpegPictureCallback implements Camera.PictureCallback {
        private final OnMediaSavedListener listener;

        public JpegPictureCallback(OnMediaSavedListener listener) {
            /*mIndex = 0;*/
            this.listener = listener;
        }

        @Override
        public void onPictureTaken(final byte[] originalJpegData, final Camera camera) {
            frontCamera.startPreview();
            if (originalJpegData == null) {
                Logger.i("BurstPictureCallback null");
                return;
            }
            //mJpegPictureCallbackTime = System.currentTimeMillis();
            final ExifInterface exif = Exif.getExif(originalJpegData);
            saveFinalPhoto(originalJpegData, exif, camera);
        }

        void saveFinalPhoto(final byte[] jpegData, final ExifInterface exif, Camera camera) {
            int orientation = Exif.getOrientation(exif);
            Logger.i("orientation null " + orientation);
            int width = previewSizeWidth, height = previewSizeHeight;

            long dateTaken = System.currentTimeMillis();
            //Logger.d("=dateTaken======" + dateTaken);
            Date date = new Date(dateTaken);
            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    fragment.getActivity().getString(R.string.video_file_name_format));
            String prefix = InitParam.prefixPic;
            String title = "";
            String suffix = "";
            if ( !CameraInfoMg.getInstance(null).data_mirror_model.isEmpty() ) {
                suffix = "_" + CameraInfoMg.getInstance(null).data_mirror_model;
            }
            if ( dateFormat.format(date).equals(preDate) ) {
                mIndex++;
                title = prefix + dateFormat.format(date) + "_" + mIndex;
            } else {
                mIndex = 0;
                title = prefix + dateFormat.format(date);
            }
            preDate = dateFormat.format(date);
            /*if ( isIcePhoto ) {
                ImageSaveTask t = new ImageSaveTask(jpegData, Storage.PIC_ICE_NAME, dateTaken,
                        null,
                        width, height, orientation, Storage.MIME_TYPE_JPEG, exif, null, listener);
                t.execute();
            } else {*/
                ImageSaveTask t = new ImageSaveTask(jpegData, title + suffix, dateTaken,
                        null,
                        width, height, orientation, Storage.MIME_TYPE_JPEG, exif, null, listener);
                t.execute();
            /*}
            isIcePhoto = false;*/
        }
    }

    public interface OnMediaSavedListener {
        void onMediaSaved(String path);
    }

    public interface OnMediaListener {
        void onFrontNoSpace();
    }

    private OnMediaListener mOnMediaListener;

    public void setmOnMediaListener(OnMediaListener mOnMediaListener) {
        this.mOnMediaListener = mOnMediaListener;
    }

    private final OnMediaSavedListener mOnPhotoSavedListener =
        new OnMediaSavedListener() {
            @Override
            public void onMediaSaved(String path) {
                if (path != null) {
                    //notifyNewMedia(path);
                    ///===
                }
            }
        };

    private class ImageSaveTask extends AsyncTask<Void, Void, String> {
        private final byte[] data;
        private final String title;
        private final long date;
        private final Location loc;
        private int width, height;
        private final int orientation;
        private final String mimeType;
        private final ExifInterface exif;
        private final ContentResolver resolver;
        private final OnMediaSavedListener listener;

        public ImageSaveTask(byte[] data, String title, long date, Location loc,
                             int width, int height, int orientation, String mimeType,
                             ExifInterface exif, ContentResolver resolver,
                             OnMediaSavedListener listener) {
            this.data = data;
            this.title = title;
            this.date = date;
            this.loc = loc;
            this.width = width;
            this.height = height;
            this.orientation = orientation;
            this.mimeType = mimeType;
            this.exif = exif;
            this.resolver = resolver;
            this.listener = listener;
        }

        @Override
        protected void onPreExecute() {
            // do nothing.
        }

        @Override
        protected String doInBackground(Void... v) {
            if (width == 0 || height == 0) {
                // Decode bounds
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeByteArray(data, 0, data.length, options);
                width = options.outWidth;
                height = options.outHeight;
            }
            try {
                String startTime = date + "";
                String path = Storage.addImage(
                        resolver, title, date, loc, orientation, exif, data, width, height,
                        mimeType);
                mVideoManager.addPicToDb(title, title + Storage.JPEG_POSTFIX, startTime, System.currentTimeMillis() + "",
                        Storage.PIC_DIR, "procedure", timeStamp2Date(startTime,"HH:mm"),
                        title + Storage.JPEG_POSTFIX, Storage.PIC_DIR, 0, InitParam.FILE_PHOTO,
                        InitParam.CAM_FRONT, previewSizeWidth, previewSizeHeight);
                return path;
            } catch (IOException e) {
                Logger.e("Failed to write data", e.getMessage());
                return null;
            }
        }

        @Override
        protected void onPostExecute(String path) {
            if (listener != null) {
                listener.onMediaSaved(path);
            }
        }
    }

    public int getAwbParam() {
        return awbParam;
    }

    int awbParam = 1;//2
    String awbStr[] = {Camera.Parameters.WHITE_BALANCE_INCANDESCENT, Camera.Parameters.WHITE_BALANCE_FLUORESCENT,
            Camera.Parameters.WHITE_BALANCE_AUTO, Camera.Parameters.WHITE_BALANCE_DAYLIGHT,
            Camera.Parameters.WHITE_BALANCE_CLOUDY_DAYLIGHT, };
    public void setWhiteBalance(int i, boolean auto) {
        if ( !auto ) {
            awbParam = i;
        }
        if ( frontCamera != null ) {
            Camera.Parameters param;
            param = frontCamera.getParameters();
            if ( auto ) {
                awbParam++;
                if ( awbParam >= awbStr.length ) {
                    awbParam = 0;
                }
            }
            param.setWhiteBalance(awbStr[awbParam]);
            frontCamera.setParameters(param);
        }
    }

    int zoomParam = 0;
    public void setZoom() {
        int step = 10;
        if ( frontCamera != null ) {
            Camera.Parameters param;
            param = frontCamera.getParameters();
            int max = param.getMaxZoom() - 20;
            Logger.d(TAG, "===========setZoom===max==" + max + " getZoom " + param.getZoom());
            /*int curZ = (int) (i / 100.0f * 40);
            param.setZoom(curZ);
            frontCamera.setParameters(param);*/
            zoomParam = (zoomParam + step) > max ? 0 : (zoomParam + step);
            int curZ = zoomParam;
            param.setZoom(curZ);
            frontCamera.setParameters(param);
        }
    }

    private Camera.Size getBestPreviewSize(int width, int height) {
        Camera.Size result = null;
        final Camera.Parameters p = frontCamera.getParameters();
        //特别注意此处需要规定rate的比是大的比小的,不然有可能出现rate = height/width,但是后面遍历的时候,current_rate = width/height,所以我们限定都为大的比小的。
        float rate = (float) Math.max(width, height)/ (float)Math.min(width, height);
        float tmp_diff;
        float min_diff = -1f;
        for (Camera.Size size : p.getSupportedPreviewSizes()) {
            float current_rate = (float) Math.max(size.width, size.height) / (float)Math.min(size.width, size.height);
            tmp_diff = Math.abs(current_rate-rate);
            if( min_diff < 0){
                min_diff = tmp_diff ;
                result = size;
            }
            if( tmp_diff < min_diff ){
                min_diff = tmp_diff ;
                result = size;
            }
        }
        return result;
    }

    public String timeStamp2Date(String seconds, String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty())
            format = "HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }

}