Home | History | Annotate | Download | only in bootanimation
      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_NDEBUG 0
     18 #define LOG_TAG "BootAnimation"
     19 
     20 #include <stdint.h>
     21 #include <sys/inotify.h>
     22 #include <sys/poll.h>
     23 #include <sys/stat.h>
     24 #include <sys/types.h>
     25 #include <math.h>
     26 #include <fcntl.h>
     27 #include <utils/misc.h>
     28 #include <signal.h>
     29 #include <time.h>
     30 
     31 #include <cutils/properties.h>
     32 
     33 #include <androidfw/AssetManager.h>
     34 #include <binder/IPCThreadState.h>
     35 #include <utils/Atomic.h>
     36 #include <utils/Errors.h>
     37 #include <utils/Log.h>
     38 
     39 #include <ui/PixelFormat.h>
     40 #include <ui/Rect.h>
     41 #include <ui/Region.h>
     42 #include <ui/DisplayInfo.h>
     43 
     44 #include <gui/ISurfaceComposer.h>
     45 #include <gui/Surface.h>
     46 #include <gui/SurfaceComposerClient.h>
     47 
     48 // TODO: Fix Skia.
     49 #pragma GCC diagnostic push
     50 #pragma GCC diagnostic ignored "-Wunused-parameter"
     51 #include <SkBitmap.h>
     52 #include <SkStream.h>
     53 #include <SkImageDecoder.h>
     54 #pragma GCC diagnostic pop
     55 
     56 #include <GLES/gl.h>
     57 #include <GLES/glext.h>
     58 #include <EGL/eglext.h>
     59 
     60 #include "BootAnimation.h"
     61 #include "audioplay.h"
     62 
     63 namespace android {
     64 
     65 static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
     66 static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
     67 static const char SYSTEM_ENCRYPTED_BOOTANIMATION_FILE[] = "/system/media/bootanimation-encrypted.zip";
     68 static const char SYSTEM_DATA_DIR_PATH[] = "/data/system";
     69 static const char SYSTEM_TIME_DIR_NAME[] = "time";
     70 static const char SYSTEM_TIME_DIR_PATH[] = "/data/system/time";
     71 static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
     72 static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/system/time/last_time_change";
     73 static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
     74 static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/system/time/time_is_accurate";
     75 // Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
     76 static const long long ACCURATE_TIME_EPOCH = 946684800000;
     77 static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
     78 static const char PLAY_SOUND_PROP_NAME[] = "persist.sys.bootanim.play_sound";
     79 static const int ANIM_ENTRY_NAME_MAX = 256;
     80 static const char BOOT_COMPLETED_PROP_NAME[] = "sys.boot_completed";
     81 static const char BOOTREASON_PROP_NAME[] = "ro.boot.bootreason";
     82 // bootreasons list in "system/core/bootstat/bootstat.cpp".
     83 static const std::vector<std::string> PLAY_SOUND_BOOTREASON_BLACKLIST {
     84   "kernel_panic",
     85   "Panic",
     86   "Watchdog",
     87 };
     88 
     89 // ---------------------------------------------------------------------------
     90 
     91 BootAnimation::BootAnimation() : Thread(false), mClockEnabled(true), mTimeIsAccurate(false),
     92         mTimeCheckThread(NULL) {
     93     mSession = new SurfaceComposerClient();
     94 
     95     // If the system has already booted, the animation is not being used for a boot.
     96     mSystemBoot = !property_get_bool(BOOT_COMPLETED_PROP_NAME, 0);
     97 }
     98 
     99 BootAnimation::~BootAnimation() {}
    100 
    101 void BootAnimation::onFirstRef() {
    102     status_t err = mSession->linkToComposerDeath(this);
    103     ALOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
    104     if (err == NO_ERROR) {
    105         run("BootAnimation", PRIORITY_DISPLAY);
    106     }
    107 }
    108 
    109 sp<SurfaceComposerClient> BootAnimation::session() const {
    110     return mSession;
    111 }
    112 
    113 
    114 void BootAnimation::binderDied(const wp<IBinder>&)
    115 {
    116     // woah, surfaceflinger died!
    117     ALOGD("SurfaceFlinger died, exiting...");
    118 
    119     // calling requestExit() is not enough here because the Surface code
    120     // might be blocked on a condition variable that will never be updated.
    121     kill( getpid(), SIGKILL );
    122     requestExit();
    123     audioplay::destroy();
    124 }
    125 
    126 status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
    127         const char* name) {
    128     Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
    129     if (asset == NULL)
    130         return NO_INIT;
    131     SkBitmap bitmap;
    132     SkImageDecoder::DecodeMemory(asset->getBuffer(false), asset->getLength(),
    133             &bitmap, kUnknown_SkColorType, SkImageDecoder::kDecodePixels_Mode);
    134     asset->close();
    135     delete asset;
    136 
    137     // ensure we can call getPixels(). No need to call unlock, since the
    138     // bitmap will go out of scope when we return from this method.
    139     bitmap.lockPixels();
    140 
    141     const int w = bitmap.width();
    142     const int h = bitmap.height();
    143     const void* p = bitmap.getPixels();
    144 
    145     GLint crop[4] = { 0, h, w, -h };
    146     texture->w = w;
    147     texture->h = h;
    148 
    149     glGenTextures(1, &texture->name);
    150     glBindTexture(GL_TEXTURE_2D, texture->name);
    151 
    152     switch (bitmap.colorType()) {
    153         case kAlpha_8_SkColorType:
    154             glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
    155                     GL_UNSIGNED_BYTE, p);
    156             break;
    157         case kARGB_4444_SkColorType:
    158             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
    159                     GL_UNSIGNED_SHORT_4_4_4_4, p);
    160             break;
    161         case kN32_SkColorType:
    162             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
    163                     GL_UNSIGNED_BYTE, p);
    164             break;
    165         case kRGB_565_SkColorType:
    166             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
    167                     GL_UNSIGNED_SHORT_5_6_5, p);
    168             break;
    169         default:
    170             break;
    171     }
    172 
    173     glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
    174     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    175     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    176     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    177     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    178     return NO_ERROR;
    179 }
    180 
    181 status_t BootAnimation::initTexture(const Animation::Frame& frame)
    182 {
    183     //StopWatch watch("blah");
    184 
    185     SkBitmap bitmap;
    186     SkMemoryStream  stream(frame.map->getDataPtr(), frame.map->getDataLength());
    187     SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
    188     if (codec != NULL) {
    189         codec->setDitherImage(false);
    190         codec->decode(&stream, &bitmap,
    191                 kN32_SkColorType,
    192                 SkImageDecoder::kDecodePixels_Mode);
    193         delete codec;
    194     }
    195 
    196     // FileMap memory is never released until application exit.
    197     // Release it now as the texture is already loaded and the memory used for
    198     // the packed resource can be released.
    199     delete frame.map;
    200 
    201     // ensure we can call getPixels(). No need to call unlock, since the
    202     // bitmap will go out of scope when we return from this method.
    203     bitmap.lockPixels();
    204 
    205     const int w = bitmap.width();
    206     const int h = bitmap.height();
    207     const void* p = bitmap.getPixels();
    208 
    209     GLint crop[4] = { 0, h, w, -h };
    210     int tw = 1 << (31 - __builtin_clz(w));
    211     int th = 1 << (31 - __builtin_clz(h));
    212     if (tw < w) tw <<= 1;
    213     if (th < h) th <<= 1;
    214 
    215     switch (bitmap.colorType()) {
    216         case kN32_SkColorType:
    217             if (!mUseNpotTextures && (tw != w || th != h)) {
    218                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
    219                         GL_UNSIGNED_BYTE, 0);
    220                 glTexSubImage2D(GL_TEXTURE_2D, 0,
    221                         0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
    222             } else {
    223                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
    224                         GL_UNSIGNED_BYTE, p);
    225             }
    226             break;
    227 
    228         case kRGB_565_SkColorType:
    229             if (!mUseNpotTextures && (tw != w || th != h)) {
    230                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
    231                         GL_UNSIGNED_SHORT_5_6_5, 0);
    232                 glTexSubImage2D(GL_TEXTURE_2D, 0,
    233                         0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p);
    234             } else {
    235                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
    236                         GL_UNSIGNED_SHORT_5_6_5, p);
    237             }
    238             break;
    239         default:
    240             break;
    241     }
    242 
    243     glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
    244 
    245     return NO_ERROR;
    246 }
    247 
    248 status_t BootAnimation::readyToRun() {
    249     mAssets.addDefaultAssets();
    250 
    251     sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
    252             ISurfaceComposer::eDisplayIdMain));
    253     DisplayInfo dinfo;
    254     status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &dinfo);
    255     if (status)
    256         return -1;
    257 
    258     // create the native surface
    259     sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
    260             dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565);
    261 
    262     SurfaceComposerClient::openGlobalTransaction();
    263     control->setLayer(0x40000000);
    264     SurfaceComposerClient::closeGlobalTransaction();
    265 
    266     sp<Surface> s = control->getSurface();
    267 
    268     // initialize opengl and egl
    269     const EGLint attribs[] = {
    270             EGL_RED_SIZE,   8,
    271             EGL_GREEN_SIZE, 8,
    272             EGL_BLUE_SIZE,  8,
    273             EGL_DEPTH_SIZE, 0,
    274             EGL_NONE
    275     };
    276     EGLint w, h;
    277     EGLint numConfigs;
    278     EGLConfig config;
    279     EGLSurface surface;
    280     EGLContext context;
    281 
    282     EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    283 
    284     eglInitialize(display, 0, 0);
    285     eglChooseConfig(display, attribs, &config, 1, &numConfigs);
    286     surface = eglCreateWindowSurface(display, config, s.get(), NULL);
    287     context = eglCreateContext(display, config, NULL, NULL);
    288     eglQuerySurface(display, surface, EGL_WIDTH, &w);
    289     eglQuerySurface(display, surface, EGL_HEIGHT, &h);
    290 
    291     if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
    292         return NO_INIT;
    293 
    294     mDisplay = display;
    295     mContext = context;
    296     mSurface = surface;
    297     mWidth = w;
    298     mHeight = h;
    299     mFlingerSurfaceControl = control;
    300     mFlingerSurface = s;
    301 
    302     // If the device has encryption turned on or is in process
    303     // of being encrypted we show the encrypted boot animation.
    304     char decrypt[PROPERTY_VALUE_MAX];
    305     property_get("vold.decrypt", decrypt, "");
    306 
    307     bool encryptedAnimation = atoi(decrypt) != 0 || !strcmp("trigger_restart_min_framework", decrypt);
    308 
    309     if (encryptedAnimation && (access(SYSTEM_ENCRYPTED_BOOTANIMATION_FILE, R_OK) == 0)) {
    310         mZipFileName = SYSTEM_ENCRYPTED_BOOTANIMATION_FILE;
    311     }
    312     else if (access(OEM_BOOTANIMATION_FILE, R_OK) == 0) {
    313         mZipFileName = OEM_BOOTANIMATION_FILE;
    314     }
    315     else if (access(SYSTEM_BOOTANIMATION_FILE, R_OK) == 0) {
    316         mZipFileName = SYSTEM_BOOTANIMATION_FILE;
    317     }
    318     return NO_ERROR;
    319 }
    320 
    321 bool BootAnimation::threadLoop()
    322 {
    323     bool r;
    324     // We have no bootanimation file, so we use the stock android logo
    325     // animation.
    326     if (mZipFileName.isEmpty()) {
    327         r = android();
    328     } else {
    329         r = movie();
    330     }
    331 
    332     eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    333     eglDestroyContext(mDisplay, mContext);
    334     eglDestroySurface(mDisplay, mSurface);
    335     mFlingerSurface.clear();
    336     mFlingerSurfaceControl.clear();
    337     eglTerminate(mDisplay);
    338     IPCThreadState::self()->stopProcess();
    339     return r;
    340 }
    341 
    342 bool BootAnimation::android()
    343 {
    344     initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
    345     initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
    346 
    347     // clear screen
    348     glShadeModel(GL_FLAT);
    349     glDisable(GL_DITHER);
    350     glDisable(GL_SCISSOR_TEST);
    351     glClearColor(0,0,0,1);
    352     glClear(GL_COLOR_BUFFER_BIT);
    353     eglSwapBuffers(mDisplay, mSurface);
    354 
    355     glEnable(GL_TEXTURE_2D);
    356     glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    357 
    358     const GLint xc = (mWidth  - mAndroid[0].w) / 2;
    359     const GLint yc = (mHeight - mAndroid[0].h) / 2;
    360     const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
    361 
    362     glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
    363             updateRect.height());
    364 
    365     // Blend state
    366     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    367     glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    368 
    369     const nsecs_t startTime = systemTime();
    370     do {
    371         nsecs_t now = systemTime();
    372         double time = now - startTime;
    373         float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
    374         GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
    375         GLint x = xc - offset;
    376 
    377         glDisable(GL_SCISSOR_TEST);
    378         glClear(GL_COLOR_BUFFER_BIT);
    379 
    380         glEnable(GL_SCISSOR_TEST);
    381         glDisable(GL_BLEND);
    382         glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
    383         glDrawTexiOES(x,                 yc, 0, mAndroid[1].w, mAndroid[1].h);
    384         glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);
    385 
    386         glEnable(GL_BLEND);
    387         glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
    388         glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);
    389 
    390         EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
    391         if (res == EGL_FALSE)
    392             break;
    393 
    394         // 12fps: don't animate too fast to preserve CPU
    395         const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
    396         if (sleepTime > 0)
    397             usleep(sleepTime);
    398 
    399         checkExit();
    400     } while (!exitPending());
    401 
    402     glDeleteTextures(1, &mAndroid[0].name);
    403     glDeleteTextures(1, &mAndroid[1].name);
    404     return false;
    405 }
    406 
    407 
    408 void BootAnimation::checkExit() {
    409     // Allow surface flinger to gracefully request shutdown
    410     char value[PROPERTY_VALUE_MAX];
    411     property_get(EXIT_PROP_NAME, value, "0");
    412     int exitnow = atoi(value);
    413     if (exitnow) {
    414         requestExit();
    415     }
    416 }
    417 
    418 // Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
    419 // characters in str is a hex number in [0, 255], which are converted to
    420 // floating point values in the range [0.0, 1.0] and placed in the
    421 // corresponding elements of color.
    422 //
    423 // If the input string isn't valid, parseColor returns false and color is
    424 // left unchanged.
    425 static bool parseColor(const char str[7], float color[3]) {
    426     float tmpColor[3];
    427     for (int i = 0; i < 3; i++) {
    428         int val = 0;
    429         for (int j = 0; j < 2; j++) {
    430             val *= 16;
    431             char c = str[2*i + j];
    432             if      (c >= '0' && c <= '9') val += c - '0';
    433             else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
    434             else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
    435             else                           return false;
    436         }
    437         tmpColor[i] = static_cast<float>(val) / 255.0f;
    438     }
    439     memcpy(color, tmpColor, sizeof(tmpColor));
    440     return true;
    441 }
    442 
    443 
    444 static bool readFile(ZipFileRO* zip, const char* name, String8& outString)
    445 {
    446     ZipEntryRO entry = zip->findEntryByName(name);
    447     ALOGE_IF(!entry, "couldn't find %s", name);
    448     if (!entry) {
    449         return false;
    450     }
    451 
    452     FileMap* entryMap = zip->createEntryFileMap(entry);
    453     zip->releaseEntry(entry);
    454     ALOGE_IF(!entryMap, "entryMap is null");
    455     if (!entryMap) {
    456         return false;
    457     }
    458 
    459     outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
    460     delete entryMap;
    461     return true;
    462 }
    463 
    464 // The time glyphs are stored in a single image of height 64 pixels. Each digit is 40 pixels wide,
    465 // and the colon character is half that at 20 pixels. The glyph order is '0123456789:'.
    466 // We render 24 hour time.
    467 void BootAnimation::drawTime(const Texture& clockTex, const int yPos) {
    468     static constexpr char TIME_FORMAT[] = "%H:%M";
    469     static constexpr int TIME_LENGTH = sizeof(TIME_FORMAT);
    470 
    471     static constexpr int DIGIT_HEIGHT = 64;
    472     static constexpr int DIGIT_WIDTH = 40;
    473     static constexpr int COLON_WIDTH = DIGIT_WIDTH / 2;
    474     static constexpr int TIME_WIDTH = (DIGIT_WIDTH * 4) + COLON_WIDTH;
    475 
    476     if (clockTex.h < DIGIT_HEIGHT || clockTex.w < (10 * DIGIT_WIDTH + COLON_WIDTH)) {
    477         ALOGE("Clock texture is too small; abandoning boot animation clock");
    478         mClockEnabled = false;
    479         return;
    480     }
    481 
    482     time_t rawtime;
    483     time(&rawtime);
    484     struct tm* timeInfo = localtime(&rawtime);
    485 
    486     char timeBuff[TIME_LENGTH];
    487     size_t length = strftime(timeBuff, TIME_LENGTH, TIME_FORMAT, timeInfo);
    488 
    489     if (length != TIME_LENGTH - 1) {
    490         ALOGE("Couldn't format time; abandoning boot animation clock");
    491         mClockEnabled = false;
    492         return;
    493     }
    494 
    495     glEnable(GL_BLEND);  // Allow us to draw on top of the animation
    496     glBindTexture(GL_TEXTURE_2D, clockTex.name);
    497 
    498     int xPos = (mWidth - TIME_WIDTH) / 2;
    499     int cropRect[4] = { 0, DIGIT_HEIGHT, DIGIT_WIDTH, -DIGIT_HEIGHT };
    500 
    501     for (int i = 0; i < TIME_LENGTH - 1; i++) {
    502         char c = timeBuff[i];
    503         int width = DIGIT_WIDTH;
    504         int pos = c - '0';  // Position in the character list
    505         if (pos < 0 || pos > 10) {
    506             continue;
    507         }
    508         if (c == ':') {
    509             width = COLON_WIDTH;
    510         }
    511 
    512         // Crop the texture to only the pixels in the current glyph
    513         int left = pos * DIGIT_WIDTH;
    514         cropRect[0] = left;
    515         cropRect[2] = width;
    516         glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
    517 
    518         glDrawTexiOES(xPos, yPos, 0, width, DIGIT_HEIGHT);
    519 
    520         xPos += width;
    521     }
    522 
    523     glDisable(GL_BLEND);  // Return to the animation's default behaviour
    524     glBindTexture(GL_TEXTURE_2D, 0);
    525 }
    526 
    527 bool BootAnimation::parseAnimationDesc(Animation& animation)
    528 {
    529     String8 desString;
    530 
    531     if (!readFile(animation.zip, "desc.txt", desString)) {
    532         return false;
    533     }
    534     char const* s = desString.string();
    535 
    536     // Parse the description file
    537     for (;;) {
    538         const char* endl = strstr(s, "\n");
    539         if (endl == NULL) break;
    540         String8 line(s, endl - s);
    541         const char* l = line.string();
    542         int fps = 0;
    543         int width = 0;
    544         int height = 0;
    545         int count = 0;
    546         int pause = 0;
    547         int clockPosY = -1;
    548         char path[ANIM_ENTRY_NAME_MAX];
    549         char color[7] = "000000"; // default to black if unspecified
    550 
    551         char pathType;
    552         if (sscanf(l, "%d %d %d", &width, &height, &fps) == 3) {
    553             // ALOGD("> w=%d, h=%d, fps=%d", width, height, fps);
    554             animation.width = width;
    555             animation.height = height;
    556             animation.fps = fps;
    557         } else if (sscanf(l, " %c %d %d %s #%6s %d",
    558                           &pathType, &count, &pause, path, color, &clockPosY) >= 4) {
    559             // ALOGD("> type=%c, count=%d, pause=%d, path=%s, color=%s, clockPosY=%d", pathType, count, pause, path, color, clockPosY);
    560             Animation::Part part;
    561             part.playUntilComplete = pathType == 'c';
    562             part.count = count;
    563             part.pause = pause;
    564             part.path = path;
    565             part.clockPosY = clockPosY;
    566             part.audioData = NULL;
    567             part.animation = NULL;
    568             if (!parseColor(color, part.backgroundColor)) {
    569                 ALOGE("> invalid color '#%s'", color);
    570                 part.backgroundColor[0] = 0.0f;
    571                 part.backgroundColor[1] = 0.0f;
    572                 part.backgroundColor[2] = 0.0f;
    573             }
    574             animation.parts.add(part);
    575         }
    576         else if (strcmp(l, "$SYSTEM") == 0) {
    577             // ALOGD("> SYSTEM");
    578             Animation::Part part;
    579             part.playUntilComplete = false;
    580             part.count = 1;
    581             part.pause = 0;
    582             part.audioData = NULL;
    583             part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
    584             if (part.animation != NULL)
    585                 animation.parts.add(part);
    586         }
    587         s = ++endl;
    588     }
    589 
    590     return true;
    591 }
    592 
    593 bool BootAnimation::preloadZip(Animation& animation)
    594 {
    595     // read all the data structures
    596     const size_t pcount = animation.parts.size();
    597     void *cookie = NULL;
    598     ZipFileRO* zip = animation.zip;
    599     if (!zip->startIteration(&cookie)) {
    600         return false;
    601     }
    602 
    603     Animation::Part* partWithAudio = NULL;
    604     ZipEntryRO entry;
    605     char name[ANIM_ENTRY_NAME_MAX];
    606     while ((entry = zip->nextEntry(cookie)) != NULL) {
    607         const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
    608         if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
    609             ALOGE("Error fetching entry file name");
    610             continue;
    611         }
    612 
    613         const String8 entryName(name);
    614         const String8 path(entryName.getPathDir());
    615         const String8 leaf(entryName.getPathLeaf());
    616         if (leaf.size() > 0) {
    617             for (size_t j = 0; j < pcount; j++) {
    618                 if (path == animation.parts[j].path) {
    619                     uint16_t method;
    620                     // supports only stored png files
    621                     if (zip->getEntryInfo(entry, &method, NULL, NULL, NULL, NULL, NULL)) {
    622                         if (method == ZipFileRO::kCompressStored) {
    623                             FileMap* map = zip->createEntryFileMap(entry);
    624                             if (map) {
    625                                 Animation::Part& part(animation.parts.editItemAt(j));
    626                                 if (leaf == "audio.wav") {
    627                                     // a part may have at most one audio file
    628                                     part.audioData = (uint8_t *)map->getDataPtr();
    629                                     part.audioLength = map->getDataLength();
    630                                     partWithAudio = &part;
    631                                 } else if (leaf == "trim.txt") {
    632                                     part.trimData.setTo((char const*)map->getDataPtr(),
    633                                                         map->getDataLength());
    634                                 } else {
    635                                     Animation::Frame frame;
    636                                     frame.name = leaf;
    637                                     frame.map = map;
    638                                     frame.trimWidth = animation.width;
    639                                     frame.trimHeight = animation.height;
    640                                     frame.trimX = 0;
    641                                     frame.trimY = 0;
    642                                     part.frames.add(frame);
    643                                 }
    644                             }
    645                         } else {
    646                             ALOGE("bootanimation.zip is compressed; must be only stored");
    647                         }
    648                     }
    649                 }
    650             }
    651         }
    652     }
    653 
    654     // If there is trimData present, override the positioning defaults.
    655     for (Animation::Part& part : animation.parts) {
    656         const char* trimDataStr = part.trimData.string();
    657         for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
    658             const char* endl = strstr(trimDataStr, "\n");
    659             // No more trimData for this part.
    660             if (endl == NULL) {
    661                 break;
    662             }
    663             String8 line(trimDataStr, endl - trimDataStr);
    664             const char* lineStr = line.string();
    665             trimDataStr = ++endl;
    666             int width = 0, height = 0, x = 0, y = 0;
    667             if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
    668                 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
    669                 frame.trimWidth = width;
    670                 frame.trimHeight = height;
    671                 frame.trimX = x;
    672                 frame.trimY = y;
    673             } else {
    674                 ALOGE("Error parsing trim.txt, line: %s", lineStr);
    675                 break;
    676             }
    677         }
    678     }
    679 
    680     // Create and initialize audioplay if there is a wav file in any of the animations.
    681     if (partWithAudio != NULL) {
    682         ALOGD("found audio.wav, creating playback engine");
    683         if (!audioplay::create(partWithAudio->audioData, partWithAudio->audioLength)) {
    684             return false;
    685         }
    686     }
    687 
    688     zip->endIteration(cookie);
    689 
    690     return true;
    691 }
    692 
    693 bool BootAnimation::movie()
    694 {
    695     Animation* animation = loadAnimation(mZipFileName);
    696     if (animation == NULL)
    697         return false;
    698 
    699     bool anyPartHasClock = false;
    700     for (size_t i=0; i < animation->parts.size(); i++) {
    701         if(animation->parts[i].clockPosY >= 0) {
    702             anyPartHasClock = true;
    703             break;
    704         }
    705     }
    706     if (!anyPartHasClock) {
    707         mClockEnabled = false;
    708     }
    709 
    710     // Check if npot textures are supported
    711     mUseNpotTextures = false;
    712     String8 gl_extensions;
    713     const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
    714     if (!exts) {
    715         glGetError();
    716     } else {
    717         gl_extensions.setTo(exts);
    718         if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
    719             (gl_extensions.find("GL_OES_texture_npot") != -1)) {
    720             mUseNpotTextures = true;
    721         }
    722     }
    723 
    724     // Blend required to draw time on top of animation frames.
    725     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    726     glShadeModel(GL_FLAT);
    727     glDisable(GL_DITHER);
    728     glDisable(GL_SCISSOR_TEST);
    729     glDisable(GL_BLEND);
    730 
    731     glBindTexture(GL_TEXTURE_2D, 0);
    732     glEnable(GL_TEXTURE_2D);
    733     glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    734     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    735     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    736     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    737     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    738 
    739     bool clockTextureInitialized = false;
    740     if (mClockEnabled) {
    741         clockTextureInitialized = (initTexture(&mClock, mAssets, "images/clock64.png") == NO_ERROR);
    742         mClockEnabled = clockTextureInitialized;
    743     }
    744 
    745     if (mClockEnabled && !updateIsTimeAccurate()) {
    746         mTimeCheckThread = new TimeCheckThread(this);
    747         mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
    748     }
    749 
    750     playAnimation(*animation);
    751 
    752     if (mTimeCheckThread != NULL) {
    753         mTimeCheckThread->requestExit();
    754         mTimeCheckThread = NULL;
    755     }
    756 
    757     releaseAnimation(animation);
    758 
    759     if (clockTextureInitialized) {
    760         glDeleteTextures(1, &mClock.name);
    761     }
    762 
    763     return false;
    764 }
    765 
    766 bool BootAnimation::playAnimation(const Animation& animation)
    767 {
    768     const size_t pcount = animation.parts.size();
    769     nsecs_t frameDuration = s2ns(1) / animation.fps;
    770     const int animationX = (mWidth - animation.width) / 2;
    771     const int animationY = (mHeight - animation.height) / 2;
    772 
    773     for (size_t i=0 ; i<pcount ; i++) {
    774         const Animation::Part& part(animation.parts[i]);
    775         const size_t fcount = part.frames.size();
    776         glBindTexture(GL_TEXTURE_2D, 0);
    777 
    778         // Handle animation package
    779         if (part.animation != NULL) {
    780             playAnimation(*part.animation);
    781             if (exitPending())
    782                 break;
    783             continue; //to next part
    784         }
    785 
    786         for (int r=0 ; !part.count || r<part.count ; r++) {
    787             // Exit any non playuntil complete parts immediately
    788             if(exitPending() && !part.playUntilComplete)
    789                 break;
    790 
    791             // only play audio file the first time we animate the part
    792             if (r == 0 && part.audioData && playSoundsAllowed()) {
    793                 ALOGD("playing clip for part%d, size=%d", (int) i, part.audioLength);
    794                 audioplay::playClip(part.audioData, part.audioLength);
    795             }
    796 
    797             glClearColor(
    798                     part.backgroundColor[0],
    799                     part.backgroundColor[1],
    800                     part.backgroundColor[2],
    801                     1.0f);
    802 
    803             for (size_t j=0 ; j<fcount && (!exitPending() || part.playUntilComplete) ; j++) {
    804                 const Animation::Frame& frame(part.frames[j]);
    805                 nsecs_t lastFrame = systemTime();
    806 
    807                 if (r > 0) {
    808                     glBindTexture(GL_TEXTURE_2D, frame.tid);
    809                 } else {
    810                     if (part.count != 1) {
    811                         glGenTextures(1, &frame.tid);
    812                         glBindTexture(GL_TEXTURE_2D, frame.tid);
    813                         glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    814                         glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    815                     }
    816                     initTexture(frame);
    817                 }
    818 
    819                 const int xc = animationX + frame.trimX;
    820                 const int yc = animationY + frame.trimY;
    821                 Region clearReg(Rect(mWidth, mHeight));
    822                 clearReg.subtractSelf(Rect(xc, yc, xc+frame.trimWidth, yc+frame.trimHeight));
    823                 if (!clearReg.isEmpty()) {
    824                     Region::const_iterator head(clearReg.begin());
    825                     Region::const_iterator tail(clearReg.end());
    826                     glEnable(GL_SCISSOR_TEST);
    827                     while (head != tail) {
    828                         const Rect& r2(*head++);
    829                         glScissor(r2.left, mHeight - r2.bottom, r2.width(), r2.height());
    830                         glClear(GL_COLOR_BUFFER_BIT);
    831                     }
    832                     glDisable(GL_SCISSOR_TEST);
    833                 }
    834                 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
    835                 // which is equivalent to mHeight - (yc + frame.trimHeight)
    836                 glDrawTexiOES(xc, mHeight - (yc + frame.trimHeight),
    837                               0, frame.trimWidth, frame.trimHeight);
    838                 if (mClockEnabled && mTimeIsAccurate && part.clockPosY >= 0) {
    839                     drawTime(mClock, part.clockPosY);
    840                 }
    841 
    842                 eglSwapBuffers(mDisplay, mSurface);
    843 
    844                 nsecs_t now = systemTime();
    845                 nsecs_t delay = frameDuration - (now - lastFrame);
    846                 //ALOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
    847                 lastFrame = now;
    848 
    849                 if (delay > 0) {
    850                     struct timespec spec;
    851                     spec.tv_sec  = (now + delay) / 1000000000;
    852                     spec.tv_nsec = (now + delay) % 1000000000;
    853                     int err;
    854                     do {
    855                         err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
    856                     } while (err<0 && errno == EINTR);
    857                 }
    858 
    859                 checkExit();
    860             }
    861 
    862             usleep(part.pause * ns2us(frameDuration));
    863 
    864             // For infinite parts, we've now played them at least once, so perhaps exit
    865             if(exitPending() && !part.count)
    866                 break;
    867         }
    868 
    869     }
    870 
    871     // Free textures created for looping parts now that the animation is done.
    872     for (const Animation::Part& part : animation.parts) {
    873         if (part.count != 1) {
    874             const size_t fcount = part.frames.size();
    875             for (size_t j = 0; j < fcount; j++) {
    876                 const Animation::Frame& frame(part.frames[j]);
    877                 glDeleteTextures(1, &frame.tid);
    878             }
    879         }
    880     }
    881 
    882     // we've finally played everything we're going to play
    883     audioplay::setPlaying(false);
    884     audioplay::destroy();
    885 
    886     return true;
    887 }
    888 
    889 void BootAnimation::releaseAnimation(Animation* animation) const
    890 {
    891     for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
    892          e = animation->parts.end(); it != e; ++it) {
    893         if (it->animation)
    894             releaseAnimation(it->animation);
    895     }
    896     if (animation->zip)
    897         delete animation->zip;
    898     delete animation;
    899 }
    900 
    901 BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn)
    902 {
    903     if (mLoadedFiles.indexOf(fn) >= 0) {
    904         ALOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
    905             fn.string());
    906         return NULL;
    907     }
    908     ZipFileRO *zip = ZipFileRO::open(fn);
    909     if (zip == NULL) {
    910         ALOGE("Failed to open animation zip \"%s\": %s",
    911             fn.string(), strerror(errno));
    912         return NULL;
    913     }
    914 
    915     Animation *animation =  new Animation;
    916     animation->fileName = fn;
    917     animation->zip = zip;
    918     mLoadedFiles.add(animation->fileName);
    919 
    920     parseAnimationDesc(*animation);
    921     if (!preloadZip(*animation)) {
    922         return NULL;
    923     }
    924 
    925 
    926     mLoadedFiles.remove(fn);
    927     return animation;
    928 }
    929 
    930 bool BootAnimation::playSoundsAllowed() const {
    931     // Only play sounds for system boots, not runtime restarts.
    932     if (!mSystemBoot) {
    933         return false;
    934     }
    935 
    936     // Read the system property to see if we should play the sound.
    937     // If it's not present, default to allowed.
    938     if (!property_get_bool(PLAY_SOUND_PROP_NAME, 1)) {
    939         return false;
    940     }
    941 
    942     // Don't play sounds if this is a reboot due to an error.
    943     char bootreason[PROPERTY_VALUE_MAX];
    944     if (property_get(BOOTREASON_PROP_NAME, bootreason, nullptr) > 0) {
    945         for (const auto& str : PLAY_SOUND_BOOTREASON_BLACKLIST) {
    946             if (strcasecmp(str.c_str(), bootreason) == 0) {
    947                 return false;
    948             }
    949         }
    950     }
    951     return true;
    952 }
    953 
    954 bool BootAnimation::updateIsTimeAccurate() {
    955     static constexpr long long MAX_TIME_IN_PAST =   60000LL * 60LL * 24LL * 30LL;  // 30 days
    956     static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL;  // 90 minutes
    957 
    958     if (mTimeIsAccurate) {
    959         return true;
    960     }
    961 
    962     struct stat statResult;
    963     if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
    964         mTimeIsAccurate = true;
    965         return true;
    966     }
    967 
    968     FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
    969     if (file != NULL) {
    970       long long lastChangedTime = 0;
    971       fscanf(file, "%lld", &lastChangedTime);
    972       fclose(file);
    973       if (lastChangedTime > 0) {
    974         struct timespec now;
    975         clock_gettime(CLOCK_REALTIME, &now);
    976         // Match the Java timestamp format
    977         long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
    978         if (ACCURATE_TIME_EPOCH < rtcNow
    979             && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
    980             && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
    981             mTimeIsAccurate = true;
    982         }
    983       }
    984     }
    985 
    986     return mTimeIsAccurate;
    987 }
    988 
    989 BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
    990     mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
    991 
    992 BootAnimation::TimeCheckThread::~TimeCheckThread() {
    993     // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
    994     close(mInotifyFd);
    995 }
    996 
    997 bool BootAnimation::TimeCheckThread::threadLoop() {
    998     bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
    999         && mBootAnimation->mClockEnabled;
   1000     if (!shouldLoop) {
   1001         close(mInotifyFd);
   1002         mInotifyFd = -1;
   1003     }
   1004     return shouldLoop;
   1005 }
   1006 
   1007 bool BootAnimation::TimeCheckThread::doThreadLoop() {
   1008     static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
   1009 
   1010     // Poll instead of doing a blocking read so the Thread can exit if requested.
   1011     struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
   1012     ssize_t pollResult = poll(&pfd, 1, 1000);
   1013 
   1014     if (pollResult == 0) {
   1015         return true;
   1016     } else if (pollResult < 0) {
   1017         ALOGE("Could not poll inotify events");
   1018         return false;
   1019     }
   1020 
   1021     char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
   1022     ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
   1023     if (length == 0) {
   1024         return true;
   1025     } else if (length < 0) {
   1026         ALOGE("Could not read inotify events");
   1027         return false;
   1028     }
   1029 
   1030     const struct inotify_event *event;
   1031     for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
   1032         event = (const struct inotify_event *) ptr;
   1033         if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
   1034             addTimeDirWatch();
   1035         } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
   1036                 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
   1037             return !mBootAnimation->updateIsTimeAccurate();
   1038         }
   1039     }
   1040 
   1041     return true;
   1042 }
   1043 
   1044 void BootAnimation::TimeCheckThread::addTimeDirWatch() {
   1045         mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
   1046                 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
   1047         if (mTimeWd > 0) {
   1048             // No need to watch for the time directory to be created if it already exists
   1049             inotify_rm_watch(mInotifyFd, mSystemWd);
   1050             mSystemWd = -1;
   1051         }
   1052 }
   1053 
   1054 status_t BootAnimation::TimeCheckThread::readyToRun() {
   1055     mInotifyFd = inotify_init();
   1056     if (mInotifyFd < 0) {
   1057         ALOGE("Could not initialize inotify fd");
   1058         return NO_INIT;
   1059     }
   1060 
   1061     mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
   1062     if (mSystemWd < 0) {
   1063         close(mInotifyFd);
   1064         mInotifyFd = -1;
   1065         ALOGE("Could not add watch for %s", SYSTEM_DATA_DIR_PATH);
   1066         return NO_INIT;
   1067     }
   1068 
   1069     addTimeDirWatch();
   1070 
   1071     if (mBootAnimation->updateIsTimeAccurate()) {
   1072         close(mInotifyFd);
   1073         mInotifyFd = -1;
   1074         return ALREADY_EXISTS;
   1075     }
   1076 
   1077     return NO_ERROR;
   1078 }
   1079 
   1080 // ---------------------------------------------------------------------------
   1081 
   1082 }
   1083 ; // namespace android
   1084