BootAnimation.cpp revision 9d7d4da6b719594a89b4b8b17546f6601b617f33
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 <cutils/properties.h>
27
28#include <androidfw/AssetManager.h>
29#include <binder/IPCThreadState.h>
30#include <utils/Atomic.h>
31#include <utils/Errors.h>
32#include <utils/Log.h>
33#include <utils/threads.h>
34
35#include <ui/PixelFormat.h>
36#include <ui/Rect.h>
37#include <ui/Region.h>
38#include <ui/DisplayInfo.h>
39#include <ui/FramebufferNativeWindow.h>
40
41#include <gui/ISurfaceComposer.h>
42#include <gui/Surface.h>
43#include <gui/SurfaceComposerClient.h>
44
45#include <core/SkBitmap.h>
46#include <core/SkStream.h>
47#include <core/SkImageDecoder.h>
48
49#include <GLES/gl.h>
50#include <GLES/glext.h>
51#include <EGL/eglext.h>
52
53#include "BootAnimation.h"
54
55#define SYSTEM_BOOTANIMATION_FILE "/system/media/bootanimation.zip"
56#define SYSTEM_ENCRYPTED_BOOTANIMATION_FILE "/system/media/bootanimation-encrypted.zip"
57#define EXIT_PROP_NAME "service.bootanim.exit"
58
59extern "C" int clock_nanosleep(clockid_t clock_id, int flags,
60                           const struct timespec *request,
61                           struct timespec *remain);
62
63namespace android {
64
65static const int ANIM_ENTRY_NAME_MAX = 256;
66
67// ---------------------------------------------------------------------------
68
69BootAnimation::BootAnimation() : Thread(false), mZip(NULL)
70{
71    mSession = new SurfaceComposerClient();
72}
73
74BootAnimation::~BootAnimation() {
75    if (mZip != NULL) {
76        delete mZip;
77    }
78}
79
80void BootAnimation::onFirstRef() {
81    status_t err = mSession->linkToComposerDeath(this);
82    ALOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
83    if (err == NO_ERROR) {
84        run("BootAnimation", PRIORITY_DISPLAY);
85    }
86}
87
88sp<SurfaceComposerClient> BootAnimation::session() const {
89    return mSession;
90}
91
92
93void BootAnimation::binderDied(const wp<IBinder>&)
94{
95    // woah, surfaceflinger died!
96    ALOGD("SurfaceFlinger died, exiting...");
97
98    // calling requestExit() is not enough here because the Surface code
99    // might be blocked on a condition variable that will never be updated.
100    kill( getpid(), SIGKILL );
101    requestExit();
102}
103
104status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
105        const char* name) {
106    Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
107    if (!asset)
108        return NO_INIT;
109    SkBitmap bitmap;
110    SkImageDecoder::DecodeMemory(asset->getBuffer(false), asset->getLength(),
111            &bitmap, SkBitmap::kNo_Config, SkImageDecoder::kDecodePixels_Mode);
112    asset->close();
113    delete asset;
114
115    // ensure we can call getPixels(). No need to call unlock, since the
116    // bitmap will go out of scope when we return from this method.
117    bitmap.lockPixels();
118
119    const int w = bitmap.width();
120    const int h = bitmap.height();
121    const void* p = bitmap.getPixels();
122
123    GLint crop[4] = { 0, h, w, -h };
124    texture->w = w;
125    texture->h = h;
126
127    glGenTextures(1, &texture->name);
128    glBindTexture(GL_TEXTURE_2D, texture->name);
129
130    switch (bitmap.config()) {
131        case SkBitmap::kA8_Config:
132            glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
133                    GL_UNSIGNED_BYTE, p);
134            break;
135        case SkBitmap::kARGB_4444_Config:
136            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
137                    GL_UNSIGNED_SHORT_4_4_4_4, p);
138            break;
139        case SkBitmap::kARGB_8888_Config:
140            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
141                    GL_UNSIGNED_BYTE, p);
142            break;
143        case SkBitmap::kRGB_565_Config:
144            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
145                    GL_UNSIGNED_SHORT_5_6_5, p);
146            break;
147        default:
148            break;
149    }
150
151    glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
152    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
153    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
154    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
155    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
156    return NO_ERROR;
157}
158
159status_t BootAnimation::initTexture(void* buffer, size_t len)
160{
161    //StopWatch watch("blah");
162
163    SkBitmap bitmap;
164    SkMemoryStream  stream(buffer, len);
165    SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
166    if (codec) {
167        codec->setDitherImage(false);
168        codec->decode(&stream, &bitmap,
169                SkBitmap::kARGB_8888_Config,
170                SkImageDecoder::kDecodePixels_Mode);
171        delete codec;
172    }
173
174    // ensure we can call getPixels(). No need to call unlock, since the
175    // bitmap will go out of scope when we return from this method.
176    bitmap.lockPixels();
177
178    const int w = bitmap.width();
179    const int h = bitmap.height();
180    const void* p = bitmap.getPixels();
181
182    GLint crop[4] = { 0, h, w, -h };
183    int tw = 1 << (31 - __builtin_clz(w));
184    int th = 1 << (31 - __builtin_clz(h));
185    if (tw < w) tw <<= 1;
186    if (th < h) th <<= 1;
187
188    switch (bitmap.config()) {
189        case SkBitmap::kARGB_8888_Config:
190            if (tw != w || th != h) {
191                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
192                        GL_UNSIGNED_BYTE, 0);
193                glTexSubImage2D(GL_TEXTURE_2D, 0,
194                        0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
195            } else {
196                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
197                        GL_UNSIGNED_BYTE, p);
198            }
199            break;
200
201        case SkBitmap::kRGB_565_Config:
202            if (tw != w || th != h) {
203                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
204                        GL_UNSIGNED_SHORT_5_6_5, 0);
205                glTexSubImage2D(GL_TEXTURE_2D, 0,
206                        0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p);
207            } else {
208                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
209                        GL_UNSIGNED_SHORT_5_6_5, p);
210            }
211            break;
212        default:
213            break;
214    }
215
216    glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
217
218    return NO_ERROR;
219}
220
221status_t BootAnimation::readyToRun() {
222    mAssets.addDefaultAssets();
223
224    sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
225            ISurfaceComposer::eDisplayIdMain));
226    DisplayInfo dinfo;
227    status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &dinfo);
228    if (status)
229        return -1;
230
231    // create the native surface
232    sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
233            dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565);
234
235    SurfaceComposerClient::openGlobalTransaction();
236    control->setLayer(0x40000000);
237    SurfaceComposerClient::closeGlobalTransaction();
238
239    sp<Surface> s = control->getSurface();
240
241    // initialize opengl and egl
242    const EGLint attribs[] = {
243            EGL_RED_SIZE,   8,
244            EGL_GREEN_SIZE, 8,
245            EGL_BLUE_SIZE,  8,
246            EGL_DEPTH_SIZE, 0,
247            EGL_NONE
248    };
249    EGLint w, h, dummy;
250    EGLint numConfigs;
251    EGLConfig config;
252    EGLSurface surface;
253    EGLContext context;
254
255    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
256
257    eglInitialize(display, 0, 0);
258    eglChooseConfig(display, attribs, &config, 1, &numConfigs);
259    surface = eglCreateWindowSurface(display, config, s.get(), NULL);
260    context = eglCreateContext(display, config, NULL, NULL);
261    eglQuerySurface(display, surface, EGL_WIDTH, &w);
262    eglQuerySurface(display, surface, EGL_HEIGHT, &h);
263
264    if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
265        return NO_INIT;
266
267    mDisplay = display;
268    mContext = context;
269    mSurface = surface;
270    mWidth = w;
271    mHeight = h;
272    mFlingerSurfaceControl = control;
273    mFlingerSurface = s;
274
275    // If the device has encryption turned on or is in process
276    // of being encrypted we show the encrypted boot animation.
277    char decrypt[PROPERTY_VALUE_MAX];
278    property_get("vold.decrypt", decrypt, "");
279
280    bool encryptedAnimation = atoi(decrypt) != 0 || !strcmp("trigger_restart_min_framework", decrypt);
281
282    ZipFileRO* zipFile = NULL;
283    if ((encryptedAnimation &&
284            (access(SYSTEM_ENCRYPTED_BOOTANIMATION_FILE, R_OK) == 0) &&
285            ((zipFile = ZipFileRO::open(SYSTEM_ENCRYPTED_BOOTANIMATION_FILE)) != NULL)) ||
286
287            ((access(SYSTEM_BOOTANIMATION_FILE, R_OK) == 0) &&
288            ((zipFile = ZipFileRO::open(SYSTEM_BOOTANIMATION_FILE)) != NULL))) {
289        mZip = zipFile;
290    }
291
292    return NO_ERROR;
293}
294
295bool BootAnimation::threadLoop()
296{
297    bool r;
298    // We have no bootanimation file, so we use the stock android logo
299    // animation.
300    if (mZip == NULL) {
301        r = android();
302    } else {
303        r = movie();
304    }
305
306    eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
307    eglDestroyContext(mDisplay, mContext);
308    eglDestroySurface(mDisplay, mSurface);
309    mFlingerSurface.clear();
310    mFlingerSurfaceControl.clear();
311    eglTerminate(mDisplay);
312    IPCThreadState::self()->stopProcess();
313    return r;
314}
315
316bool BootAnimation::android()
317{
318    initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
319    initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
320
321    // clear screen
322    glShadeModel(GL_FLAT);
323    glDisable(GL_DITHER);
324    glDisable(GL_SCISSOR_TEST);
325    glClearColor(0,0,0,1);
326    glClear(GL_COLOR_BUFFER_BIT);
327    eglSwapBuffers(mDisplay, mSurface);
328
329    glEnable(GL_TEXTURE_2D);
330    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
331
332    const GLint xc = (mWidth  - mAndroid[0].w) / 2;
333    const GLint yc = (mHeight - mAndroid[0].h) / 2;
334    const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
335
336    glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
337            updateRect.height());
338
339    // Blend state
340    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
341    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
342
343    const nsecs_t startTime = systemTime();
344    do {
345        nsecs_t now = systemTime();
346        double time = now - startTime;
347        float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
348        GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
349        GLint x = xc - offset;
350
351        glDisable(GL_SCISSOR_TEST);
352        glClear(GL_COLOR_BUFFER_BIT);
353
354        glEnable(GL_SCISSOR_TEST);
355        glDisable(GL_BLEND);
356        glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
357        glDrawTexiOES(x,                 yc, 0, mAndroid[1].w, mAndroid[1].h);
358        glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);
359
360        glEnable(GL_BLEND);
361        glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
362        glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);
363
364        EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
365        if (res == EGL_FALSE)
366            break;
367
368        // 12fps: don't animate too fast to preserve CPU
369        const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
370        if (sleepTime > 0)
371            usleep(sleepTime);
372
373        checkExit();
374    } while (!exitPending());
375
376    glDeleteTextures(1, &mAndroid[0].name);
377    glDeleteTextures(1, &mAndroid[1].name);
378    return false;
379}
380
381
382void BootAnimation::checkExit() {
383    // Allow surface flinger to gracefully request shutdown
384    char value[PROPERTY_VALUE_MAX];
385    property_get(EXIT_PROP_NAME, value, "0");
386    int exitnow = atoi(value);
387    if (exitnow) {
388        requestExit();
389    }
390}
391
392bool BootAnimation::movie()
393{
394    ZipEntryRO desc = mZip->findEntryByName("desc.txt");
395    ALOGE_IF(!desc, "couldn't find desc.txt");
396    if (!desc) {
397        return false;
398    }
399
400    FileMap* descMap = mZip->createEntryFileMap(desc);
401    mZip->releaseEntry(desc);
402    ALOGE_IF(!descMap, "descMap is null");
403    if (!descMap) {
404        return false;
405    }
406
407    String8 desString((char const*)descMap->getDataPtr(),
408            descMap->getDataLength());
409    char const* s = desString.string();
410
411    Animation animation;
412
413    // Parse the description file
414    for (;;) {
415        const char* endl = strstr(s, "\n");
416        if (!endl) break;
417        String8 line(s, endl - s);
418        const char* l = line.string();
419        int fps, width, height, count, pause;
420        char path[ANIM_ENTRY_NAME_MAX];
421        char pathType;
422        if (sscanf(l, "%d %d %d", &width, &height, &fps) == 3) {
423            //LOGD("> w=%d, h=%d, fps=%d", width, height, fps);
424            animation.width = width;
425            animation.height = height;
426            animation.fps = fps;
427        }
428        else if (sscanf(l, " %c %d %d %s", &pathType, &count, &pause, path) == 4) {
429            //LOGD("> type=%c, count=%d, pause=%d, path=%s", pathType, count, pause, path);
430            Animation::Part part;
431            part.playUntilComplete = pathType == 'c';
432            part.count = count;
433            part.pause = pause;
434            part.path = path;
435            animation.parts.add(part);
436        }
437
438        s = ++endl;
439    }
440
441    // read all the data structures
442    const size_t pcount = animation.parts.size();
443    void *cookie = NULL;
444    if (!mZip->startIteration(&cookie)) {
445        return false;
446    }
447
448    ZipEntryRO entry;
449    char name[ANIM_ENTRY_NAME_MAX];
450    while ((entry = mZip->nextEntry(cookie)) != NULL) {
451        const int foundEntryName = mZip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
452        if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
453            ALOGE("Error fetching entry file name");
454            continue;
455        }
456
457        const String8 entryName(name);
458        const String8 path(entryName.getPathDir());
459        const String8 leaf(entryName.getPathLeaf());
460        if (leaf.size() > 0) {
461            for (size_t j=0 ; j<pcount ; j++) {
462                if (path == animation.parts[j].path) {
463                    int method;
464                    // supports only stored png files
465                    if (mZip->getEntryInfo(entry, &method, NULL, NULL, NULL, NULL, NULL)) {
466                        if (method == ZipFileRO::kCompressStored) {
467                            FileMap* map = mZip->createEntryFileMap(entry);
468                            if (map) {
469                                Animation::Frame frame;
470                                frame.name = leaf;
471                                frame.map = map;
472                                Animation::Part& part(animation.parts.editItemAt(j));
473                                part.frames.add(frame);
474                            }
475                        }
476                    }
477                }
478            }
479        }
480    }
481
482    mZip->endIteration(cookie);
483
484    // clear screen
485    glShadeModel(GL_FLAT);
486    glDisable(GL_DITHER);
487    glDisable(GL_SCISSOR_TEST);
488    glDisable(GL_BLEND);
489    glClearColor(0,0,0,1);
490    glClear(GL_COLOR_BUFFER_BIT);
491
492    eglSwapBuffers(mDisplay, mSurface);
493
494    glBindTexture(GL_TEXTURE_2D, 0);
495    glEnable(GL_TEXTURE_2D);
496    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
497    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
498    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
499    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
500    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
501
502    const int xc = (mWidth - animation.width) / 2;
503    const int yc = ((mHeight - animation.height) / 2);
504    nsecs_t lastFrame = systemTime();
505    nsecs_t frameDuration = s2ns(1) / animation.fps;
506
507    Region clearReg(Rect(mWidth, mHeight));
508    clearReg.subtractSelf(Rect(xc, yc, xc+animation.width, yc+animation.height));
509
510    for (size_t i=0 ; i<pcount ; i++) {
511        const Animation::Part& part(animation.parts[i]);
512        const size_t fcount = part.frames.size();
513        glBindTexture(GL_TEXTURE_2D, 0);
514
515        for (int r=0 ; !part.count || r<part.count ; r++) {
516            // Exit any non playuntil complete parts immediately
517            if(exitPending() && !part.playUntilComplete)
518                break;
519
520            for (size_t j=0 ; j<fcount && (!exitPending() || part.playUntilComplete) ; j++) {
521                const Animation::Frame& frame(part.frames[j]);
522                nsecs_t lastFrame = systemTime();
523
524                if (r > 0) {
525                    glBindTexture(GL_TEXTURE_2D, frame.tid);
526                } else {
527                    if (part.count != 1) {
528                        glGenTextures(1, &frame.tid);
529                        glBindTexture(GL_TEXTURE_2D, frame.tid);
530                        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
531                        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
532                    }
533                    initTexture(
534                            frame.map->getDataPtr(),
535                            frame.map->getDataLength());
536                }
537
538                if (!clearReg.isEmpty()) {
539                    Region::const_iterator head(clearReg.begin());
540                    Region::const_iterator tail(clearReg.end());
541                    glEnable(GL_SCISSOR_TEST);
542                    while (head != tail) {
543                        const Rect& r(*head++);
544                        glScissor(r.left, mHeight - r.bottom,
545                                r.width(), r.height());
546                        glClear(GL_COLOR_BUFFER_BIT);
547                    }
548                    glDisable(GL_SCISSOR_TEST);
549                }
550                glDrawTexiOES(xc, yc, 0, animation.width, animation.height);
551                eglSwapBuffers(mDisplay, mSurface);
552
553                nsecs_t now = systemTime();
554                nsecs_t delay = frameDuration - (now - lastFrame);
555                //ALOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
556                lastFrame = now;
557
558                if (delay > 0) {
559                    struct timespec spec;
560                    spec.tv_sec  = (now + delay) / 1000000000;
561                    spec.tv_nsec = (now + delay) % 1000000000;
562                    int err;
563                    do {
564                        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
565                    } while (err<0 && errno == EINTR);
566                }
567
568                checkExit();
569            }
570
571            usleep(part.pause * ns2us(frameDuration));
572
573            // For infinite parts, we've now played them at least once, so perhaps exit
574            if(exitPending() && !part.count)
575                break;
576        }
577
578        // free the textures for this part
579        if (part.count != 1) {
580            for (size_t j=0 ; j<fcount ; j++) {
581                const Animation::Frame& frame(part.frames[j]);
582                glDeleteTextures(1, &frame.tid);
583            }
584        }
585    }
586
587    return false;
588}
589
590// ---------------------------------------------------------------------------
591
592}
593; // namespace android
594