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