BootAnimation.cpp revision 2978751310b4efef1faa87b116fcaee9423c007f
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "BootAnimation"
18
19#include <stdint.h>
20#include <sys/types.h>
21#include <math.h>
22#include <fcntl.h>
23#include <utils/misc.h>
24#include <signal.h>
25
26#include <binder/IPCThreadState.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/Log.h>
31#include <utils/AssetManager.h>
32
33#include <ui/PixelFormat.h>
34#include <ui/Rect.h>
35#include <ui/Region.h>
36#include <ui/DisplayInfo.h>
37#include <ui/FramebufferNativeWindow.h>
38#include <ui/EGLUtils.h>
39
40#include <surfaceflinger/ISurfaceComposer.h>
41#include <surfaceflinger/ISurfaceFlingerClient.h>
42
43#include <core/SkBitmap.h>
44#include <images/SkImageDecoder.h>
45
46#include <GLES/gl.h>
47#include <GLES/glext.h>
48#include <EGL/eglext.h>
49
50#include "BootAnimation.h"
51
52#define USER_BOOTANIMATION_FILE "/data/local/bootanimation.zip"
53#define SYSTEM_BOOTANIMATION_FILE "/system/media/bootanimation.zip"
54
55namespace android {
56
57// ---------------------------------------------------------------------------
58
59BootAnimation::BootAnimation() : Thread(false)
60{
61    mSession = new SurfaceComposerClient();
62}
63
64BootAnimation::~BootAnimation() {
65}
66
67void BootAnimation::onFirstRef() {
68    status_t err = mSession->linkToComposerDeath(this);
69    LOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
70    if (err == NO_ERROR) {
71        run("BootAnimation", PRIORITY_DISPLAY);
72    }
73}
74
75sp<SurfaceComposerClient> BootAnimation::session() const {
76    return mSession;
77}
78
79
80void BootAnimation::binderDied(const wp<IBinder>& who)
81{
82    // woah, surfaceflinger died!
83    LOGD("SurfaceFlinger died, exiting...");
84
85    // calling requestExit() is not enough here because the Surface code
86    // might be blocked on a condition variable that will never be updated.
87    kill( getpid(), SIGKILL );
88    requestExit();
89}
90
91status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
92        const char* name) {
93    Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
94    if (!asset)
95        return NO_INIT;
96    SkBitmap bitmap;
97    SkImageDecoder::DecodeMemory(asset->getBuffer(false), asset->getLength(),
98            &bitmap, SkBitmap::kNo_Config, SkImageDecoder::kDecodePixels_Mode);
99    asset->close();
100    delete asset;
101
102    // ensure we can call getPixels(). No need to call unlock, since the
103    // bitmap will go out of scope when we return from this method.
104    bitmap.lockPixels();
105
106    const int w = bitmap.width();
107    const int h = bitmap.height();
108    const void* p = bitmap.getPixels();
109
110    GLint crop[4] = { 0, h, w, -h };
111    texture->w = w;
112    texture->h = h;
113
114    glGenTextures(1, &texture->name);
115    glBindTexture(GL_TEXTURE_2D, texture->name);
116
117    switch (bitmap.getConfig()) {
118        case SkBitmap::kA8_Config:
119            glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
120                    GL_UNSIGNED_BYTE, p);
121            break;
122        case SkBitmap::kARGB_4444_Config:
123            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
124                    GL_UNSIGNED_SHORT_4_4_4_4, p);
125            break;
126        case SkBitmap::kARGB_8888_Config:
127            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
128                    GL_UNSIGNED_BYTE, p);
129            break;
130        case SkBitmap::kRGB_565_Config:
131            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
132                    GL_UNSIGNED_SHORT_5_6_5, p);
133            break;
134        default:
135            break;
136    }
137
138    glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
139    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
140    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
141    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
142    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
143    return NO_ERROR;
144}
145
146status_t BootAnimation::initTexture(void* buffer, size_t len)
147{
148    //StopWatch watch("blah");
149
150    SkBitmap bitmap;
151    SkImageDecoder::DecodeMemory(buffer, len,
152            &bitmap, SkBitmap::kRGB_565_Config,
153            SkImageDecoder::kDecodePixels_Mode);
154
155    // ensure we can call getPixels(). No need to call unlock, since the
156    // bitmap will go out of scope when we return from this method.
157    bitmap.lockPixels();
158
159    const int w = bitmap.width();
160    const int h = bitmap.height();
161    const void* p = bitmap.getPixels();
162
163    GLint crop[4] = { 0, h, w, -h };
164    int tw = 1 << (31 - __builtin_clz(w));
165    int th = 1 << (31 - __builtin_clz(h));
166    if (tw < w) tw <<= 1;
167    if (th < h) th <<= 1;
168
169    switch (bitmap.getConfig()) {
170        case SkBitmap::kARGB_8888_Config:
171            if (tw != w || th != h) {
172                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
173                        GL_UNSIGNED_BYTE, 0);
174                glTexSubImage2D(GL_TEXTURE_2D, 0,
175                        0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
176            } else {
177                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
178                        GL_UNSIGNED_BYTE, p);
179            }
180            break;
181
182        case SkBitmap::kRGB_565_Config:
183            if (tw != w || th != h) {
184                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
185                        GL_UNSIGNED_SHORT_5_6_5, 0);
186                glTexSubImage2D(GL_TEXTURE_2D, 0,
187                        0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p);
188            } else {
189                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
190                        GL_UNSIGNED_SHORT_5_6_5, p);
191            }
192            break;
193        default:
194            break;
195    }
196
197    glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
198
199    return NO_ERROR;
200}
201
202status_t BootAnimation::readyToRun() {
203    mAssets.addDefaultAssets();
204
205    DisplayInfo dinfo;
206    status_t status = session()->getDisplayInfo(0, &dinfo);
207    if (status)
208        return -1;
209
210    // create the native surface
211    sp<SurfaceControl> control = session()->createSurface(
212            getpid(), 0, dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565);
213    session()->openTransaction();
214    control->setLayer(0x40000000);
215    session()->closeTransaction();
216
217    sp<Surface> s = control->getSurface();
218
219    // initialize opengl and egl
220    const EGLint attribs[] = {
221            EGL_DEPTH_SIZE, 0,
222            EGL_NONE
223    };
224    EGLint w, h, dummy;
225    EGLint numConfigs;
226    EGLConfig config;
227    EGLSurface surface;
228    EGLContext context;
229
230    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
231
232    eglInitialize(display, 0, 0);
233    EGLUtils::selectConfigForNativeWindow(display, attribs, s.get(), &config);
234    surface = eglCreateWindowSurface(display, config, s.get(), NULL);
235    context = eglCreateContext(display, config, NULL, NULL);
236    eglQuerySurface(display, surface, EGL_WIDTH, &w);
237    eglQuerySurface(display, surface, EGL_HEIGHT, &h);
238
239    if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
240        return NO_INIT;
241
242    mDisplay = display;
243    mContext = context;
244    mSurface = surface;
245    mWidth = w;
246    mHeight = h;
247    mFlingerSurfaceControl = control;
248    mFlingerSurface = s;
249
250    mAndroidAnimation = true;
251    if ((access(USER_BOOTANIMATION_FILE, R_OK) == 0) &&
252            (mZip.open(USER_BOOTANIMATION_FILE) == NO_ERROR) ||
253            (access(SYSTEM_BOOTANIMATION_FILE, R_OK) == 0) &&
254            (mZip.open(SYSTEM_BOOTANIMATION_FILE) == NO_ERROR))
255        mAndroidAnimation = false;
256
257    return NO_ERROR;
258}
259
260bool BootAnimation::threadLoop()
261{
262    bool r;
263    if (mAndroidAnimation) {
264        r = android();
265    } else {
266        r = movie();
267    }
268
269    eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
270    eglDestroyContext(mDisplay, mContext);
271    eglDestroySurface(mDisplay, mSurface);
272    mFlingerSurface.clear();
273    mFlingerSurfaceControl.clear();
274    eglTerminate(mDisplay);
275    IPCThreadState::self()->stopProcess();
276    return r;
277}
278
279bool BootAnimation::android()
280{
281    initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
282    initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
283
284    // clear screen
285    glShadeModel(GL_FLAT);
286    glDisable(GL_DITHER);
287    glDisable(GL_SCISSOR_TEST);
288    glClear(GL_COLOR_BUFFER_BIT);
289    eglSwapBuffers(mDisplay, mSurface);
290
291    glEnable(GL_TEXTURE_2D);
292    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
293
294    const GLint xc = (mWidth  - mAndroid[0].w) / 2;
295    const GLint yc = (mHeight - mAndroid[0].h) / 2;
296    const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
297
298    // draw and update only what we need
299    mFlingerSurface->setSwapRectangle(updateRect);
300
301    glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
302            updateRect.height());
303
304    // Blend state
305    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
306    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
307
308    const nsecs_t startTime = systemTime();
309    do {
310        nsecs_t now = systemTime();
311        double time = now - startTime;
312        float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
313        GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
314        GLint x = xc - offset;
315
316        glDisable(GL_SCISSOR_TEST);
317        glClear(GL_COLOR_BUFFER_BIT);
318
319        glEnable(GL_SCISSOR_TEST);
320        glDisable(GL_BLEND);
321        glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
322        glDrawTexiOES(x,                 yc, 0, mAndroid[1].w, mAndroid[1].h);
323        glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);
324
325        glEnable(GL_BLEND);
326        glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
327        glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);
328
329        EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
330        if (res == EGL_FALSE)
331            break;
332
333        // 12fps: don't animate too fast to preserve CPU
334        const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
335        if (sleepTime > 0)
336            usleep(sleepTime);
337    } while (!exitPending());
338
339    glDeleteTextures(1, &mAndroid[0].name);
340    glDeleteTextures(1, &mAndroid[1].name);
341    return false;
342}
343
344
345bool BootAnimation::movie()
346{
347    ZipFileRO& zip(mZip);
348
349    size_t numEntries = zip.getNumEntries();
350    ZipEntryRO desc = zip.findEntryByName("desc.txt");
351    FileMap* descMap = zip.createEntryFileMap(desc);
352    LOGE_IF(!descMap, "descMap is null");
353    if (!descMap) {
354        return false;
355    }
356
357    String8 desString((char const*)descMap->getDataPtr(),
358            descMap->getDataLength());
359    char const* s = desString.string();
360
361    Animation animation;
362
363    // Parse the description file
364    for (;;) {
365        const char* endl = strstr(s, "\n");
366        if (!endl) break;
367        String8 line(s, endl - s);
368        const char* l = line.string();
369        int fps, width, height, count, pause;
370        char path[256];
371        if (sscanf(l, "%d %d %d", &width, &height, &fps) == 3) {
372            //LOGD("> w=%d, h=%d, fps=%d", fps, width, height);
373            animation.width = width;
374            animation.height = height;
375            animation.fps = fps;
376        }
377        if (sscanf(l, "p %d %d %s", &count, &pause, path) == 3) {
378            //LOGD("> count=%d, pause=%d, path=%s", count, pause, path);
379            Animation::Part part;
380            part.count = count;
381            part.pause = pause;
382            part.path = path;
383            animation.parts.add(part);
384        }
385        s = ++endl;
386    }
387
388    // read all the data structures
389    const size_t pcount = animation.parts.size();
390    for (size_t i=0 ; i<numEntries ; i++) {
391        char name[256];
392        ZipEntryRO entry = zip.findEntryByIndex(i);
393        if (zip.getEntryFileName(entry, name, 256) == 0) {
394            const String8 entryName(name);
395            const String8 path(entryName.getPathDir());
396            const String8 leaf(entryName.getPathLeaf());
397            if (leaf.size() > 0) {
398                for (int j=0 ; j<pcount ; j++) {
399                    if (path == animation.parts[j].path) {
400                        int method;
401                        // supports only stored png files
402                        if (zip.getEntryInfo(entry, &method, 0, 0, 0, 0, 0)) {
403                            if (method == ZipFileRO::kCompressStored) {
404                                FileMap* map = zip.createEntryFileMap(entry);
405                                if (map) {
406                                    Animation::Frame frame;
407                                    frame.name = leaf;
408                                    frame.map = map;
409                                    Animation::Part& part(animation.parts.editItemAt(j));
410                                    part.frames.add(frame);
411                                }
412                            }
413                        }
414                    }
415                }
416            }
417        }
418    }
419
420    // clear screen
421    glShadeModel(GL_FLAT);
422    glDisable(GL_DITHER);
423    glDisable(GL_SCISSOR_TEST);
424    glDisable(GL_BLEND);
425    glClear(GL_COLOR_BUFFER_BIT);
426
427    eglSwapBuffers(mDisplay, mSurface);
428
429    glBindTexture(GL_TEXTURE_2D, 0);
430    glEnable(GL_TEXTURE_2D);
431    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
432    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
433    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
434    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
435    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
436
437    const int xc = (mWidth - animation.width) / 2;
438    const int yc = ((mHeight - animation.height) / 2);
439    nsecs_t lastFrame = systemTime();
440    nsecs_t frameDuration = s2ns(1) / animation.fps;
441
442    Region clearReg(Rect(mWidth, mHeight));
443    clearReg.subtractSelf(Rect(xc, yc, xc+animation.width, yc+animation.height));
444
445    for (int i=0 ; i<pcount && !exitPending() ; i++) {
446        const Animation::Part& part(animation.parts[i]);
447        const size_t fcount = part.frames.size();
448        glBindTexture(GL_TEXTURE_2D, 0);
449
450        for (int r=0 ; !part.count || r<part.count ; r++) {
451            for (int j=0 ; j<fcount && !exitPending(); j++) {
452                const Animation::Frame& frame(part.frames[j]);
453
454                if (r > 0) {
455                    glBindTexture(GL_TEXTURE_2D, frame.tid);
456                } else {
457                    if (part.count != 1) {
458                        glGenTextures(1, &frame.tid);
459                        glBindTexture(GL_TEXTURE_2D, frame.tid);
460                        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
461                        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
462                    }
463                    initTexture(
464                            frame.map->getDataPtr(),
465                            frame.map->getDataLength());
466                }
467
468                if (!clearReg.isEmpty()) {
469                    Region::const_iterator head(clearReg.begin());
470                    Region::const_iterator tail(clearReg.end());
471                    glEnable(GL_SCISSOR_TEST);
472                    while (head != tail) {
473                        const Rect& r(*head++);
474                        glScissor(r.left, mHeight - r.bottom,
475                                r.width(), r.height());
476                        glClear(GL_COLOR_BUFFER_BIT);
477                    }
478                    glDisable(GL_SCISSOR_TEST);
479                }
480                glDrawTexiOES(xc, yc, 0, animation.width, animation.height);
481                eglSwapBuffers(mDisplay, mSurface);
482
483                nsecs_t now = systemTime();
484                nsecs_t delay = frameDuration - (now - lastFrame);
485                lastFrame = now;
486                long wait = ns2us(frameDuration);
487                if (wait > 0)
488                    usleep(wait);
489            }
490            usleep(part.pause * ns2us(frameDuration));
491        }
492
493        // free the textures for this part
494        if (part.count != 1) {
495            for (int j=0 ; j<fcount ; j++) {
496                const Animation::Frame& frame(part.frames[j]);
497                glDeleteTextures(1, &frame.tid);
498            }
499        }
500    }
501
502    return false;
503}
504
505// ---------------------------------------------------------------------------
506
507}
508; // namespace android
509