Android 12(S) 圖形顯示系統 - 初識ANativeWindow/Surface/SurfaceControl(七)

二的次方發表於2022-03-17

題外話

"行百里者半九十",是說步行一百里路,走過九十里,只能算是走了一半。因為步行越接近目的地,走起來越困難。借指凡事到了接近成功,往往是最吃力、最艱難的時段。勸人做事貴在堅持,有始容易,有終實難。

不多說了,希望自己能堅持寫完這個系列 ......


1 前言

在前幾篇文章中,你應該已經看到文中有冒出來比較多的陌生的類,比如 Surface/SurfaceControl/ANativeWindow/ANativeWindowBuffer,這些類有什麼作用?它們之間有什麼關係?以及它們和BufferQueue之間的關係是怎樣的?我們帶著這些問題,來開始這篇文章的講解

♦ ANativeWindow

♦ Surface

♦ SurfaceControl

♦ ANativeWindowBuffer

2 幾個常用類介紹

ANativeWindow


ANativeWindow 顧名思義,這個結構體是對一個本地視窗的抽象描述。老規矩先看程式碼:

其定義位於:/frameworks/native/libs/nativewindow/include/system/window.h

struct ANativeWindow
{
    // C++ 程式碼下會定義建構函式,並初始化common成員中的部分資訊
#ifdef __cplusplus
    ANativeWindow()
        : flags(0), minSwapInterval(0), maxSwapInterval(0), xdpi(0), ydpi(0)
    {
        common.magic = ANDROID_NATIVE_WINDOW_MAGIC;
        common.version = sizeof(ANativeWindow);
        memset(common.reserved, 0, sizeof(common.reserved));
    }

    /* Implement the methods that sp<ANativeWindow> expects so that it
       can be used to automatically refcount ANativeWindow's. */
    void incStrong(const void* /*id*/) const {
        common.incRef(const_cast<android_native_base_t*>(&common));
    }
    void decStrong(const void* /*id*/) const {
        common.decRef(const_cast<android_native_base_t*>(&common));
    }
#endif
    // 結構體第一個成員,相當於繼承自android_native_base_t,其主要用於引用計數,還有版本資訊
    struct android_native_base_t common;

    /* flags describing some attributes of this surface or its updater */
    const uint32_t flags;

    /* min swap interval supported by this updated */
    const int   minSwapInterval;

    /* max swap interval supported by this updated */
    const int   maxSwapInterval;

    /* horizontal and vertical resolution in DPI */
    const float xdpi;
    const float ydpi;

    /* Some storage reserved for the OEM's driver. */
    intptr_t    oem[4];

    /* 設定swap間隔,跟蹤原始碼可發現其最終呼叫了mGraphicBufferProducer->setAsyncMode,
       也就是設定Producer是同步or非同步模式 */
    int     (*setSwapInterval)(struct ANativeWindow* window,
                int interval);

    /* 請求(出佇列)一塊buffer。執行後這塊buffer就不是locked鎖定狀態,因此內容不能被修改。
       如果沒有可用的buffer,這個方法會被阻塞。
       該方法已被棄用。*/
    int     (*dequeueBuffer_DEPRECATED)(struct ANativeWindow* window,
                struct ANativeWindowBuffer** buffer);

    /* 鎖住buffer。在修改buffer中的內容前一定要先呼叫lock方法。
       這塊buffer首先是dequeueBuffer請求到的。
       該方法已被棄用。*/
     */
    int     (*lockBuffer_DEPRECATED)(struct ANativeWindow* window,
                struct ANativeWindowBuffer* buffer);

    /* 當修改完buffer內容,呼叫這個方法,把buffer返回到佇列中,用於後續顯示輸出。
       該方法已被棄用。*/
    int     (*queueBuffer_DEPRECATED)(struct ANativeWindow* window,
                struct ANativeWindowBuffer* buffer);

    /* 檢索查詢有關 native window 的資訊 
       what指明要查詢資訊的型別,比如 NATIVE_WINDOW_WIDTH 、NATIVE_WINDOW_HEIGHT 查詢寬高*/
    int     (*query)(const struct ANativeWindow* window,
                int what, int* value);

