Dana
8 天以前 01d5238738887b1739cede0c6b589b8c4e34031d
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
package com.safeluck.floatwindow.manager;
 
import android.content.Context;
 
import com.alivc.live.pusher.AlivcAudioAACProfileEnum;
import timber.log.Timber;
import com.alivc.live.pusher.AlivcEncodeModeEnum;
import com.alivc.live.pusher.AlivcFpsEnum;
import com.alivc.live.pusher.AlivcImageFormat;
import com.alivc.live.pusher.AlivcLivePushCameraTypeEnum;
import com.alivc.live.pusher.AlivcLivePushConfig;
import com.alivc.live.pusher.AlivcLivePushError;
import com.alivc.live.pusher.AlivcLivePushErrorListener;
import com.alivc.live.pusher.AlivcLivePushInfoListener;
import com.alivc.live.pusher.AlivcLivePushNetworkListener;
import com.alivc.live.pusher.AlivcLivePushStats;
import com.alivc.live.pusher.AlivcLivePusher;
import com.alivc.live.pusher.AlivcPreviewOrientationEnum;
import com.alivc.live.pusher.AlivcQualityModeEnum;
import com.alivc.live.pusher.AlivcResolutionEnum;
import com.anyun.libusbcamera.UsbCamera;
import com.safeluck.floatwindow.MediaArgu;
import com.safeluck.floatwindow.ResponseVO;
 
/**
 * USB摄像头推流管理器
 */
public class UsbCameraPushManager {
    private static final String TAG = "UsbCameraPushManager";
    
    private Context context;
    private MediaArgu mediaArgu;
    private PushCallback callback;
    
    // 阿里推流相关
    private AlivcLivePusher alivcPusher;
    private AlivcLivePushConfig alivcLivePushConfig;
    
    // USB摄像头相关
    private UsbCamera usbCamera;
    private PushThread pushThread;
    private boolean isRunning = false;
    private boolean cameraExists = false;
    
    // 推流URL
    private String pushUrl;
    
    // 分辨率数组 [width, height]
    private int[] resolutionArr = new int[]{640, 480};
    
    // 是否开启摄像头加密
    private boolean ay_encrypt = false;
    
    /**
     * 推流回调接口
     */
    public interface PushCallback {
        void onResult(ResponseVO response);
    }
    
    public UsbCameraPushManager(Context context) {
        this.context = context;
    }
    
    /**
     * 设置回调
     */
    public void setCallback(PushCallback callback) {
        this.callback = callback;
    }
    
    /**
     * 开始推流
     */
    public void startPush(MediaArgu media) {
        if (media == null) {
            notifyCallback(1, -1, "MediaArgu is null");
            return;
        }
        
        this.mediaArgu = media;
        this.pushUrl = media.getUrl();
        
        if (pushUrl == null || pushUrl.isEmpty()) {
            notifyCallback(1, -2, "Push URL is empty");
            return;
        }
        
        // 设置分辨率
        if (media.getM_screen() != null) {
            resolutionArr[0] = media.getM_screen().getWidth();
            resolutionArr[1] = media.getM_screen().getHeight();
            Timber.d("设置分辨率: %dx%d", resolutionArr[0], resolutionArr[1]);
        }
        
        try {
            // 初始化推流SDK
            initAlivcPusher();
            
            // 检查并打开USB摄像头
            if (!openUsbCamera()) {
                cameraExists = false;
                notifyCallback(1, -1, "USB摄像头打开失败");
                return;
            }
            
            cameraExists = true;
            Timber.d("USB摄像头打开成功");
            
            // 启动摄像头数据推送线程
            startPushThread();
            
            notifyCallback(1, 0, "推流已启动");
        } catch (Exception e) {
            Timber.e(e, "Failed to start push");
            notifyCallback(1, -3, "启动推流失败: " + e.getMessage());
        }
    }
    
    /**
     * 停止推流
     */
    public void stopPush() {
        Timber.d("stopPush called");
        stopPushThread();
        releaseAlivcPusher();
        if (usbCamera != null) {
            usbCamera.stopCamera();
        }
        notifyCallback(1, 4, "推流已停止");
    }
    
