Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入剖析 Android 開機動畫的三個階段

編輯:關於 Android 程式設計

Android 系統的開機動畫可以劃分為三個部分:kernel 啟動、init 進程啟動、以及 Android 系統服務啟動。這三段動畫都是在同一個稱為幀緩衝區(frame buffer)的硬件設備上渲染繪制的。

在 Linux 內核中,每個硬件設備都有一個主設備號和一個從設備號,用來唯一標識設備。對於幀緩衝區來說,主設備號定義為 FB_MAJOR(29),從設備號則與注冊順序相關,依次為 0、1、2 等。每個被注冊的幀緩衝區設備在 /dev/graphics 目錄下都有一個對應的設備文件 fb<minor>,例如第一個設備對應 fb0。用戶空間的應用程序正是通過這個設備文件來操作幀緩衝區,把要顯示的畫面渲染上去。

一、kernel 啟動動畫

kernel 的啟動畫面在一般 Android 系統裡默認並不出現。在 kernel 的 config 裡有這麼兩項:

# CONFIG_FRAMEBUFFER_CONSOLE is not set
# CONFIG_LOGO is not set

第一項代表是否支持幀緩衝控制台,第二項代表是否顯示 logo。對應的編譯菜單分別位於:

Device Drivers → Graphics support → Console display driver support → Framebuffer Console support

Device Drivers → Graphics support → Bootup logo

kernel 中的動畫基本都在 kernel/drivers/video/fbmem.c 中實現。經過一系列初始化與准備後,最終會調用 kernel/drivers/video/logo.c 中的 fb_find_logo(...) 來保存 kernel 動畫的內容:

const struct linux_logo * __init_refok fb_find_logo(int depth) {
    const struct linux_logo *logo = NULL;
    if (nologo) return NULL;
    if (depth >= 1) {
#ifdef CONFIG_LOGO_LINUX_MONO
        logo = &logo_linux_mono;
#endif
        ...
    }
    if (depth >= 4) {
#ifdef CONFIG_LOGO_LINUX_VGA16
        logo = &logo_linux_vga16;
#endif
        ...
    }
    if (depth >= 8) {
#ifdef CONFIG_LOGO_LINUX_CLUT224
        logo = &logo_linux_clut224;
#endif
        ...
    }
    return logo;
}

這個函數會根據幀緩衝區的顏色深度 depth 以及不同的編譯選項,獲取對應 logo 內容的指針。這些內容結構體定義在 kernel/include/linux/linux_logo.h 中:

extern const struct linux_logo logo_linux_mono;
extern const struct linux_logo logo_linux_vga16;
extern const struct linux_logo logo_linux_clut224;
extern const struct linux_logo logo_blackfin_vga16;
extern const struct linux_logo logo_blackfin_clut224;
...

這些結構體變量保存了 kernel/drivers/video/logo/ 下的 *.ppm 與 *.pbm 文件內容。logo 指針保存動畫內容之後,接著就進入渲染環節,調用 fbmem.c 中的:

int fb_show_logo(struct fb_info *info, int rotate) {
    int y;
    y = fb_show_logo_line(info, rotate, fb_logo.logo, 0, num_online_cpus());
    y = fb_show_extra_logos(info, y, rotate);
    return y;
}

再往下調用:

static void fb_do_show_logo(struct fb_info *info, struct fb_image *image, int rotate, unsigned int num) {
    unsigned int x;
    if (rotate == FB_ROTATE_UR) {
        for (x = 0; x < num && image->dx + image->width <= info->var.xres; x++) {
            info->fbops->fb_imageblit(info, image);
            image->dx += image->width + 8;
        }
    } else if (rotate == FB_ROTATE_UD) {
        ...
    } else if (rotate == FB_ROTATE_CW) {
        ...
    } else if (rotate == FB_ROTATE_CCW) {
        ...
    }
}

其中:FB_ROTATE_UR 正常顯示、FB_ROTATE_UD 上下倒置、FB_ROTATE_CW 順時針旋轉 90 度、FB_ROTATE_CCW 逆時針旋轉 90 度。到這裡就開始調用幀緩衝區設備來渲染指定圖像。