    /* 對surface執行各種操作,比如 NATIVE_WINDOW_SET_USAGE or NATIVE_WINDOW_CONNECT
       一般不會直接呼叫這個方法,而是使用輔助方法,比如 native_window_set_usage */
    int     (*perform)(struct ANativeWindow* window,
                int operation, ... );

    /* 取消已出佇列的buffer。這個方法已被棄用 */
    int     (*cancelBuffer_DEPRECATED)(struct ANativeWindow* window,
                struct ANativeWindowBuffer* buffer);

    /* 請求(出佇列)一塊buffer。如果沒有可用的buffer,這個方法會被阻塞。
       fenceFd是一個fence檔案描述符,可以簡單理解為一個資源同步鎖
       當發出fence訊號後才可以寫buffer */
    int     (*dequeueBuffer)(struct ANativeWindow* window,
                struct ANativeWindowBuffer** buffer, int* fenceFd);

    /* 入佇列一塊buffer */
    int     (*queueBuffer)(struct ANativeWindow* window,
                struct ANativeWindowBuffer* buffer, int fenceFd);

    /* 取消一塊已經dequeue的buffer */
    int     (*cancelBuffer)(struct ANativeWindow* window,
                struct ANativeWindowBuffer* buffer, int fenceFd);
};

/frameworks/native/libs/nativewindow/include/system/window.h這個標頭檔案中,還定義很多enum常量,這些常量的作用這原始碼中都有詳細的英文註釋,建議直接閱讀理解。

用於query()函式檢索資訊的常量

/* attributes queriable with query() */
enum {
    NATIVE_WINDOW_WIDTH = 0,
    NATIVE_WINDOW_HEIGHT = 1,
    NATIVE_WINDOW_FORMAT = 2,
    NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS = ANATIVEWINDOW_QUERY_MIN_UNDEQUEUED_BUFFERS,
    NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER = 4,
    NATIVE_WINDOW_CONCRETE_TYPE = 5,
    NATIVE_WINDOW_DEFAULT_WIDTH = ANATIVEWINDOW_QUERY_DEFAULT_WIDTH,
    NATIVE_WINDOW_DEFAULT_HEIGHT = ANATIVEWINDOW_QUERY_DEFAULT_HEIGHT,
    NATIVE_WINDOW_TRANSFORM_HINT = ANATIVEWINDOW_QUERY_TRANSFORM_HINT,
    NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND = 9,
    NATIVE_WINDOW_CONSUMER_USAGE_BITS = 10, /* deprecated */
    NATIVE_WINDOW_STICKY_TRANSFORM = 11,
    NATIVE_WINDOW_DEFAULT_DATASPACE = 12,
    NATIVE_WINDOW_BUFFER_AGE = ANATIVEWINDOW_QUERY_BUFFER_AGE,
    NATIVE_WINDOW_LAST_DEQUEUE_DURATION = 14,
    NATIVE_WINDOW_LAST_QUEUE_DURATION = 15,
    NATIVE_WINDOW_LAYER_COUNT = 16,
    NATIVE_WINDOW_IS_VALID = 17,
    NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT = 18,
    NATIVE_WINDOW_CONSUMER_IS_PROTECTED = 19,
    NATIVE_WINDOW_DATASPACE = 20,
    NATIVE_WINDOW_MAX_BUFFER_COUNT = 21,
};

用於(*perform)()的標識各種操作的常量

deprecated標記的可能已被棄用或被其他功能函式取代

標記為“私有”的值應被視為框架私有。可以訪問ANativeWindow的HAL實現程式碼不應該使用這些,因為它可能無法與框架對ANativeWindow的使用進行正確的互動。

/* Valid operations for the (*perform)() hook. */
enum {
    // clang-format off
    NATIVE_WINDOW_SET_USAGE                       =  ANATIVEWINDOW_PERFORM_SET_USAGE,   /* deprecated */
    NATIVE_WINDOW_CONNECT                         =  1,   /* deprecated */
    NATIVE_WINDOW_DISCONNECT                      =  2,   /* deprecated */
    NATIVE_WINDOW_SET_CROP                        =  3,   /* private */

    // 完整內容,請參考原始碼    
}

用於NATIVE_WINDOW_[API_][DIS]CONNECT的引數

兩個函式native_window_api_connect  和  native_window_api_disconnect

/* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
enum {
    NATIVE_WINDOW_API_EGL = 1, // 使用OpenGL ES填充buffer後,EGL通過eglSwapBuffers入佇列這個buffer
    NATIVE_WINDOW_API_CPU = 2, // 使用CPU填充buffer後,入佇列buffer
    NATIVE_WINDOW_API_MEDIA = 3, // video解碼器填充buffer後,Stagefright入佇列這個buffer
    NATIVE_WINDOW_API_CAMERA = 4,// 友camera HAL 入佇列buffer
};

用於NATIVE_WINDOW_SET_BUFFERS_TRANSFORM 影像轉換的引數

/* parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM */
enum {
    NATIVE_WINDOW_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H ,// 水平翻轉
    NATIVE_WINDOW_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V, // 垂直翻轉
    NATIVE_WINDOW_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90, // 將源影像按時鐘方向旋轉90度
    NATIVE_WINDOW_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,// 將源影像按時鐘方向旋轉180度
    NATIVE_WINDOW_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270, // 將源影像按時鐘方向旋轉270度
    NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY = 0x08 // 通過對其顯示的螢幕進行逆變換來轉換源。
};

上述引數即用於如下這個函式,buffer顯示時就會按照我們設定的轉換型別進行翻轉、旋轉。

/*
 * native_window_set_buffers_transform(..., int transform)
 * All buffers queued after this call will be displayed transformed according
 * to the transform parameter specified.
 */
static inline int native_window_set_buffers_transform(
        struct ANativeWindow* window,
        int transform)
{
    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TRANSFORM,
            transform);
}

用於NATIVE_WINDOW_SET_SCALING_MODE設定縮放模式的常量

/* parameter for NATIVE_WINDOW_SET_SCALING_MODE */
enum {
    /* the window content is not updated (frozen) until a buffer of
     * the window size is received (enqueued)
     */
    NATIVE_WINDOW_SCALING_MODE_FREEZE           = 0,
    /* the buffer is scaled in both dimensions to match the window size */
    NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW  = 1,
    /* the buffer is scaled uniformly such that the smaller dimension
     * of the buffer matches the window size (cropping in the process)
     */
    NATIVE_WINDOW_SCALING_MODE_SCALE_CROP       = 2,
    /* the window is clipped to the size of the buffer's crop rectangle; pixels
     * outside the crop rectangle are treated as if they are completely
     * transparent.
     */
    NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP    = 3,
};

上述引數即用於如下這個函式

/*
 * native_window_set_scaling_mode(..., int mode)
 * All buffers queued after this call will be associated with the scaling mode
 * specified.
 */
static inline int native_window_set_scaling_mode(
        struct ANativeWindow* window,
        int mode)
{
    return window->perform(window, NATIVE_WINDOW_SET_SCALING_MODE,
            mode);
}

 

Surface


Surface和ANativeWindow存在千絲萬縷的聯絡,Surface繼承了ANativeWindow,並對其中的功能做了具體實現。

ANativeWindow這個結構體中定義了大量的函式指標,這些函式指標指向了哪裡?或函式功能在哪裡?答案就在Surface中。

 

Surface的定義位於:/frameworks/native/libs/gui/include/gui/Surface.h

先看看它的宣告:

class Surface
    : public ANativeObjectBase<ANativeWindow, Surface, RefBase>
{
    ......
}

ANativeObjectBase是一個模板類,作為輔助類將ANativeXXXX的物件型別轉換為C++的引用計數型別

template <typename NATIVE_TYPE, typename TYPE, typename REF,
        typename NATIVE_BASE = android_native_base_t>
class ANativeObjectBase : public NATIVE_TYPE, public REF
{

我們結合上面這兩段程式碼來看,是不是很清晰了:

在Surface的定義中,NATIVE_TYPE==ANativeWindow , REF==RefBas ==> ANativeObjectBase 繼承了ANativeWindow

根據繼承的邏輯關係,很明顯Surface繼承了ANativeWindow

 

Surface中定義了很多函式介面,不過也有些規律。

♦ hook_*的函式

hook函式有10個,這些函式和ANativeWindow中定義的函式指標對應,hook鉤連一塊

他們是怎麼樣鉤連起來的呢?可以看/frameworks/native/libs/gui/Surface.cpp 中建構函式

Surface::Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp,
                 const sp<IBinder>& surfaceControlHandle)
      : .... {
    // Initialize the ANativeWindow function pointers.
    ANativeWindow::setSwapInterval  = hook_setSwapInterval;
    ANativeWindow::dequeueBuffer    = hook_dequeueBuffer;
    ANativeWindow::cancelBuffer     = hook_cancelBuffer;
    ANativeWindow::queueBuffer      = hook_queueBuffer;
    ANativeWindow::query            = hook_query;
    ANativeWindow::perform          = hook_perform;

    ANativeWindow::dequeueBuffer_DEPRECATED = hook_dequeueBuffer_DEPRECATED;
    ANativeWindow::cancelBuffer_DEPRECATED  = hook_cancelBuffer_DEPRECATED;
    ANativeWindow::lockBuffer_DEPRECATED    = hook_lockBuffer_DEPRECATED;
    ANativeWindow::queueBuffer_DEPRECATED   = hook_queueBuffer_DEPRECATED;
}

一目瞭然,Initialize the ANativeWindow function pointers. 初始化函式指標。

比如我們程式中如果呼叫ANativeWindow::query函式,即會呼叫實現具體功能的Surface::hook_query.

 

♦ dispatch*的函式

dispatch函式有46個,前面我們有講到perform函式對應的各種操作,都是會走到對應的dispatch函式中。

我們通過一個例子來說明下具體流程:Android 12(S) 圖形顯示系統 - 示例應用(二)

之前的demo中 ,比如有用到

    // 3. set the ANativeWindow format
    err = native_window_set_buffers_format(nativeWindow, PIXEL_FORMAT_RGBX_8888);

看!native_window_set_buffers_format的定義

static inline int native_window_set_buffers_format(
        struct ANativeWindow* window,
        int format)
{
    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_FORMAT, format);
}

其中繼續呼叫 window->perform(),這個函式對應到了Surface::hook_perform

int Surface::hook_perform(ANativeWindow* window, int operation, ...) {
    va_list args;
    va_start(args, operation);
    Surface* c = getSelf(window); // 型別轉換
    int result;
    // Don't acquire shared ownership of the interceptor mutex if we're going to
    // do interceptor registration, as otherwise we'll deadlock on acquiring
    // exclusive ownership.
    if (!isInterceptorRegistrationOp(operation)) {
        std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
        if (c->mPerformInterceptor != nullptr) {
            result = c->mPerformInterceptor(window, Surface::performInternal,
                                            c->mPerformInterceptorData, operation, args);
            va_end(args);
            return result;
        }
    }
    result = c->perform(operation, args);
    va_end(args);
    return result;
}

接著看! 呼叫c->perform(),流程到了Surface::perform

int Surface::perform(int operation, va_list args)
{
    int res = NO_ERROR;
    switch (operation) {
        ...... 
        case NATIVE_WINDOW_SET_BUFFERS_FORMAT:
        res = dispatchSetBuffersFormat(args);
        break;
        ......   
    }
    
}

switch語句中判斷是哪種case(哪中操作),呼叫對應的dispatchXXX,在我們的例子中即呼叫dispatchSetBuffersFormat

int Surface::dispatchSetBuffersFormat(va_list args) {
    PixelFormat format = va_arg(args, PixelFormat);
    return setBuffersFormat(format);
}

私有方法Surface::setBuffersFormat 中來完成最終的工作。

通過上面這個例子應該就理清了 perform <--> dispatchXXX 的處理流程了

 

♦ 其它的函式和私有成員

Surface中還有很多函式和資料成員,它們提供了操作surface的介面或用於存surface的屬性資訊。

比如 寬、高、畫素格式等屬性資訊

    BufferSlot mSlots[NUM_BUFFER_SLOTS];
    uint32_t mReqWidth;
    uint32_t mReqHeight;
    PixelFormat mReqFormat;
    uint64_t mReqUsage;

我們在此就不展開介紹了,後續講解中如有遇到會再解釋。

 


簡單小結下:ANativeWindow中定義很多函式指標成員變數,Surface繼承自ANativeWindow,當然那些函式指標成員變數也是屬於Surface了,Surface實現了各種功能函式,並且讓ANativeWindow中函式指標成員變數與實際功能函式建立關聯(hook)

