Fix issue 1) not recognizes some usb device, 2) reconnect when ffmpeg encoder error
[rtmpclient.git] / app / src / main / java / ai / suanzi / rtmpclient / MainActivity.java
index 31fcbf3..bf53ce4 100644 (file)
 package ai.suanzi.rtmpclient;
 
+import android.content.IntentFilter;
+import android.support.design.widget.TextInputEditText;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.util.Log;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import android.view.View;
+import android.widget.Button;
+import android.widget.Toast;
+import android.content.Context;
 
-public class MainActivity extends AppCompatActivity {
+import java.io.File;
+import android.content.Intent;
+import de.mindpipe.android.logging.log4j.LogConfigurator;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import android.net.wifi.WifiManager;
+import android.net.wifi.WifiInfo;
+import android.content.ServiceConnection;
+import android.content.ComponentName;
 
-    private static final String TAG = "PENG";
-    private Ffmpeg ffmpeg = new Ffmpeg();
+import ai.suanzi.rtmpclient.MyService.LocalBinder;
+import android.os.IBinder;
+import android.net.ConnectivityManager;
+
+//"rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90";
+
+public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MyService.MyServiceEventListener{
+
+    private static final String TAG = "MainActivity";
+    private Logger gLogger;
+
+    private SurfaceHolder mHolder;
+    private SurfaceView mSufaceView;
+    private Button mBtnStart;
+    private TextInputEditText mTextServer;
+    private TextInputEditText mTextUser;
+    private TextInputEditText mTextCamera;
+    private String mMacAddr = "";
+    private NetworkMonitor networkMonitor;
+    private UsbMonitor mUsbMonitor;
+    private ServiceHealthMonitor mServiceHealthMonitor;
+    private static final int INTERVAL = 3 * 60; // seconds
+
+    boolean mBounded = false;
+    MyService mServer;
+    Intent mIntent;
+
+    private void configLog(){
+        try {
+            final LogConfigurator logConfigurator = new LogConfigurator();
+            String fname = getExternalFilesDir(null) + File.separator + "log.txt";
+            logConfigurator.setFileName(fname);
+            Log.e(TAG, "Log file is located at: " + fname);
+            logConfigurator.setRootLevel(Level.DEBUG);
+            logConfigurator.setLevel("org.apache", Level.ERROR);
+            logConfigurator.setMaxFileSize(1024 * 1024 * 10);
+            logConfigurator.configure();
+            gLogger = Logger.getLogger(getClass());
+        } catch (Exception e){
+            e.printStackTrace();
+        }
+    }
+
+    private void init(){
+        configLog();
+        gLogger.debug("#######################################");
+        // set config file
+        UserInfo.setConfigPath(getExternalFilesDir(null) + File.separator + "config");
+
+        this.mMacAddr = getMacAddr();
+        mBtnStart = findViewById(R.id.button);
+        mTextServer = findViewById(R.id.textServer);
+        mTextUser = findViewById(R.id.textUser);
+        mTextCamera = findViewById(R.id.textCamera);
+        mSufaceView = findViewById(R.id.surfaceView);
+        mHolder = mSufaceView.getHolder();
+        mHolder.addCallback(this);
+
+        mIntent = new Intent(this, MyService.class);
+        mUsbMonitor = new UsbMonitor(new UsbMonitor.UsbListener() {
+            @Override
+            public void onCameraConnected() {
+                gLogger.error("onCameraConnected, current Usb Camera count: " + mUsbMonitor.getUsbCameraCount());
+                doUnbindService();
+                if(mUsbMonitor.hasUsbCamera()){
+                    doBindService();
+                }
+            }
+
+            @Override
+            public void onCameraDisconnected() {
+                gLogger.error("onCameraDisconnected, current camera count: " + mUsbMonitor.getUsbCameraCount());
+                doUnbindService();
+                if(mUsbMonitor.hasUsbCamera()){
+                    doBindService();
+                }
+            }
+        }, this);
+
+        networkMonitor = new NetworkMonitor(new NetworkMonitor.NetworkListener() {
+            @Override
+            public void onWifiConnected() {
+                gLogger.error("onWifiConnected");
+                doBindService();
+            }
+
+            @Override
+            public void onWifiDisconnected() {
+                gLogger.error("onWifiDisconnected");
+                doUnbindService();
+            }
+
+            @Override
+            public void onWifiEnabled() {
+                gLogger.error("onWifiEnabled");
+            }
+
+            @Override
+            public void onWifiDisabled() {
+                gLogger.error("onWifiDisabled");
+            }
+        });
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
+        registerReceiver(networkMonitor, filter);
+
+        mServiceHealthMonitor = new ServiceHealthMonitor(new ServiceHealthMonitor.Callback() {
+            @Override
+            public void onNotHealthy() {
+                gLogger.error("onNotHealthy, in " + INTERVAL + " seconds, the publishing may stopped or have error ");
+                doUnbindService();
+                doBindService();
+                //restartApplication();
+            }
+        });
+        mServiceHealthMonitor.setInterval(INTERVAL); // 5 minutes
+    }
+
+
+    ServiceConnection mConnection = new ServiceConnection() {
+        @Override
+        public void onServiceDisconnected(ComponentName name) {
+            Toast.makeText(MainActivity.this, "Service is disconnected", 1000).show();
+            gLogger.error("onServiceDisconnected ---------->");
+            mBounded = false;
+            mServer = null;
+        }
+
+        @Override
+        public void onServiceConnected(ComponentName name, IBinder service) {
+            Toast.makeText(MainActivity.this, "Service is connected", 1000).show();
+            gLogger.error("onServiceConnected ---------->");
+            mBounded = true;
+            LocalBinder mLocalBinder = (LocalBinder)service;
+            mServer = mLocalBinder.getServiceInstance();
+            mServer.setServiceEventListener(MainActivity.this);
+            if(mServer.setRtmpUrl(UserInfo.getConfig().toUrl(mMacAddr))){
+                mServer.startPreview(mHolder);
+            }
+
+
+        }
+    };
+
+    private void doBindService(){
+        gLogger.debug("doBindService");
+        if(!mBounded && canStartService()) {
+            gLogger.debug("Start service --------->");
+            bindService(mIntent, mConnection, BIND_AUTO_CREATE);
+        }
+    }
+
+    private void doUnbindService() {
+        gLogger.debug("doUnbindService");
+        if(mBounded){
+            gLogger.debug("Stop service <---------");
+            unbindService(mConnection);
+            mBounded = false;
+        }
+    }
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
-        Log.e(TAG, "Ffmpeg Version: " + ffmpeg.getVersion());
+
+        init();
+        loadConfig();
+
+        if(NetworkMonitor.isNetworkAvailable(this) && mUsbMonitor.hasUsbCamera()){
+            gLogger.error("Current network is available");
+            doBindService();
+        } else {
+            gLogger.error("Current network NOT available or no USB Camera connected");
+        }
+
+        mBtnStart.setText("start");
+        mBtnStart.setOnClickListener(new View.OnClickListener(){
+            @Override
+            public void onClick(View view){
+                gLogger.error("----------> onClick");
+                saveConfig();
+                doUnbindService();
+                doBindService();
+            }
+        });
+
+        if(!mServiceHealthMonitor.isAlive()) {
+            gLogger.debug("mServiceHealthMonitor start, interval " + INTERVAL);
+            mServiceHealthMonitor.start();
+        }
+    }
+
+    @Override
+    protected void onPause(){
+        super.onPause();
+        gLogger.error("OnPause --------->");
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        gLogger.error("OnResume ---------> ");
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+        gLogger.debug("onStop --------->");
+    }
+
+    @Override
+    protected void onStart(){
+        super.onStart();
+        gLogger.debug("onStart --------->");
+    }
+
+    @Override
+    protected void onDestroy(){
+        super.onDestroy();
+        mUsbMonitor.unregisterReceiver();
+        unregisterReceiver(networkMonitor);
+        unbindService(mConnection);
+        gLogger.debug("onDestroy --------->");
+    }
+
+    @Override
+    protected void onRestart(){
+        super.onRestart();
+        gLogger.debug("onRestart ---------->");
+    }
+
+    @Override
+    public void onBackPressed() {
+        gLogger.error("onBackPressed  --------->");
+        Intent intent = new Intent(Intent.ACTION_MAIN);
+        intent.addCategory(Intent.CATEGORY_HOME);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        startActivity(intent);
+    }
+
+    // SurfaceHolder.Callback implementation
+    @Override
+    public void surfaceCreated(final SurfaceHolder holder){
+        gLogger.error("SurfacedCreated");
+    }
+
+    @Override
+    public void surfaceChanged(SurfaceHolder holder, int format, int widht, int height){
+        gLogger.error("surfaceChanged");
+        mHolder = holder;
+        if (mServer != null) {
+            mServer.startPreview(holder);
+        }
+    }
+
+    @Override
+    public void surfaceDestroyed(SurfaceHolder holder){ gLogger.debug("surfaceDestroyed");
+    }
+
+    private String getMacAddr() {
+        WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
+        WifiInfo info = manager.getConnectionInfo();
+        return info.getMacAddress().replace(":", ""); //02:00:00:00:00:00 - 020000000000
+    }
+
+    private void loadConfig() {
+        UserInfo info = UserInfo.getConfig();
+        gLogger.error("server is:" + info.server);
+        mTextServer.setText(info.server.equals("") ? "rtmp://gpussh.suanzi.ai:1935/myapp" : info.server);
+        mTextUser.setText(info.user);
+        mTextCamera.setText(info.cameraId);
+        //mMacAddr = info.macAddr.equals("") ?  this.mMacAddr : info.macAddr;
+        gLogger.error("loadConfig - url is :" + info.toUrl(mMacAddr));
+    }
+
+    private void saveConfig() {
+        UserInfo info = UserInfo.getConfig();
+        info.update(mTextServer.getText().toString(), mTextUser.getText().toString(), mMacAddr, mTextCamera.getText().toString());
+        if(info.saveConfig()) {
+            Toast.makeText(getApplicationContext(), "Config saved", Toast.LENGTH_LONG).show();
+        } else {
+            Toast.makeText(getApplicationContext(), "Error: config saved", Toast.LENGTH_LONG).show();
+        }
+        gLogger.error("saveConfig - url: " + info.toUrl(mMacAddr));
+    }
+
+    private boolean canStartService(){
+        return mUsbMonitor.hasUsbCamera() && NetworkMonitor.isNetworkAvailable(this);
+    }
+
+    // MyServiceEventListener
+    @Override
+    public void onCameraError(String msg){
+        gLogger.error("onCameraEvent " + msg);
+        if(mUsbMonitor.hasUsbCamera()){
+            //mServer.reopenCamera();
+        }
+    }
+
+    @Override
+    public void onEncoderError(String msg){
+        gLogger.error("onEncoderError: " + msg);
+        doUnbindService();
+        doBindService();
+    }
+
+    @Override
+    public void onPublishing(String msg){
+        mServiceHealthMonitor.record();
+    }
+
+    private void restartApplication() {
+        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
+        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+        startActivity(intent);
     }
 }