二、init 進程啟動動畫

init 進程的啟動要從 /system/core/init/init.c 的 main 函數說起:

int main(int argc, char **argv) {
    ...
    if (!strcmp(basename(argv[0]), "ueventd")) return ueventd_main(argc, argv);
    if (!strcmp(basename(argv[0]), "watchdogd")) return watchdogd_main(argc, argv);
    ...
    queue_builtin_action(console_init_action, "console_init");
    ...
}

這裡會根據傳入的 argv[0] 判斷進程名。因為最先啟動的是 init 進程,之後會根據 init.rc 配置 ueventd 以及 watchdogd 等進程,而這些進程加載的執行文件也是從 init 開始、以這個 main 函數為入口,所以需要先做判別。

接著向 init 進程的 action 執行隊列添加了一個 console_init_action,最後依次執行隊列中的 action:

static int console_init_action(int nargs, char **args) {
    int fd;
    char tmp[PROP_VALUE_MAX];
    if (console[0]) {
        snprintf(tmp, sizeof(tmp), "/dev/%s", console);
        console_name = strdup(tmp);
    }
    fd = open(console_name, O_RDWR);
    if (fd >= 0) have_console = 1;
    close(fd);
    if (load_565rle_image(INIT_IMAGE_FILE)) {
        fd = open("/dev/tty0", O_WRONLY);
        if (fd >= 0) {
            const char *msg = " A N D R O I D ";
            write(fd, msg, strlen(msg));
            close(fd);
        }
    }
    return 0;
}

這裡先初始化控制台,通過 /dev/console 設備訪問控制台,若存在則把全局變量 have_console 置 1。然後通過 load_565rle_image(INIT_IMAGE_FILE) 加載顯示 init 動畫,其中 INIT_IMAGE_FILE 宏定義了動畫內容的位置(定義在 init.h 中):

#define INIT_IMAGE_FILE "/initlogo.rle"

具體實現在 /system/core/init/logo.c:

int load_565rle_image(char *fn) {
    struct FB fb;
    struct stat s;
    unsigned short *data, *bits, *ptr;
    unsigned count, max;
    int fd;
    if (vt_set_mode(1)) return -1;
    fd = open(fn, O_RDONLY);
    ...
    data = mmap(0, s.st_size, PROT_READ, MAP_SHARED, fd, 0);
    ...
    if (fb_open(&fb)) goto fail_unmap_data;
    max = fb_width(&fb) * fb_height(&fb);
    ptr = data;
    count = s.st_size;
    bits = fb.bits;
    while (count > 3) {
        unsigned n = ptr[0];
        if (n > max) break;
        android_memset16(bits, ptr[1], n << 1);
        bits += n;
        max -= n;
        ptr += 2;
        count -= 4;
    }
    munmap(data, s.st_size);
    fb_update(&fb);
    fb_close(&fb);
    close(fd);
    unlink(fn);
    return 0;
    ...
}

vt_set_mode 打開控制台設備 /dev/tty0,設置控制台顯示方式,傳入參數 1 時控制台以圖形方式顯示:

static int vt_set_mode(int graphics) {
    int fd, r;
    fd = open("/dev/tty0", O_RDWR | O_SYNC);
    if (fd < 0) return -1;
    r = ioctl(fd, KDSETMODE, (void*) (graphics ? KD_GRAPHICS : KD_TEXT));
    close(fd);
    return r;
}

隨後打開傳入的動畫文件,用 fstat 計算大小,通過 mmap 把 initlogo.rle 映射到 init 進程地址空間;再打開 /dev/graphics/fb0 訪問幀緩衝區設備,獲取固定與可變信息並映射進來,算出屏幕寬高與可寫入大小,最後通過一個 while 循環把內容寫入幀緩衝區。更新畫面的 fb_update 通過 ioctl 設置 yoffset 完成:

static void fb_update(struct FB *fb) {
    fb->vi.yoffset = 1;
    ioctl(fb->fd, FBIOPUT_VSCREENINFO, &fb->vi);
    fb->vi.yoffset = 0;
    ioctl(fb->fd, FBIOPUT_VSCREENINFO, &fb->vi);
}

三、系統服務啟動動畫

這是 Android 最常見的一段開機動畫,由 bootanimation 負責顯示運行,在 init.rc 裡作為一個 service:

1. init.rc 配置

service bootanim /system/bin/bootanimation
    class main
    user graphics
    group graphics
    disabled
    oneshot

這裡配置了 disabled,因此 init 啟動解析時不會主動啟動它。

2. SurfaceFlinger 服務的啟動

在 system server 啟動系統所需服務時,system_init.cpp 啟動視頻服務會啟動一個 SurfaceFlinger 服務並獲取實例。SurfaceFlinger 繼承於 BinderService 模板類,其 instantiate() 函數負責構造服務對象並注冊到 ServiceManager 進程:

static void instantiate() {
    publish();
}
static status_t publish(bool allowIsolated = false) {
    sp<IServiceManager> sm(defaultServiceManager());
    return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
}

由於 SurfaceFlinger 又繼承於 RefBase 類並重寫了 onFirstRef(),對象第一次創建時會自動調用 onFirstRef():

void SurfaceFlinger::onFirstRef() {
    mEventQueue.init(this);
    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
    mReadyToRunBarrier.wait();
}

這裡從父類 Thread 創建了一個新線程,加入 threadLoop 函數並調用 readyToRun():

status_t SurfaceFlinger::readyToRun() {
    ...
    DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
    initializeGL(mEGLDisplay);
    mEventThread = new EventThread(this);
    mEventQueue.setEventThread(mEventThread);
    // start boot animation
    startBootAnim();
    return NO_ERROR;
}

3. 在 SurfaceFlinger 中開啟 bootanimation 服務

void SurfaceFlinger::startBootAnim() {
    property_set("service.bootanim.exit", "0");
    property_set("ctl.start", "bootanim");
}

把系統屬性 ctl.start 設為 bootanim,於是啟動了一個新的服務進程 bootanim,入口為 /frameworks/base/cmds/bootanimation/bootanimation_main.cpp:

int main(int argc, char** argv) {
    char value[PROPERTY_VALUE_MAX];
    property_get("debug.sf.nobootanimation", value, "0");
    int noBootAnimation = atoi(value);
    if (!noBootAnimation) {
        sp<ProcessState> proc(ProcessState::self());
        ProcessState::self()->startThreadPool();
        sp<BootAnimation> boot = new BootAnimation();
        IPCThreadState::self()->joinThreadPool();
    }
    return 0;
}

程序讀取 nobootanimation 屬性,若為 0 則啟動 Binder 線程池並創建 BootAnimation 對象。由於 BootAnimation 在顯示動畫時需要與 SurfaceFlinger 通信,所以必須啟動 Binder 線程池。BootAnimation 間接繼承 RefBase 並重寫 onFirstRef:

void BootAnimation::onFirstRef() {
    status_t err = mSession->linkToComposerDeath(this);
    if (err == NO_ERROR) {
        run("BootAnimation", PRIORITY_DISPLAY);
    }
}

構造函數中創建了用於與 SurfaceFlinger 進行 Binder 通信的 SurfaceComposerClient:

BootAnimation::BootAnimation() : Thread(false) { mSession = new SurfaceComposerClient(); }

4. bootanimation 線程構建

BootAnimation 繼承 Thread,當 onFirstRef 調用父類 run 後系統會創建線程,線程首次運行前調用 readyToRun 做初始化,之後調用 threadLoop 顯示動畫:

status_t BootAnimation::readyToRun() {
    mAssets.addDefaultAssets();
    ...
    char decrypt[PROPERTY_VALUE_MAX];
    property_get("vold.decrypt", decrypt, "");
    bool encryptedAnimation = atoi(decrypt) != 0 || !strcmp("trigger_restart_min_framework", decrypt);
    if (... ) {
        mAndroidAnimation = false;
    }
    return NO_ERROR;
}

