Android中多USB攝像頭解決方案——UVCCamera

??????先貼上采用的開源庫鏈接:https://github.com/saki4510t/UVCCamera

??????業(yè)余時(shí)間搗鼓了下Android 板子連接多個(gè)usb攝像頭的方案,一開始使用系統(tǒng)的CameraV1的api,但是取到的攝像頭數(shù)量一直不對(api: Camera.getNumberOfCameras()),然后又去網(wǎng)上查了方案(傳送門:https://blog.csdn.net/xiangzhihong8/article/details/82877901)發(fā)現(xiàn)Android P之后原生就支持多攝像頭,心里美滋滋,這么快就大結(jié)局了,但是果然天不遂人愿,于是改用CameraV2的api,但還是識別不到完整的攝像頭列表。沒查到具體原因,但是猜測是跟Android板子有關(guān),雖然在軟件上已經(jīng)支持多攝像頭,但是底層可能還是限制了最大連接數(shù)量。之后去應(yīng)用市場下了一個(gè)usb攝像頭app,發(fā)現(xiàn)居然是可以正常識別出所有的攝像頭,遂反編譯之,發(fā)現(xiàn)是使用了UVCCamera。這個(gè)開源庫貌似已經(jīng)很久沒有維護(hù),并且根據(jù)之前使用的經(jīng)驗(yàn)來看也有不少bug(主要是兼容性方面),但是項(xiàng)目中用到的硬件只有一個(gè)型號,并不需要做太多設(shè)備兼容性的適配,因此還是可以拿來一用。下面就分享一下UVCCamera的接入過程。

??????無論使用哪種Camera的api,Camera的封裝都可以大致分為兩個(gè)流程:數(shù)據(jù)采集、渲染。于是我們就可以定義出這兩塊功能的接口:

數(shù)據(jù)采集

public interface ICamera {
    List<String> getCameras();

    interface OnPhotoTake {
        void onPhotoTake(Bitmap reader,String path);
    }

    boolean open(String id);

    void close();

    void takePicture(OnPhotoTake onPhotoTake,String id);
}

渲染

public interface CameraViewInterface extends IAspectRatioView {
    interface Callback {
        void onSurfaceCreated(CameraViewInterface view, Surface surface);

        void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height);

        void onSurfaceDestroy(CameraViewInterface view, Surface surface);
    }

    void onPause();

    void onResume();

    void setCallback(Callback callback);

    SurfaceTexture getSurfaceTexture();

    Surface getSurface();

    boolean hasSurface();

    void setVideoEncoder(final IVideoEncoder encoder);

    Bitmap captureStillImage(int width, int height);
}

??????雖然是多個(gè)攝像頭,但是我們可以用一個(gè)單例類來統(tǒng)一管理——UVCCameraHelper。在這個(gè)類中我們要做的事有:連接上usb攝像頭設(shè)備,開啟攝像頭采集數(shù)據(jù)并將數(shù)據(jù)渲染到surface上,此外還需要提供拍照、視頻錄制等api。那么這里就需要用到UVCCcamera這個(gè)開源庫了。我們需要在UVCCameraHelper定義一個(gè)USBMonitor對象,這個(gè)類的核心接口提供了USB設(shè)備的連接狀態(tài)維護(hù)。

public interface OnDeviceConnectListener {
        /**
         * called when device attached
         * @param device
         */
        public void onAttach(UsbDevice device);
        /**
         * called when device dettach(after onDisconnect)
         * @param device
         */
        public void onDettach(UsbDevice device);
        /**
         * called after device opend
         * @param device
         * @param ctrlBlock
         * @param createNew
         */
        public void onConnect(UsbDevice device, UsbControlBlock ctrlBlock, boolean createNew);
        /**
         * called when USB device removed or its power off (this callback is called after device closing)
         * @param device
         * @param ctrlBlock
         */
        public void onDisconnect(UsbDevice device, UsbControlBlock ctrlBlock);
        /**
         * called when canceled or could not get permission from user
         * @param device
         */
        public void onCancel(UsbDevice device);
    }

??????UVCCameraHelper中開啟USB攝像頭預(yù)覽的方法:

 public void requestPermission(int index) {
        List<UsbDevice> devList = getUsbDeviceList();
        if (devList == null || devList.size() == 0) {
            return;
        }
        int count = devList.size();
        if (index >= count)
            new IllegalArgumentException("index illegal,should be < devList.size()");
        if (mUSBMonitor != null) {
            mUSBMonitor.requestPermission(getUsbDeviceList().get(index));
        }
    }

    public int getUsbDeviceCount() {
        List<UsbDevice> devList = getUsbDeviceList();
        if (devList == null || devList.size() == 0) {
            return 0;
        }
        return devList.size();
    }

    public List<UsbDevice> getUsbDeviceList() {
        List<DeviceFilter> deviceFilters = DeviceFilter
                .getDeviceFilters(mActivity.getApplicationContext(), R.xml.device_filter_uvc);
        if (mUSBMonitor == null || deviceFilters == null)
            return null;
        return mUSBMonitor.getDeviceList(deviceFilters.get(0));
    }

??????可以看到在requestPermission方法中先根據(jù)指定的index從usb設(shè)備列表中拿到設(shè)備,然后再調(diào)用了USBMonitor的requestPermission方法。我們繼續(xù)看USBMonitor的requestPermission方法:

public synchronized boolean requestPermission(final UsbDevice device) {
//      if (DEBUG) Log.v(TAG, "requestPermission:device=" + device);
        boolean result = false;
        if (isRegistered()) {
            if (device != null) {
                if (mUsbManager.hasPermission(device)) {
                    // call onConnect if app already has permission
                    processConnect(device);
                } else {
                    try {
                        // パーミッションがなければ要求する
                        mUsbManager.requestPermission(device, mPermissionIntent);
                    } catch (final Exception e) {
                        // Android5.1.xのGALAXY系でandroid.permission.sec.MDM_APP_MGMTという意味不明の例外生成するみたい
                        Log.w(TAG, e);
                        processCancel(device);
                        result = true;
                    }
                }
            } else {
                processCancel(device);
                result = true;
            }
        } else {
            processCancel(device);
            result = true;
        }
        return result;
    }

??????在該方法中注解居然是日文的(因?yàn)樽髡呤侨毡救耍?,居然讓我感到有種莫名的中二感……言歸正傳,該方法主要就是先判斷是否已經(jīng)對當(dāng)前USB設(shè)備授權(quán),如果未授權(quán)則先彈授權(quán)彈窗,如果已經(jīng)授權(quán)那么就執(zhí)行processConnect方法:

private final void processConnect(final UsbDevice device) {
        if (destroyed) return;
        updatePermission(device, true);
        mAsyncHandler.post(new Runnable() {
            @Override
            public void run() {
                if (DEBUG) Log.v(TAG, "processConnect:device=" + device);
                UsbControlBlock ctrlBlock;
                final boolean createNew;
                ctrlBlock = mCtrlBlocks.get(device);
                if (ctrlBlock == null) {
                    ctrlBlock = new UsbControlBlock(USBMonitor.this, device);
                    mCtrlBlocks.put(device, ctrlBlock);
                    createNew = true;
                } else {
                    createNew = false;
                }
                if (mOnDeviceConnectListener != null) {
                    mOnDeviceConnectListener.onConnect(device, ctrlBlock, createNew);
                }
            }
        });
    }

??????在該方法中會創(chuàng)建一個(gè)UsbControlBlock對象,在該對象中會根據(jù)傳入的UsbDevice維護(hù)一個(gè)UsbDeviceConnection,這個(gè)類是被用來對USB設(shè)備做收發(fā)數(shù)據(jù)以及控制命令的(This class is used for sending and receiving data and control messages to a USB device.)然后就會回調(diào)到我們之前定義的OnDeviceConnectListener接口的onConnect方法。之后在onConnect中就會真正開啟攝像頭預(yù)覽。
我們定義一個(gè)CameraThread繼承自Thread,將所有操作放到子線程中,然后再定一個(gè)Handler類來維護(hù)所有預(yù)覽(數(shù)據(jù)采集+渲染)相關(guān)操作,這樣我們就可以通過消息機(jī)制來控制所有操作的執(zhí)行順序了。
??????我們先來看onConnect中調(diào)用的openCamera(USBMonitor.UsbControlBlock ctrlBlock),它實(shí)際就是通過Handler來執(zhí)行消息的發(fā)送與處理:

private void openCamera(USBMonitor.UsbControlBlock ctrlBlock) {
        if (mCameraHandler != null) {
            mCameraHandler.open(ctrlBlock);
        }
}
 public void open(final USBMonitor.UsbControlBlock ctrlBlock) {
        checkReleased();
        sendMessage(obtainMessage(MSG_OPEN, ctrlBlock));
}

 case MSG_OPEN:
    thread.handleOpen((USBMonitor.UsbControlBlock) msg.obj);

??????這里需要提的是在thread的handleOpen方法中會創(chuàng)建UVCCamera這個(gè)核心類,它會調(diào)用到j(luò)ni層的api去做真正的相機(jī)相關(guān)操作。
我們繼續(xù)回到onConnect,在開啟相機(jī)之后會接著調(diào)用startPreview方法來將采集到的數(shù)據(jù)綁定到一塊surface上:

public void startPreview(final Object surface) {
        checkReleased();
        if (!((surface instanceof SurfaceHolder) || (surface instanceof Surface) || (surface instanceof SurfaceTexture))) {
            throw new IllegalArgumentException("surface should be one of SurfaceHolder, Surface or SurfaceTexture: " + surface);
        }
        sendMessage(obtainMessage(MSG_PREVIEW_START, surface));
}
 case MSG_PREVIEW_START:
    thread.handleStartPreview(msg.obj);

??????預(yù)覽開啟之后對于拍照等操作也是類似:

public void captureStill(final String path, AbstractUVCCameraHandler.OnCaptureListener listener) {
        AbstractUVCCameraHandler.mCaptureListener = listener;
        checkReleased();
        sendMessage(obtainMessage(MSG_CAPTURE_STILL, path));
        isCaptureStill = true;
}
case MSG_CAPTURE_STILL:
    thread.handleStillPicture((String) msg.obj);

??????這樣一個(gè)基本的攝像頭開啟、拍照流程就走完了,當(dāng)然還有很多細(xì)節(jié)處理沒有一一列出來,如異常處理、各種狀態(tài)判斷等等,這些需要在實(shí)際項(xiàng)目開發(fā)中根據(jù)自己的業(yè)務(wù)來做處理即可。
未來我會繼續(xù)去扒jni層的代碼,看看底層開啟相機(jī)具體又做了哪些事情,就請繼續(xù)期待后續(xù)的分享文章。
??????從事的工作剛好是自己的愛好,是一件無比幸福的事情。哪怕在業(yè)余時(shí)間也會像在打游戲一樣樂在其中。慢慢找回自己吧。

UVCCamera源碼分析(一):
http://www.itdecent.cn/p/f7f548c2c0e7
UVCCamera源碼分析(二):
http://www.itdecent.cn/p/225734c143ba
UVCCamera源碼分析(三):
http://www.itdecent.cn/p/313e6e4ca418
UVCCamera源碼分析(四):
http://www.itdecent.cn/p/e7e370011775
UVCCamera源碼分析(五):
http://www.itdecent.cn/p/3b7f3ff6ab45

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容