window.h中有很多static函式,使用這些函式時就可以透過ANativeWindow呼叫到Surface中的功能了

繞啊繞,繞啊繞,為啥要這樣繞....


 

SurfaceControl


SurfaceControl 顧名思義是用於控制surface的一個類。他是如何進行控制的呢?且讓我們慢慢看....

還記得我們例子中如何建立surface的嗎?可以回頭再看看 Android 12(S) 圖形顯示系統 - 示例應用(二)

使用SurfaceComposerClient::createSurface 獲得了SurfaceControl物件,神奇吧!

    sp<SurfaceControl> surfaceControl = surfaceComposerClient->createSurface(mName, resolution.getWidth(), 
                                                                             resolution.getHeight(), PIXEL_FORMAT_RGBA_8888,
                                                                             ISurfaceComposerClient::eFXSurfaceBufferState,
                                                                             /*parent*/ nullptr);

深入其中,一探究竟,createSurface做了什麼神奇操作呢?

sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
                                                        PixelFormat format, uint32_t flags,
                                                        const sp<IBinder>& parentHandle,
                                                        LayerMetadata metadata,
                                                        uint32_t* outTransformHint) {
    sp<SurfaceControl> s;
    createSurfaceChecked(name, w, h, format, &s, flags, parentHandle, std::move(metadata),
                         outTransformHint);
    return s;
}

繼續去呼叫 createSurfaceChecked

status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
                                                     PixelFormat format,
                                                     sp<SurfaceControl>* outSurface, uint32_t flags,
                                                     const sp<IBinder>& parentHandle,
                                                     LayerMetadata metadata,
                                                     uint32_t* outTransformHint) {
    sp<SurfaceControl> sur;
    status_t err = mStatus;

    if (mStatus == NO_ERROR) {
        sp<IBinder> handle;
        sp<IGraphicBufferProducer> gbp;

        uint32_t transformHint = 0;
        int32_t id = -1;
        err = mClient->createSurface(name, w, h, format, flags, parentHandle, std::move(metadata),
                                     &handle, &gbp, &id, &transformHint);

        if (outTransformHint) {
            *outTransformHint = transformHint;
        }
        ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
        if (err == NO_ERROR) {
            *outSurface =
                    new SurfaceControl(this, handle, gbp, id, w, h, format, transformHint, flags);
        }
    }
    return err;
}

真相已浮現,看到 new SurfaceControl 了

在前面文章 

Android 12(S) 圖形顯示系統 - createSurface的流程(五)Android 12(S) 圖形顯示系統 - BufferQueue/BLASTBufferQueue之初識(六)

我們詳細分析過createSurface的流程,還有SurfaceControl中的資訊,我們再貼一下資訊:

原始碼位置: /frameworks/native/libs/gui/include/gui/SurfaceControl.h

class SurfaceControl : public RefBase
    ...
private:
    sp<SurfaceComposerClient>   mClient;                 // 應用建立的SurfaceComposerClient物件指標,裡面封裝了和SurfaceFlinger通訊的Binder客戶端
    sp<IBinder>                 mHandle;                 // 應用中顯式建立的layer handle,這是個BufferStateLayer 它作為parent
    sp<IGraphicBufferProducer>  mGraphicBufferProducer;  // 這個貌似沒有實際用了?
    mutable Mutex               mLock;
    mutable sp<Surface>         mSurfaceData;            // 
    mutable sp<BLASTBufferQueue> mBbq;                   // BLASTBufferQueue物件例項
    mutable sp<SurfaceControl> mBbqChild;                // child layer,它會和mBbq相關聯
    int32_t mLayerId;                                    // layer id
    uint32_t mTransformHint;                             // 方向
    uint32_t mWidth;                                     // surface 寬
    uint32_t mHeight;                                    // surface 高
    PixelFormat mFormat;
    uint32_t mCreateFlags;                               // createSurface的標誌資訊
};

 

SurfaceControl中持有Surface:mSurfaceData, 持有BufferQueue:mBbq 這就是控制的基礎

總結一張圖

 

3 小結

ANativeWindow/Surface/SurfaceControl的基本就介紹這些了,主要是瞭解這些類內有什麼內容,可以使用他們做些什麼操作,以及他們與其它圖形元件的關係。

 

相關文章