0d0136d5d0a4032659efeb0d436b1999f1c4daf8
[rtmpclient.git] / app / src / main / java / ai / suanzi / rtmpclient / MyService.java
1 package ai.suanzi.rtmpclient;
2
3 import android.app.Service;
4 import android.content.Intent;
5 import android.graphics.SurfaceTexture;
6 import android.hardware.Camera;
7 import android.os.Handler;
8 import android.os.HandlerThread;
9 import android.os.IBinder;
10 import android.os.Looper;
11 import android.util.Log;
12 import android.view.SurfaceHolder;
13 import android.view.SurfaceView;
14 import android.view.WindowManager;
15 import android.widget.Toast;
16 import android.support.v4.app.NotificationCompat;
17 import android.graphics.BitmapFactory;
18 import android.app.Notification;
19 import android.os.Message;
20 import org.apache.log4j.Level;
21 import org.apache.log4j.Logger;
22 import android.hardware.Camera.PreviewCallback;
23 import android.os.IBinder;
24 import android.os.Binder;
25 import android.content.Context;
26 import android.graphics.PixelFormat;
27 import java.io.IOException;
28 import android.view.Gravity;
29
30 public class MyService extends Service  implements Camera.PreviewCallback {
31
32     private static Logger gLogger = Logger.getLogger("MyService");
33     private static String TAG = "MyService";
34
35     private Ffmpeg ffmpeg = Ffmpeg.getInstance();
36     private  Boolean isRunning = false;
37     private Camera mCamera = null;
38     IBinder mBinder = new LocalBinder();
39     private String rtmpUrl;
40     private long frameCount = 0;
41
42
43     public class LocalBinder extends Binder {
44         public MyService getServiceInstance(){
45             return MyService.this;
46         }
47     }
48
49     public Camera getCameraInstance() {
50         if (mCamera == null) {
51             CameraHandlerThread mThread = new CameraHandlerThread("camera thread");
52             synchronized (mThread) {
53                 mThread.openCamera();
54             }
55         }
56         if (mCamera == null){
57             gLogger.error("getCameraInstance, camera is null");
58         }
59         return mCamera;
60     }
61
62     private void openCameraOriginal() {
63         try {
64             gLogger.error("openCameraOriginal");
65             mCamera = Camera.open(1);
66         } catch (Exception e) {
67             gLogger.error("camera is not available. error: " + e.getMessage());
68         }
69     }
70
71     private class CameraHandlerThread extends HandlerThread {
72         Handler mHandler;
73
74         public CameraHandlerThread(String name) {
75             super(name);
76             gLogger.error("CameraHandlerThread: " + name);
77             start();
78             mHandler = new Handler(getLooper());
79         }
80
81         synchronized void notifyCameraOpened() {
82             notify();
83         }
84
85         void openCamera() {
86             mHandler.post(new Runnable() {
87                 @Override
88                 public void run() {
89                     openCameraOriginal();
90                     notifyCameraOpened();
91                 }
92             });
93             try {
94                 wait();
95             } catch (InterruptedException e) {
96                 gLogger.error("wait was interrupted");
97             }
98         }
99     }
100
101     private static final int NOTIFICATION_DOWNLOAD_PROGRESS_ID = 0x0001;                                        //id不可设置为0,否则不能设置为前台service
102     private void createNotification(){
103         gLogger.debug("createNotification");
104         NotificationCompat.Builder builder=new NotificationCompat.Builder(this);                        //使用兼容版本
105         builder.setSmallIcon(R.mipmap.ic_launcher);                                                             //设置状态栏的通知图标
106         builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_background));   //设置通知栏横条的图标
107         builder.setAutoCancel(false);                                                                           //禁止用户点击删除按钮删除
108         builder.setOngoing(true);                                                                               //禁止滑动删除
109         builder.setShowWhen(true);                                                                              //右上角的时间显示
110         builder.setContentTitle("Rtmp Foreground Service!!!");                                                  //设置通知栏的标题内容
111         Notification notification = builder.build();                                                            //创建通知
112         startForeground(NOTIFICATION_DOWNLOAD_PROGRESS_ID,notification);                                        //设置为前台服务
113     }
114
115     @Override
116     public IBinder onBind(Intent intent) {
117         return mBinder;
118     }
119
120     @Override
121     public void onCreate() {
122         super.onCreate();
123         gLogger.error("onCreate ---> ");
124         createNotification();
125         Toast.makeText(this, "Video stream pushed to " + this.rtmpUrl, Toast.LENGTH_LONG).show();
126         mCamera = getCameraInstance();
127         configCamera(mCamera);
128     }
129
130     @Override
131     public void onDestroy() {
132         stopForeground(true);
133         super.onDestroy();
134         gLogger.error( "onDestroy --------->");
135         Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
136         if(mCamera != null){
137             mCamera.stopPreview();
138             mCamera.release();
139         }
140     }
141
142
143     @Override
144     public int onStartCommand(Intent intent, int flags, int startId) {
145         gLogger.error("onStartCommand");
146         //nrunnable = new FfmpegRunnable("xxx", this);
147         //new Thread(runnable).start();
148         return START_STICKY;
149     }
150
151     @Override
152     public void onLowMemory(){
153         super.onLowMemory();
154         gLogger.error("onLowMemory");
155     }
156
157     // Camera.PreviewCallback
158     @Override
159     public void  onPreviewFrame(final byte[] data, Camera camera){
160         if(frameCount % (15 * 60) == 0) {
161             gLogger.error("onPreviewFrame");
162         }
163         frameCount++;
164         ffmpeg.process(data);
165     }
166
167     public void startPreview (SurfaceHolder holder){
168         gLogger.error("startPreview");
169         if (mCamera == null){
170             gLogger.error("startPreview - error: camera is null");
171             return;
172         }
173         try {
174             mCamera.setPreviewDisplay(holder);
175             mCamera.startPreview();
176         } catch (Exception e){
177             gLogger.error("startPreview - error: " + e.getMessage());
178             e.printStackTrace();
179         }
180     }
181
182     public boolean setRtmpUrl (String url){
183         this.rtmpUrl = url;
184         Camera.Parameters param = mCamera.getParameters();
185         int width = param.getPictureSize().width;
186         int height = param.getPictureSize().height;
187         gLogger.error("setRtmpUrl - size: " +  width + "x" + height + ". url: " + url);
188         int ret = ffmpeg.initnew(width, height, url);
189         return ret == 0 ? true : false;
190     }
191
192     private void configCamera(Camera camera){
193         if(mCamera == null){
194             gLogger.error("configCamera - camera is null");
195             return;
196         }
197         Camera.Parameters paras = camera.getParameters();
198         gLogger.error("Supported Picture Sizes:");
199         Camera.Size preferredSize = paras.getSupportedPictureSizes().get(0);
200         for (Camera.Size cc : paras.getSupportedPictureSizes()){
201             if (cc.width == 640)
202                 preferredSize = cc;
203             gLogger.error(cc.width + "x" + cc.height);
204         }
205         gLogger.error("Supported Preview fps range:");
206         for(int[] i : paras.getSupportedPreviewFpsRange()){
207             gLogger.error("[" + i[0] + "," + i[1] + "]");
208         }
209         paras.setPictureSize(preferredSize.width, preferredSize.height); // use 640x480 preferred
210         camera.setParameters(paras);
211         camera.setDisplayOrientation(0);
212         gLogger.error("Preview Format: " + paras.getPreviewFormat() + ". Size: " + paras.getPreviewSize().width + "x" + paras.getPreviewSize().height);
213         gLogger.error("Picture Format: " + paras.getPictureFormat() + ". Size: " + paras.getPictureSize().width + "x" + paras.getPictureSize().height);
214         camera.setPreviewCallback(this);
215     }
216 }