這裡判斷是否為 Android 默認動畫,涉及的文件路徑定義如下:

#define USER_BOOTANIMATION_FILE "/data/local/bootanimation.zip"

#define SYSTEM_BOOTANIMATION_FILE "/system/media/bootanimation.zip"

#define SYSTEM_ENCRYPTED_BOOTANIMATION_FILE "/system/media/bootanimation-encrypted.zip"

上面這些文件只要有任意一個存在,就代表不是 Android 默認動畫,而是用戶自定義的開機動畫。

5. bootanimation 執行動畫

bool BootAnimation::threadLoop() {
    bool r;
    if (mAndroidAnimation) {
        r = android();
    } else {
        r = movie();
    }
    eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    ...
    return r;
}

如果是默認動畫,會調用 android():

bool BootAnimation::android() {
    initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
    initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
    ...
}

這兩張圖保存在 frameworks/base/core/res/assets/images 目錄。android-logo-mask.png 作為動畫前景,是一個镂空的「ANDROID」圖像;android-logo-shine.png 作為背景,中間有一條 45 度角的高亮條紋。每次循環中,背景圖被劃分為左右兩部分,寬度隨時間此消彼長,營造出條紋移動的錯覺;由於前景镂空,我們便能透過它看到背後條紋一閃一閃劃過。

如果是用戶自定義動畫,則調用 movie(),解析 bootanimation.zip 中的 desc.txt:

bool BootAnimation::movie() {
    ZipFileRO& zip(mZip);
    ...
    ZipEntryRO desc = zip.findEntryByName("desc.txt");
    FileMap* descMap = zip.createEntryFileMap(desc);
    ...
    // 解析描述文件
    for (;;) {
        ...
        if (sscanf(l, "%d %d %d", &width, &height, &fps) == 3) {
            animation.width = width;
            animation.height = height;
            animation.fps = fps;
        } else if (sscanf(l, " %c %d %d %s", &pathType, &count, &pause, path) == 4) {
            Animation::Part part;
            part.playUntilComplete = pathType == 'c';
            part.count = count;
            part.pause = pause;
            part.path = path;
            animation.parts.add(part);
        }
        s = ++endl;
    }
    ...
}

desc.txt 描述了動畫的分辨率與幀率,例如:

1920 1080 24

p 1 0 part1

p 0 10 part2

第一行的三個數字分別表示顯示寬度、高度和幀速(fps)。其餘每行描述一個動畫片斷,必須以字符「p」開頭,後面跟兩個數字和一個文件目錄路徑。第一個數字表示循環次數(0 代表無限循環),第二個數字表示兩次循環之間的時間間隔(以幀為單位),目錄下保存一系列 png 圖片依次顯示。以本例而言,動畫大小為 1920×1080,速度 24 幀每秒,包含 part1(只顯示一次)和 part2(無限循環,間隔 10×(1/24) 秒)兩個片斷。

6. bootanimation 停止

當 Android 啟動到 Launcher、第一個應用主線程空閒時,Activity 會向 ActivityManagerService 發送空閒通知,最終走到:

public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
    ...
    ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
    ...
}

並在 activityIdleInternal 中標記 mBooted 並調用 enableScreenAfterBoot(),再通過 WindowManagerService 的 performEnableScreen() 通過 Binder 通知 SurfaceFlinger:

public void performEnableScreen() {
    synchronized (mWindowMap) {
        ...
        IBinder surfaceFlinger = ServiceManager.getService("SurfaceFlinger");
        if (surfaceFlinger != null) {
            Parcel data = Parcel.obtain();
            data.writeInterfaceToken("android.ui.ISurfaceComposer");
            surfaceFlinger.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
            data.recycle();
        }
        ...
    }
}

SurfaceFlinger 收到後設置系統屬性,通知 init 守護進程停掉 bootanimation 服務,動畫隨之停止:

void SurfaceFlinger::bootFinished() {
    ...
    property_set("service.bootanim.exit", "1");
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved