neoaikon

VideoStream.java with Autofocus

May 27th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 24.40 KB | None | 0 0
  1. /*
  2.  * Copyright (C) 2011-2017 GUIGUI Simon, [email protected]
  3.  *
  4.  * This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
  5.  *
  6.  * Licensed under the Apache License, Version 2.0 (the "License");
  7.  * you may not use this file except in compliance with the License.
  8.  * You may obtain a copy of the License at
  9.  *
  10.  *     http://www.apache.org/licenses/LICENSE-2.0
  11.  *
  12.  * Unless required by applicable law or agreed to in writing, software
  13.  * distributed under the License is distributed on an "AS IS" BASIS,
  14.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15.  * See the License for the specific language governing permissions and
  16.  * limitations under the License.
  17.  */
  18.  
  19. /*
  20.     5/27/2017 - So I got the master from git and it doesn't have camera autofocus in here? What the
  21.     hell man! Added it at lines 600 and 660 if you want to see the code. Happy streaming! ~M.Stone
  22.  */
  23.  
  24. package net.majorkernelpanic.streaming.video;
  25.  
  26. import java.io.FileDescriptor;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.nio.ByteBuffer;
  30. import java.util.concurrent.Semaphore;
  31. import java.util.concurrent.TimeUnit;
  32. import net.majorkernelpanic.streaming.MediaStream;
  33. import net.majorkernelpanic.streaming.Stream;
  34. import net.majorkernelpanic.streaming.exceptions.CameraInUseException;
  35. import net.majorkernelpanic.streaming.exceptions.ConfNotSupportedException;
  36. import net.majorkernelpanic.streaming.exceptions.InvalidSurfaceException;
  37. import net.majorkernelpanic.streaming.gl.SurfaceView;
  38. import net.majorkernelpanic.streaming.hw.EncoderDebugger;
  39. import net.majorkernelpanic.streaming.hw.NV21Convertor;
  40. import net.majorkernelpanic.streaming.rtp.MediaCodecInputStream;
  41. import android.annotation.SuppressLint;
  42. import android.content.SharedPreferences;
  43. import android.content.SharedPreferences.Editor;
  44. import android.hardware.Camera;
  45. import android.hardware.Camera.CameraInfo;
  46. import android.hardware.Camera.Parameters;
  47. import android.media.MediaCodec;
  48. import android.media.MediaCodecInfo;
  49. import android.media.MediaFormat;
  50. import android.media.MediaRecorder;
  51. import android.os.Looper;
  52. import android.os.ParcelFileDescriptor;
  53. import android.util.Log;
  54. import android.view.Surface;
  55. import android.view.SurfaceHolder;
  56. import android.view.SurfaceHolder.Callback;
  57.  
  58. /**
  59.  * Don't use this class directly.
  60.  */
  61. public abstract class VideoStream extends MediaStream {
  62.  
  63.     protected final static String TAG = "VideoStream";
  64.  
  65.     protected VideoQuality mRequestedQuality = VideoQuality.DEFAULT_VIDEO_QUALITY.clone();
  66.     protected VideoQuality mQuality = mRequestedQuality.clone();
  67.     protected SurfaceHolder.Callback mSurfaceHolderCallback = null;
  68.     protected SurfaceView mSurfaceView = null;
  69.     protected SharedPreferences mSettings = null;
  70.     protected int mVideoEncoder, mCameraId = 0;
  71.     protected int mRequestedOrientation = 0, mOrientation = 0;
  72.     protected Camera mCamera;
  73.     protected Thread mCameraThread;
  74.     protected Looper mCameraLooper;
  75.  
  76.     protected boolean mCameraOpenedManually = true;
  77.     protected boolean mFlashEnabled = false;
  78.     protected boolean mSurfaceReady = false;
  79.     protected boolean mUnlocked = false;
  80.     protected boolean mPreviewStarted = false;
  81.     protected boolean mUpdated = false;
  82.    
  83.     protected String mMimeType;
  84.     protected String mEncoderName;
  85.     protected int mEncoderColorFormat;
  86.     protected int mCameraImageFormat;
  87.     protected int mMaxFps = 0; 
  88.  
  89.     /**
  90.      * Don't use this class directly.
  91.      * Uses CAMERA_FACING_BACK by default.
  92.      */
  93.     public VideoStream() {
  94.         this(CameraInfo.CAMERA_FACING_BACK);
  95.     }  
  96.  
  97.     /**
  98.      * Don't use this class directly
  99.      * @param camera Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT
  100.      */
  101.     @SuppressLint("InlinedApi")
  102.     public VideoStream(int camera) {
  103.         super();
  104.         setCamera(camera);
  105.     }
  106.  
  107.     /**
  108.      * Sets the camera that will be used to capture video.
  109.      * You can call this method at any time and changes will take effect next time you start the stream.
  110.      * @param camera Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT
  111.      */
  112.     public void setCamera(int camera) {
  113.         CameraInfo cameraInfo = new CameraInfo();
  114.         int numberOfCameras = Camera.getNumberOfCameras();
  115.         for (int i=0;i<numberOfCameras;i++) {
  116.             Camera.getCameraInfo(i, cameraInfo);
  117.             if (cameraInfo.facing == camera) {
  118.                 mCameraId = i;
  119.                 break;
  120.             }
  121.         }
  122.     }
  123.  
  124.     /** Switch between the front facing and the back facing camera of the phone.
  125.      * If {@link #startPreview()} has been called, the preview will be  briefly interrupted.
  126.      * If {@link #start()} has been called, the stream will be  briefly interrupted.
  127.      * You should not call this method from the main thread if you are already streaming.
  128.      * @throws IOException
  129.      * @throws RuntimeException
  130.      **/
  131.     public void switchCamera() throws RuntimeException, IOException {
  132.         if (Camera.getNumberOfCameras() == 1) throw new IllegalStateException("Phone only has one camera !");
  133.         boolean streaming = mStreaming;
  134.         boolean previewing = mCamera!=null && mCameraOpenedManually;
  135.         mCameraId = (mCameraId == CameraInfo.CAMERA_FACING_BACK) ? CameraInfo.CAMERA_FACING_FRONT : CameraInfo.CAMERA_FACING_BACK;
  136.         setCamera(mCameraId);
  137.         stopPreview();
  138.         mFlashEnabled = false;
  139.         if (previewing) startPreview();
  140.         if (streaming) start();
  141.     }
  142.  
  143.     /**
  144.      * Returns the id of the camera currently selected.
  145.      * Can be either {@link CameraInfo#CAMERA_FACING_BACK} or
  146.      * {@link CameraInfo#CAMERA_FACING_FRONT}.
  147.      */
  148.     public int getCamera() {
  149.         return mCameraId;
  150.     }
  151.  
  152.     /**
  153.      * Sets a Surface to show a preview of recorded media (video).
  154.      * You can call this method at any time and changes will take effect next time you call {@link #start()}.
  155.      */
  156.     public synchronized void setSurfaceView(SurfaceView view) {
  157.         mSurfaceView = view;
  158.         if (mSurfaceHolderCallback != null && mSurfaceView != null && mSurfaceView.getHolder() != null) {
  159.             mSurfaceView.getHolder().removeCallback(mSurfaceHolderCallback);
  160.         }
  161.         if (mSurfaceView != null && mSurfaceView.getHolder() != null) {
  162.             mSurfaceHolderCallback = new Callback() {
  163.                 @Override
  164.                 public void surfaceDestroyed(SurfaceHolder holder) {
  165.                     mSurfaceReady = false;
  166.                     stopPreview();
  167.                     Log.d(TAG,"Surface destroyed !");
  168.                 }
  169.                 @Override
  170.                 public void surfaceCreated(SurfaceHolder holder) {
  171.                     mSurfaceReady = true;
  172.                 }
  173.                 @Override
  174.                 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  175.                     Log.d(TAG,"Surface Changed !");
  176.                 }
  177.             };
  178.             mSurfaceView.getHolder().addCallback(mSurfaceHolderCallback);
  179.             mSurfaceReady = true;
  180.         }
  181.     }
  182.  
  183.     /** Turns the LED on or off if phone has one. */
  184.     public synchronized void setFlashState(boolean state) {
  185.         // If the camera has already been opened, we apply the change immediately
  186.         if (mCamera != null) {
  187.  
  188.             if (mStreaming && mMode == MODE_MEDIARECORDER_API) {
  189.                 lockCamera();
  190.             }
  191.  
  192.             Parameters parameters = mCamera.getParameters();
  193.  
  194.             // We test if the phone has a flash
  195.             if (parameters.getFlashMode()==null) {
  196.                 // The phone has no flash or the choosen camera can not toggle the flash
  197.                 throw new RuntimeException("Can't turn the flash on !");
  198.             } else {
  199.                 parameters.setFlashMode(state?Parameters.FLASH_MODE_TORCH:Parameters.FLASH_MODE_OFF);
  200.                 try {
  201.                     mCamera.setParameters(parameters);
  202.                     mFlashEnabled = state;
  203.                 } catch (RuntimeException e) {
  204.                     mFlashEnabled = false;
  205.                     throw new RuntimeException("Can't turn the flash on !");
  206.                 } finally {
  207.                     if (mStreaming && mMode == MODE_MEDIARECORDER_API) {
  208.                         unlockCamera();
  209.                     }
  210.                 }
  211.             }
  212.         } else {
  213.             mFlashEnabled = state;
  214.         }
  215.     }
  216.  
  217.     /**
  218.      * Toggles the LED of the phone if it has one.
  219.      * You can get the current state of the flash with {@link VideoStream#getFlashState()}.
  220.      */
  221.     public synchronized void toggleFlash() {
  222.         setFlashState(!mFlashEnabled);
  223.     }
  224.  
  225.     /** Indicates whether or not the flash of the phone is on. */
  226.     public boolean getFlashState() {
  227.         return mFlashEnabled;
  228.     }
  229.  
  230.     /**
  231.      * Sets the orientation of the preview.
  232.      * @param orientation The orientation of the preview
  233.      */
  234.     public void setPreviewOrientation(int orientation) {
  235.         mRequestedOrientation = orientation;
  236.         mUpdated = false;
  237.     }
  238.    
  239.     /**
  240.      * Sets the configuration of the stream. You can call this method at any time
  241.      * and changes will take effect next time you call {@link #configure()}.
  242.      * @param videoQuality Quality of the stream
  243.      */
  244.     public void setVideoQuality(VideoQuality videoQuality) {
  245.         if (!mRequestedQuality.equals(videoQuality)) {
  246.             mRequestedQuality = videoQuality.clone();
  247.             mUpdated = false;
  248.         }
  249.     }
  250.  
  251.     /**
  252.      * Returns the quality of the stream.  
  253.      */
  254.     public VideoQuality getVideoQuality() {
  255.         return mRequestedQuality;
  256.     }
  257.  
  258.     /**
  259.      * Some data (SPS and PPS params) needs to be stored when {@link #getSessionDescription()} is called
  260.      * @param prefs The SharedPreferences that will be used to save SPS and PPS parameters
  261.      */
  262.     public void setPreferences(SharedPreferences prefs) {
  263.         mSettings = prefs;
  264.     }
  265.  
  266.     /**
  267.      * Configures the stream. You need to call this before calling {@link #getSessionDescription()}
  268.      * to apply your configuration of the stream.
  269.      */
  270.     public synchronized void configure() throws IllegalStateException, IOException {
  271.         super.configure();
  272.         mOrientation = mRequestedOrientation;
  273.     }  
  274.    
  275.     /**
  276.      * Starts the stream.
  277.      * This will also open the camera and display the preview
  278.      * if {@link #startPreview()} has not already been called.
  279.      */
  280.     public synchronized void start() throws IllegalStateException, IOException {
  281.         if (!mPreviewStarted) mCameraOpenedManually = false;
  282.         super.start();
  283.         Log.d(TAG,"Stream configuration: FPS: "+mQuality.framerate+" Width: "+mQuality.resX+" Height: "+mQuality.resY);
  284.     }
  285.  
  286.     /** Stops the stream. */
  287.     public synchronized void stop() {
  288.         if (mCamera != null) {
  289.             if (mMode == MODE_MEDIACODEC_API) {
  290.                 mCamera.setPreviewCallbackWithBuffer(null);
  291.             }
  292.             if (mMode == MODE_MEDIACODEC_API_2) {
  293.                 ((SurfaceView)mSurfaceView).removeMediaCodecSurface();
  294.             }
  295.             super.stop();
  296.             // We need to restart the preview
  297.             if (!mCameraOpenedManually) {
  298.                 destroyCamera();
  299.             } else {
  300.                 try {
  301.                     startPreview();
  302.                 } catch (RuntimeException e) {
  303.                     e.printStackTrace();
  304.                 }
  305.             }
  306.         }
  307.     }
  308.  
  309.     public synchronized void startPreview()
  310.             throws CameraInUseException,
  311.             InvalidSurfaceException,
  312.             RuntimeException {
  313.        
  314.         mCameraOpenedManually = true;
  315.         if (!mPreviewStarted) {
  316.             createCamera();
  317.             updateCamera();
  318.         }
  319.     }
  320.  
  321.     /**
  322.      * Stops the preview.
  323.      */
  324.     public synchronized void stopPreview() {
  325.         mCameraOpenedManually = false;
  326.         stop();
  327.     }
  328.  
  329.     /**
  330.      * Video encoding is done by a MediaRecorder.
  331.      */
  332.     protected void encodeWithMediaRecorder() throws IOException, ConfNotSupportedException {
  333.  
  334.         Log.d(TAG,"Video encoded using the MediaRecorder API");
  335.  
  336.         // We need a local socket to forward data output by the camera to the packetizer
  337.         createSockets();
  338.  
  339.         // Reopens the camera if needed
  340.         destroyCamera();
  341.         createCamera();
  342.  
  343.         // The camera must be unlocked before the MediaRecorder can use it
  344.         unlockCamera();
  345.  
  346.         try {
  347.             mMediaRecorder = new MediaRecorder();
  348.             mMediaRecorder.setCamera(mCamera);
  349.             mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
  350.             mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  351.             mMediaRecorder.setVideoEncoder(mVideoEncoder);
  352.             mMediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface());
  353.             mMediaRecorder.setVideoSize(mRequestedQuality.resX,mRequestedQuality.resY);
  354.             mMediaRecorder.setVideoFrameRate(mRequestedQuality.framerate);
  355.  
  356.             // The bandwidth actually consumed is often above what was requested
  357.             mMediaRecorder.setVideoEncodingBitRate((int)(mRequestedQuality.bitrate*0.8));
  358.  
  359.             // We write the output of the camera in a local socket instead of a file !         
  360.             // This one little trick makes streaming feasible quiet simply: data from the camera
  361.             // can then be manipulated at the other end of the socket
  362.             FileDescriptor fd = null;
  363.             if (sPipeApi == PIPE_API_PFD) {
  364.                 fd = mParcelWrite.getFileDescriptor();
  365.             } else  {
  366.                 fd = mSender.getFileDescriptor();
  367.             }
  368.             mMediaRecorder.setOutputFile(fd);
  369.  
  370.             mMediaRecorder.prepare();
  371.             mMediaRecorder.start();
  372.  
  373.         } catch (Exception e) {
  374.             throw new ConfNotSupportedException(e.getMessage());
  375.         }
  376.  
  377.         InputStream is = null;
  378.  
  379.         if (sPipeApi == PIPE_API_PFD) {
  380.             is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead);
  381.         } else  {
  382.             is = mReceiver.getInputStream();
  383.         }
  384.  
  385.         // This will skip the MPEG4 header if this step fails we can't stream anything :(
  386.         try {
  387.             byte buffer[] = new byte[4];
  388.             // Skip all atoms preceding mdat atom
  389.             while (!Thread.interrupted()) {
  390.                 while (is.read() != 'm');
  391.                 is.read(buffer,0,3);
  392.                 if (buffer[0] == 'd' && buffer[1] == 'a' && buffer[2] == 't') break;
  393.             }
  394.         } catch (IOException e) {
  395.             Log.e(TAG,"Couldn't skip mp4 header :/");
  396.             stop();
  397.             throw e;
  398.         }
  399.  
  400.         // The packetizer encapsulates the bit stream in an RTP stream and send it over the network
  401.         mPacketizer.setInputStream(is);
  402.         mPacketizer.start();
  403.  
  404.         mStreaming = true;
  405.  
  406.     }
  407.  
  408.  
  409.     /**
  410.      * Video encoding is done by a MediaCodec.
  411.      */
  412.     protected void encodeWithMediaCodec() throws RuntimeException, IOException {
  413.         if (mMode == MODE_MEDIACODEC_API_2) {
  414.             // Uses the method MediaCodec.createInputSurface to feed the encoder
  415.             encodeWithMediaCodecMethod2();
  416.         } else {
  417.             // Uses dequeueInputBuffer to feed the encoder
  418.             encodeWithMediaCodecMethod1();
  419.         }
  420.     }  
  421.  
  422.     /**
  423.      * Video encoding is done by a MediaCodec.
  424.      */
  425.     @SuppressLint("NewApi")
  426.     protected void encodeWithMediaCodecMethod1() throws RuntimeException, IOException {
  427.  
  428.         Log.d(TAG,"Video encoded using the MediaCodec API with a buffer");
  429.  
  430.         // Updates the parameters of the camera if needed
  431.         createCamera();
  432.         updateCamera();
  433.  
  434.         // Estimates the frame rate of the camera
  435.         measureFramerate();
  436.  
  437.         // Starts the preview if needed
  438.         if (!mPreviewStarted) {
  439.             try {
  440.                 mCamera.startPreview();
  441.                 mPreviewStarted = true;
  442.             } catch (RuntimeException e) {
  443.                 destroyCamera();
  444.                 throw e;
  445.             }
  446.         }
  447.  
  448.         EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY);
  449.         final NV21Convertor convertor = debugger.getNV21Convertor();
  450.  
  451.         mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName());
  452.         MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", mQuality.resX, mQuality.resY);
  453.         mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitrate);
  454.         mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mQuality.framerate);
  455.         mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,debugger.getEncoderColorFormat());
  456.         mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
  457.         mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
  458.         mMediaCodec.start();
  459.  
  460.         Camera.PreviewCallback callback = new Camera.PreviewCallback() {
  461.             long now = System.nanoTime()/1000, oldnow = now, i=0;
  462.             ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
  463.             @Override
  464.             public void onPreviewFrame(byte[] data, Camera camera) {
  465.                 oldnow = now;
  466.                 now = System.nanoTime()/1000;
  467.                 if (i++>3) {
  468.                     i = 0;
  469.                     //Log.d(TAG,"Measured: "+1000000L/(now-oldnow)+" fps.");
  470.                 }
  471.                 try {
  472.                     int bufferIndex = mMediaCodec.dequeueInputBuffer(500000);
  473.                     if (bufferIndex>=0) {
  474.                         inputBuffers[bufferIndex].clear();
  475.                         if (data == null) Log.e(TAG,"Symptom of the \"Callback buffer was to small\" problem...");
  476.                         else convertor.convert(data, inputBuffers[bufferIndex]);
  477.                         mMediaCodec.queueInputBuffer(bufferIndex, 0, inputBuffers[bufferIndex].position(), now, 0);
  478.                     } else {
  479.                         Log.e(TAG,"No buffer available !");
  480.                     }
  481.                 } finally {
  482.                     mCamera.addCallbackBuffer(data);
  483.                 }              
  484.             }
  485.         };
  486.        
  487.         for (int i=0;i<10;i++) mCamera.addCallbackBuffer(new byte[convertor.getBufferSize()]);
  488.         mCamera.setPreviewCallbackWithBuffer(callback);
  489.  
  490.         // The packetizer encapsulates the bit stream in an RTP stream and send it over the network
  491.         mPacketizer.setInputStream(new MediaCodecInputStream(mMediaCodec));
  492.         mPacketizer.start();
  493.  
  494.         mStreaming = true;
  495.  
  496.     }
  497.  
  498.     /**
  499.      * Video encoding is done by a MediaCodec.
  500.      * But here we will use the buffer-to-surface method
  501.      */
  502.     @SuppressLint({ "InlinedApi", "NewApi" })  
  503.     protected void encodeWithMediaCodecMethod2() throws RuntimeException, IOException {
  504.  
  505.         Log.d(TAG,"Video encoded using the MediaCodec API with a surface");
  506.  
  507.         // Updates the parameters of the camera if needed
  508.         createCamera();
  509.         updateCamera();
  510.  
  511.         // Estimates the frame rate of the camera
  512.         measureFramerate();
  513.  
  514.         EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY);
  515.  
  516.         mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName());
  517.         MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", mQuality.resX, mQuality.resY);
  518.         mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitrate);
  519.         mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mQuality.framerate);
  520.         mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
  521.         mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
  522.         mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
  523.         Surface surface = mMediaCodec.createInputSurface();
  524.         ((SurfaceView)mSurfaceView).addMediaCodecSurface(surface);
  525.         mMediaCodec.start();
  526.  
  527.         // The packetizer encapsulates the bit stream in an RTP stream and send it over the network
  528.         mPacketizer.setInputStream(new MediaCodecInputStream(mMediaCodec));
  529.         mPacketizer.start();
  530.  
  531.         mStreaming = true;
  532.  
  533.     }
  534.  
  535.     /**
  536.      * Returns a description of the stream using SDP.
  537.      * This method can only be called after {@link Stream#configure()}.
  538.      * @throws IllegalStateException Thrown when {@link Stream#configure()} wa not called.
  539.      */
  540.     public abstract String getSessionDescription() throws IllegalStateException;
  541.  
  542.     /**
  543.      * Opens the camera in a new Looper thread so that the preview callback is not called from the main thread
  544.      * If an exception is thrown in this Looper thread, we bring it back into the main thread.
  545.      * @throws RuntimeException Might happen if another app is already using the camera.
  546.      */
  547.     private void openCamera() throws RuntimeException {
  548.         final Semaphore lock = new Semaphore(0);
  549.         final RuntimeException[] exception = new RuntimeException[1];
  550.         mCameraThread = new Thread(new Runnable() {
  551.             @Override
  552.             public void run() {
  553.                 Looper.prepare();
  554.                 mCameraLooper = Looper.myLooper();
  555.                 try {
  556.                     mCamera = Camera.open(mCameraId);
  557.                 } catch (RuntimeException e) {
  558.                     exception[0] = e;
  559.                 } finally {
  560.                     lock.release();
  561.                     Looper.loop();
  562.                 }
  563.             }
  564.         });
  565.         mCameraThread.start();
  566.         lock.acquireUninterruptibly();
  567.         if (exception[0] != null) throw new CameraInUseException(exception[0].getMessage());
  568.     }
  569.  
  570.     protected synchronized void createCamera() throws RuntimeException {
  571.         if (mSurfaceView == null)
  572.             throw new InvalidSurfaceException("Invalid surface !");
  573.         if (mSurfaceView.getHolder() == null || !mSurfaceReady)
  574.             throw new InvalidSurfaceException("Invalid surface !");
  575.  
  576.         if (mCamera == null) {
  577.             openCamera();
  578.             mUpdated = false;
  579.             mUnlocked = false;
  580.             mCamera.setErrorCallback(new Camera.ErrorCallback() {
  581.                 @Override
  582.                 public void onError(int error, Camera camera) {
  583.                     // On some phones when trying to use the camera facing front the media server will die
  584.                     // Whether or not this callback may be called really depends on the phone
  585.                     if (error == Camera.CAMERA_ERROR_SERVER_DIED) {
  586.                         // In this case the application must release the camera and instantiate a new one
  587.                         Log.e(TAG,"Media server died !");
  588.                         // We don't know in what thread we are so stop needs to be synchronized
  589.                         mCameraOpenedManually = false;
  590.                         stop();
  591.                     } else {
  592.                         Log.e(TAG,"Error unknown with the camera: "+error);
  593.                     }  
  594.                 }
  595.             });
  596.  
  597.             try {
  598.  
  599.                 // If the phone has a flash, we turn it on/off according to mFlashEnabled
  600.                 // setRecordingHint(true) is a very nice optimization if you plane to only use the Camera for recording
  601.                 Parameters parameters = mCamera.getParameters();
  602.                 if (parameters.getFlashMode()!=null) {
  603.                     parameters.setFlashMode(mFlashEnabled?Parameters.FLASH_MODE_TORCH:Parameters.FLASH_MODE_OFF);
  604.                 }
  605.  
  606.                 // M.Stone, 5/27/17, added support for camera autofocus, why wasn't this already here?
  607.                 if(parameters.getSupportedFocusModes().contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
  608.                     parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
  609.  
  610.                 parameters.setRecordingHint(true);
  611.                 mCamera.setParameters(parameters);
  612.                 mCamera.setDisplayOrientation(mOrientation);
  613.  
  614.                 try {
  615.                     if (mMode == MODE_MEDIACODEC_API_2) {
  616.                         mSurfaceView.startGLThread();
  617.                         mCamera.setPreviewTexture(mSurfaceView.getSurfaceTexture());
  618.                     } else {
  619.                         mCamera.setPreviewDisplay(mSurfaceView.getHolder());
  620.                     }
  621.                 } catch (IOException e) {
  622.                     throw new InvalidSurfaceException("Invalid surface !");
  623.                 }
  624.  
  625.             } catch (RuntimeException e) {
  626.                 destroyCamera();
  627.                 throw e;
  628.             }
  629.  
  630.         }
  631.     }
  632.  
  633.     protected synchronized void destroyCamera() {
  634.         if (mCamera != null) {
  635.             if (mStreaming) super.stop();
  636.             lockCamera();
  637.             mCamera.stopPreview();
  638.             try {
  639.                 mCamera.release();
  640.             } catch (Exception e) {
  641.                 Log.e(TAG,e.getMessage()!=null?e.getMessage():"unknown error");
  642.             }
  643.             mCamera = null;
  644.             mCameraLooper.quit();
  645.             mUnlocked = false;
  646.             mPreviewStarted = false;
  647.         }  
  648.     }
  649.  
  650.     protected synchronized void updateCamera() throws RuntimeException {
  651.        
  652.         // The camera is already correctly configured
  653.         if (mUpdated) return;
  654.        
  655.         if (mPreviewStarted) {
  656.             mPreviewStarted = false;
  657.             mCamera.stopPreview();
  658.         }
  659.  
  660.         Parameters parameters = mCamera.getParameters();
  661.         mQuality = VideoQuality.determineClosestSupportedResolution(parameters, mQuality);
  662.         int[] max = VideoQuality.determineMaximumSupportedFramerate(parameters);
  663.        
  664.         double ratio = (double)mQuality.resX/(double)mQuality.resY;
  665.         mSurfaceView.requestAspectRatio(ratio);
  666.  
  667.         // M.Stone, 5/27/17, added support for camera autofocus, why wasn't this already here?
  668.         if(parameters.getSupportedFocusModes().contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
  669.             parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
  670.  
  671.         parameters.setPreviewFormat(mCameraImageFormat);
  672.         parameters.setPreviewSize(mQuality.resX, mQuality.resY);
  673.         parameters.setPreviewFpsRange(max[0], max[1]);
  674.  
  675.         try {
  676.             mCamera.setParameters(parameters);
  677.             mCamera.setDisplayOrientation(mOrientation);
  678.             mCamera.startPreview();
  679.             mPreviewStarted = true;
  680.             mUpdated = true;
  681.         } catch (RuntimeException e) {
  682.             destroyCamera();
  683.             throw e;
  684.         }
  685.     }
  686.  
  687.     protected void lockCamera() {
  688.         if (mUnlocked) {
  689.             Log.d(TAG,"Locking camera");
  690.             try {
  691.                 mCamera.reconnect();
  692.             } catch (Exception e) {
  693.                 Log.e(TAG,e.getMessage());
  694.             }
  695.             mUnlocked = false;
  696.         }
  697.     }
  698.  
  699.     protected void unlockCamera() {
  700.         if (!mUnlocked) {
  701.             Log.d(TAG,"Unlocking camera");
  702.             try {  
  703.                 mCamera.unlock();
  704.             } catch (Exception e) {
  705.                 Log.e(TAG,e.getMessage());
  706.             }
  707.             mUnlocked = true;
  708.         }
  709.     }
  710.  
  711.  
  712.     /**
  713.      * Computes the average frame rate at which the preview callback is called.
  714.      * We will then use this average frame rate with the MediaCodec.  
  715.      * Blocks the thread in which this function is called.
  716.      */
  717.     private void measureFramerate() {
  718.         final Semaphore lock = new Semaphore(0);
  719.  
  720.         final Camera.PreviewCallback callback = new Camera.PreviewCallback() {
  721.             int i = 0, t = 0;
  722.             long now, oldnow, count = 0;
  723.             @Override
  724.             public void onPreviewFrame(byte[] data, Camera camera) {
  725.                 i++;
  726.                 now = System.nanoTime()/1000;
  727.                 if (i>3) {
  728.                     t += now - oldnow;
  729.                     count++;
  730.                 }
  731.                 if (i>20) {
  732.                     mQuality.framerate = (int) (1000000/(t/count)+1);
  733.                     lock.release();
  734.                 }
  735.                 oldnow = now;
  736.             }
  737.         };
  738.  
  739.         mCamera.setPreviewCallback(callback);
  740.  
  741.         try {
  742.             lock.tryAcquire(2,TimeUnit.SECONDS);
  743.             Log.d(TAG,"Actual framerate: "+mQuality.framerate);
  744.             if (mSettings != null) {
  745.                 Editor editor = mSettings.edit();
  746.                 editor.putInt(PREF_PREFIX+"fps"+mRequestedQuality.framerate+","+mCameraImageFormat+","+mRequestedQuality.resX+mRequestedQuality.resY, mQuality.framerate);
  747.                 editor.commit();
  748.             }
  749.         } catch (InterruptedException e) {}
  750.  
  751.         mCamera.setPreviewCallback(null);
  752.  
  753.     }  
  754.  
  755. }
Advertisement
Add Comment
Please, Sign In to add comment