    /**
     * 初始化阿里推流
     */
    private void initAlivcPusher() {
        try {
            alivcLivePushConfig = new AlivcLivePushConfig();
            
            // 根据分辨率设置
            setResolutionFromArray(resolutionArr);
            
            // 建议用户使用20fps
            alivcLivePushConfig.setFps(AlivcFpsEnum.FPS_20);
            
            // 打开码率自适应
            alivcLivePushConfig.setEnableBitrateControl(true);
            
            // 设置横屏方向
            alivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_LANDSCAPE_HOME_LEFT);
            
            // 设置音频编码模式
            alivcLivePushConfig.setAudioProfile(AlivcAudioAACProfileEnum.AAC_LC);
            
            // 设置摄像头类型
            alivcLivePushConfig.setCameraType(AlivcLivePushCameraTypeEnum.CAMERA_TYPE_BACK);
            
            // 设置视频编码模式为硬编码
            alivcLivePushConfig.setVideoEncodeMode(AlivcEncodeModeEnum.Encode_MODE_HARD);
            
            // 关闭美颜
            alivcLivePushConfig.setBeautyOn(false);
            
            // 清晰度优先模式
            alivcLivePushConfig.setQualityMode(AlivcQualityModeEnum.QM_RESOLUTION_FIRST);
            
            // 设置自定义流模式
            alivcLivePushConfig.setExternMainStream(true);
            alivcLivePushConfig.setAlivcExternMainImageFormat(AlivcImageFormat.IMAGE_FORMAT_YUV420P);
            
            // 初始化推流器
            alivcPusher = new AlivcLivePusher();
            alivcPusher.init(context.getApplicationContext(), alivcLivePushConfig);
            
            // 设置监听器
            setupListeners();
            
            Timber.d("AlivcPusher initialized successfully");
        } catch (Exception e) {
            Timber.e(e, "Failed to initialize AlivcPusher");
            notifyCallback(1, -3, "初始化推流SDK失败: " + e.getMessage());
        }
    }
    
    /**
     * 设置监听器
     */
    private void setupListeners() {
        // 推流信息监听器
        alivcPusher.setLivePushInfoListener(new AlivcLivePushInfoListener() {
            @Override
            public void onPreviewStarted(AlivcLivePusher alivcLivePusher) {
                Timber.d("onPreviewStarted");
                android.os.Handler handler = new android.os.Handler(android.os.Looper.getMainLooper());
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (alivcPusher != null && 
                            alivcPusher.getCurrentStatus() != AlivcLivePushStats.PREVIEWED && 
                            alivcPusher.getCurrentStatus() != AlivcLivePushStats.PUSHED) {
                            Timber.w("Preview状态异常");
                        } else {
                            if (cameraExists && pushUrl != null && !pushUrl.isEmpty()) {
                                Timber.d("开始推流: %s", pushUrl);
                                alivcPusher.startPushAysnc(pushUrl);
                            }
                        }
                    }
                }, 1000);
            }
            
            @Override
            public void onPreviewStoped(AlivcLivePusher alivcLivePusher) {
                Timber.d("onPreviewStoped");
            }
            
            @Override
            public void onPushStarted(AlivcLivePusher alivcLivePusher) {
                Timber.d("onPushStarted");
                notifyCallback(1, 0, "推流已开始,分辨率: " + resolutionArr[0] + "x" + resolutionArr[1]);
            }
            
            @Override
            public void onPushPauesed(AlivcLivePusher alivcLivePusher) {
                Timber.d("onPushPauesed");
            }
            
            @Override
            public void onPushResumed(AlivcLivePusher alivcLivePusher) {
                Timber.d("onPushResumed");
            }
            
            @Override
            public void onPushStoped(AlivcLivePusher alivcLivePusher) {
                Timber.d("onPushStoped");
                notifyCallback(1, 4, "推流已停止");
            }
            
            @Override
            public void onPushRestarted(AlivcLivePusher alivcLivePusher) {
                Timber.d("onPushRestarted");
            }
            
            @Override
            public void onFirstFramePreviewed(AlivcLivePusher alivcLivePusher) {
                Timber.d("onFirstFramePreviewed");
            }
            
            @Override
            public void onDropFrame(AlivcLivePusher alivcLivePusher, int i, int i1) {
                // 丢帧回调
            }
            
            @Override
            public void onAdjustBitRate(AlivcLivePusher alivcLivePusher, int i, int i1) {
                // 码率调整回调
            }
            
            @Override
            public void onAdjustFps(AlivcLivePusher alivcLivePusher, int i, int i1) {
                // 帧率调整回调
            }
        });
        
        // 错误监听器
        alivcPusher.setLivePushErrorListener(new AlivcLivePushErrorListener() {
            @Override
            public void onSystemError(AlivcLivePusher alivcLivePusher, AlivcLivePushError alivcLivePushError) {
                Timber.e("onSystemError: %s", alivcLivePushError.toString());
                notifyCallback(1, -3, "系统错误: " + alivcLivePushError.toString());
                if (alivcLivePusher != null) {
                    alivcLivePusher.stopPush();
                }
            }
            
            @Override
            public void onSDKError(AlivcLivePusher alivcLivePusher, AlivcLivePushError alivcLivePushError) {
                Timber.e("onSDKError: %s", alivcLivePushError.toString());
                notifyCallback(1, -3, "SDK错误: " + alivcLivePushError.toString());
                if (alivcLivePusher != null) {
                    alivcLivePusher.restartPushAync();
                }
            }
        });
        
        // 网络监听器
        alivcPusher.setLivePushNetworkListener(new AlivcLivePushNetworkListener() {
            @Override
            public void onNetworkPoor(AlivcLivePusher alivcLivePusher) {
                Timber.w("onNetworkPoor");
                notifyCallback(1, 3, "网络较差");
            }
            
            @Override
            public void onNetworkRecovery(AlivcLivePusher alivcLivePusher) {
                Timber.d("onNetworkRecovery");
                notifyCallback(1, 0, "网络恢复");
            }
            
            @Override
            public void onReconnectStart(AlivcLivePusher alivcLivePusher) {
                Timber.d("onReconnectStart");
            }
            
            @Override
            public void onReconnectFail(AlivcLivePusher alivcLivePusher) {
                Timber.e("onReconnectFail");
                notifyCallback(1, 2, "重连失败");
            }
            
            @Override
            public void onReconnectSucceed(AlivcLivePusher alivcLivePusher) {
                Timber.d("onReconnectSucceed");
                notifyCallback(1, 0, "重连成功");
            }
            
            @Override
            public void onSendDataTimeout(AlivcLivePusher alivcLivePusher) {
                Timber.w("onSendDataTimeout");
            }
            
            @Override
            public void onConnectFail(AlivcLivePusher alivcLivePusher) {
                Timber.e("onConnectFail");
                notifyCallback(1, -2, "连接失败");
            }
            
            @Override
            public String onPushURLAuthenticationOverdue(AlivcLivePusher alivcLivePusher) {
                Timber.w("onPushURLAuthenticationOverdue");
                return null;
            }
            
            @Override
            public void onSendMessage(AlivcLivePusher alivcLivePusher) {
                // 发送消息回调
            }
        });
    }
    
    /**
     * 根据分辨率数组设置分辨率
     */
    private void setResolutionFromArray(int[] arr) {
        for (int a : arr) {
            switch (a) {
                case 180:
                    alivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_180P);
                    break;
                case 240:
                    alivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_240P);
                    break;
                case 360:
                    alivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_360P);
                    break;
                case 480:
                    alivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_480P);
                    break;
                case 540:
                    alivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_540P);
                    break;
                case 720:
                    alivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_720P);
                    break;
                default:
                    alivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_240P);
                    break;
            }
        }
    }
    
    /**
     * 打开USB摄像头
     */
    private boolean openUsbCamera() {
        try {
            if (usbCamera == null) {
                usbCamera = new UsbCamera();
            }
 
            // 打开摄像头之前先调用setenv
            usbCamera.setenv();
 
            // 使用prepareCamera方法,camera_id范围[0,9]
            int[] cameraIds = {0, 9};
            String cameraName = null; // 不指定特定名称
 
            // 如果返回非0,代表打开失败,则先stopCamera再重试,最多3次
            int ret = -1;
            for (int i = 0; i < 3; i++) {
                ret = usbCamera.prepareCamera(cameraIds, cameraName, resolutionArr, ay_encrypt);
                Timber.d("USB摄像头第%d次打开结果: %d, 分辨率: %dx%d", i + 1, ret, resolutionArr[0], resolutionArr[1]);
                if (ret == 0) {
                    break;
                }
                // 打开失败则先关闭再重试
                usbCamera.stopCamera();
            }
 
            // 成功标准:prepareCamera 返回 0
            return ret == 0;
        } catch (Exception e) {
            Timber.e(e, "打开USB摄像头异常");
            return false;
        }
    }
    
    /**
     * 启动推流线程
     */
    private void startPushThread() {
        if (pushThread == null || !isRunning) {
            isRunning = true;
            pushThread = new PushThread();
            pushThread.start();
            Timber.d("Push thread started");
        }
    }
    
    /**
     * 停止推流线程
     */
    private void stopPushThread() {
        isRunning = false;
        if (pushThread != null) {
            try {
                pushThread.join(1000);
            } catch (InterruptedException e) {
                Timber.e(e, "Error stopping push thread");
            }
            pushThread = null;
        }
        Timber.d("Push thread stopped");
    }
    
    /**
     * 释放阿里推流资源
     */
    private void releaseAlivcPusher() {
        if (alivcPusher != null) {
            try {
                AlivcLivePushStats stats = alivcPusher.getCurrentStatus();
                Timber.d("当前推流状态: %s", stats != null ? stats.name() : "null");
                
                if (stats != null && (stats == AlivcLivePushStats.PUSHED || 
                    stats == AlivcLivePushStats.PREVIEWED)) {
                    alivcPusher.stopPush();
                }
                alivcPusher.destroy();
            } catch (Exception e) {
                Timber.e(e, "Error releasing AlivcPusher");
            }
            alivcPusher = null;
        }
        alivcLivePushConfig = null;
    }
    
    /**
     * 推流线程
     */
    private class PushThread extends Thread {
        @Override
        public void run() {
            super.run();
            Timber.d("PushThread started");
            
            try {
                int width = resolutionArr[0];
                int height = resolutionArr[1];
                
                // 计算YUV420缓冲区大小
                int bufferSize = width * height * 3 / 2;
                byte[] buffer = new byte[bufferSize];
                
                Timber.d("开始推送视频数据,分辨率: %dx%d", width, height);
                
                // 循环处理摄像头数据
                while (isRunning && cameraExists) {
                    // 处理摄像头数据
                    int processResult = usbCamera.processCamera();
                    if (processResult == -1) {
                        Timber.w("processCamera返回-1,摄像头可能断开");
                        cameraExists = false;
                        notifyCallback(1, -1, "USB摄像头断开");
                        break;
                    }
                    
                    // 获取YUV数据 (参数1表示推流)
                    usbCamera.rgba(1, buffer);
                    
                    // 推流数据到阿里云
                    if (alivcPusher != null && cameraExists) {
                        try {
                            alivcPusher.inputStreamVideoData(
                                    buffer,
                                    width,
                                    height,
                                    buffer.length,
                                    System.nanoTime() / 1000, // 转换为微秒
                                    0 // rotation
                            );
                        } catch (Exception e) {
                            Timber.e(e, "Error pushing frame");
                        }
                    }
                    
                    // 控制帧率,约20fps
                    Thread.sleep(50);
                }
                
            } catch (Exception e) {
                Timber.e(e, "Error in push thread");
                cameraExists = false;
                notifyCallback(1, -1, "推流线程异常: " + e.getMessage());
            } finally {
                Timber.d("PushThread ended");
            }
        }
    }
    
    /**
     * 通知回调
     */
    private void notifyCallback(int type, int errCode, String message) {
        if (callback != null) {
            ResponseVO response = new ResponseVO();
            response.setType(type);
            response.setErrCode(errCode);
            response.setMessage(message);
            callback.onResult(response);
        }
    }
}