2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define LOG_TAG "BootAnimation"
21 #include <sys/inotify.h>
24 #include <sys/types.h>
27 #include <utils/misc.h>
31 #include <cutils/properties.h>
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>
39 #include <ui/PixelFormat.h>
41 #include <ui/Region.h>
42 #include <ui/DisplayInfo.h>
44 #include <gui/ISurfaceComposer.h>
45 #include <gui/Surface.h>
46 #include <gui/SurfaceComposerClient.h>
49 #pragma GCC diagnostic push
50 #pragma GCC diagnostic ignored "-Wunused-parameter"
53 #include <SkImageDecoder.h>
54 #pragma GCC diagnostic pop
57 #include <GLES/glext.h>
58 #include <EGL/eglext.h>
60 #include "BootAnimation.h"
61 #include "audioplay.h"
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 CLOCK_FONT_ASSET[] = "images/clock_font.png";
72 static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
73 static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
74 static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/system/time/last_time_change";
75 static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
76 static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/system/time/time_is_accurate";
77 static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/system/time/time_format_12_hour";
78 // Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
79 static const long long ACCURATE_TIME_EPOCH = 946684800000;
80 static constexpr char FONT_BEGIN_CHAR = ' ';
81 static constexpr char FONT_END_CHAR = '~' + 1;
82 static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
83 static constexpr size_t FONT_NUM_COLS = 16;
84 static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
85 static const int TEXT_CENTER_VALUE = INT_MAX;
86 static const int TEXT_MISSING_VALUE = INT_MIN;
87 static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
88 static const char PLAY_SOUND_PROP_NAME[] = "persist.sys.bootanim.play_sound";
89 static const int ANIM_ENTRY_NAME_MAX = 256;
90 static constexpr size_t TEXT_POS_LEN_MAX = 16;
91 static const char BOOT_COMPLETED_PROP_NAME[] = "sys.boot_completed";
92 static const char BOOTREASON_PROP_NAME[] = "ro.boot.bootreason";
93 // bootreasons list in "system/core/bootstat/bootstat.cpp".
94 static const std::vector<std::string> PLAY_SOUND_BOOTREASON_BLACKLIST {
100 // ---------------------------------------------------------------------------
102 BootAnimation::BootAnimation() : Thread(false), mClockEnabled(true), mTimeIsAccurate(false),
103 mTimeFormat12Hour(false), mTimeCheckThread(NULL) {
104 mSession = new SurfaceComposerClient();
106 // If the system has already booted, the animation is not being used for a boot.
107 mSystemBoot = !property_get_bool(BOOT_COMPLETED_PROP_NAME, 0);
110 BootAnimation::~BootAnimation() {}
112 void BootAnimation::onFirstRef() {
113 status_t err = mSession->linkToComposerDeath(this);
114 ALOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
115 if (err == NO_ERROR) {
116 run("BootAnimation", PRIORITY_DISPLAY);
120 sp<SurfaceComposerClient> BootAnimation::session() const {
125 void BootAnimation::binderDied(const wp<IBinder>&)
127 // woah, surfaceflinger died!
128 ALOGD("SurfaceFlinger died, exiting...");
130 // calling requestExit() is not enough here because the Surface code
131 // might be blocked on a condition variable that will never be updated.
132 kill( getpid(), SIGKILL );
134 audioplay::destroy();
137 status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
139 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
143 SkImageDecoder::DecodeMemory(asset->getBuffer(false), asset->getLength(),
144 &bitmap, kUnknown_SkColorType, SkImageDecoder::kDecodePixels_Mode);
148 // ensure we can call getPixels(). No need to call unlock, since the
149 // bitmap will go out of scope when we return from this method.
152 const int w = bitmap.width();
153 const int h = bitmap.height();
154 const void* p = bitmap.getPixels();
156 GLint crop[4] = { 0, h, w, -h };
160 glGenTextures(1, &texture->name);
161 glBindTexture(GL_TEXTURE_2D, texture->name);
163 switch (bitmap.colorType()) {
164 case kAlpha_8_SkColorType:
165 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
166 GL_UNSIGNED_BYTE, p);
168 case kARGB_4444_SkColorType:
169 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
170 GL_UNSIGNED_SHORT_4_4_4_4, p);
172 case kN32_SkColorType:
173 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
174 GL_UNSIGNED_BYTE, p);
176 case kRGB_565_SkColorType:
177 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
178 GL_UNSIGNED_SHORT_5_6_5, p);
184 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
185 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
186 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
187 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
188 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
193 status_t BootAnimation::initTexture(FileMap* map, int* width, int* height)
196 SkMemoryStream stream(map->getDataPtr(), map->getDataLength());
197 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
199 codec->setDitherImage(false);
200 codec->decode(&stream, &bitmap,
202 SkImageDecoder::kDecodePixels_Mode);
206 // FileMap memory is never released until application exit.
207 // Release it now as the texture is already loaded and the memory used for
208 // the packed resource can be released.
211 // ensure we can call getPixels(). No need to call unlock, since the
212 // bitmap will go out of scope when we return from this method.
215 const int w = bitmap.width();
216 const int h = bitmap.height();
217 const void* p = bitmap.getPixels();
219 GLint crop[4] = { 0, h, w, -h };
220 int tw = 1 << (31 - __builtin_clz(w));
221 int th = 1 << (31 - __builtin_clz(h));
222 if (tw < w) tw <<= 1;
223 if (th < h) th <<= 1;
225 switch (bitmap.colorType()) {
226 case kN32_SkColorType:
227 if (!mUseNpotTextures && (tw != w || th != h)) {
228 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
229 GL_UNSIGNED_BYTE, 0);
230 glTexSubImage2D(GL_TEXTURE_2D, 0,
231 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
233 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
234 GL_UNSIGNED_BYTE, p);
238 case kRGB_565_SkColorType:
239 if (!mUseNpotTextures && (tw != w || th != h)) {
240 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
241 GL_UNSIGNED_SHORT_5_6_5, 0);
242 glTexSubImage2D(GL_TEXTURE_2D, 0,
243 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p);
245 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
246 GL_UNSIGNED_SHORT_5_6_5, p);
253 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
261 status_t BootAnimation::readyToRun() {
262 mAssets.addDefaultAssets();
264 sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
265 ISurfaceComposer::eDisplayIdMain));
267 status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &dinfo);
271 // create the native surface
272 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
273 dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565);
275 SurfaceComposerClient::openGlobalTransaction();
276 control->setLayer(0x40000000);
277 SurfaceComposerClient::closeGlobalTransaction();
279 sp<Surface> s = control->getSurface();
281 // initialize opengl and egl
282 const EGLint attribs[] = {
295 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
297 eglInitialize(display, 0, 0);
298 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
299 surface = eglCreateWindowSurface(display, config, s.get(), NULL);
300 context = eglCreateContext(display, config, NULL, NULL);
301 eglQuerySurface(display, surface, EGL_WIDTH, &w);
302 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
304 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
312 mFlingerSurfaceControl = control;
315 // If the device has encryption turned on or is in process
316 // of being encrypted we show the encrypted boot animation.
317 char decrypt[PROPERTY_VALUE_MAX];
318 property_get("vold.decrypt", decrypt, "");
320 bool encryptedAnimation = atoi(decrypt) != 0 || !strcmp("trigger_restart_min_framework", decrypt);
322 if (encryptedAnimation && (access(SYSTEM_ENCRYPTED_BOOTANIMATION_FILE, R_OK) == 0)) {
323 mZipFileName = SYSTEM_ENCRYPTED_BOOTANIMATION_FILE;
325 else if (access(OEM_BOOTANIMATION_FILE, R_OK) == 0) {
326 mZipFileName = OEM_BOOTANIMATION_FILE;
328 else if (access(SYSTEM_BOOTANIMATION_FILE, R_OK) == 0) {
329 mZipFileName = SYSTEM_BOOTANIMATION_FILE;
334 bool BootAnimation::threadLoop()
337 // We have no bootanimation file, so we use the stock android logo
339 if (mZipFileName.isEmpty()) {
345 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
346 eglDestroyContext(mDisplay, mContext);
347 eglDestroySurface(mDisplay, mSurface);
348 mFlingerSurface.clear();
349 mFlingerSurfaceControl.clear();
350 eglTerminate(mDisplay);
351 IPCThreadState::self()->stopProcess();
355 bool BootAnimation::android()
357 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
358 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
361 glShadeModel(GL_FLAT);
362 glDisable(GL_DITHER);
363 glDisable(GL_SCISSOR_TEST);
364 glClearColor(0,0,0,1);
365 glClear(GL_COLOR_BUFFER_BIT);
366 eglSwapBuffers(mDisplay, mSurface);
368 glEnable(GL_TEXTURE_2D);
369 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
371 const GLint xc = (mWidth - mAndroid[0].w) / 2;
372 const GLint yc = (mHeight - mAndroid[0].h) / 2;
373 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
375 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
376 updateRect.height());
379 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
380 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
382 const nsecs_t startTime = systemTime();
384 nsecs_t now = systemTime();
385 double time = now - startTime;
386 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
387 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
388 GLint x = xc - offset;
390 glDisable(GL_SCISSOR_TEST);
391 glClear(GL_COLOR_BUFFER_BIT);
393 glEnable(GL_SCISSOR_TEST);
395 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
396 glDrawTexiOES(x, yc, 0, mAndroid[1].w, mAndroid[1].h);
397 glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);
400 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
401 glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);
403 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
404 if (res == EGL_FALSE)
407 // 12fps: don't animate too fast to preserve CPU
408 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
413 } while (!exitPending());
415 glDeleteTextures(1, &mAndroid[0].name);
416 glDeleteTextures(1, &mAndroid[1].name);
420 void BootAnimation::checkExit() {
421 // Allow surface flinger to gracefully request shutdown
422 char value[PROPERTY_VALUE_MAX];
423 property_get(EXIT_PROP_NAME, value, "0");
424 int exitnow = atoi(value);
430 bool BootAnimation::validClock(const Animation::Part& part) {
431 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
434 bool parseTextCoord(const char* str, int* dest) {
435 if (strcmp("c", str) == 0) {
436 *dest = TEXT_CENTER_VALUE;
441 int val = (int) strtol(str, &end, 0);
442 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
449 // Parse two position coordinates. If only string is non-empty, treat it as the y value.
450 void parsePosition(const char* str1, const char* str2, int* x, int* y) {
451 bool success = false;
452 if (strlen(str1) == 0) { // No values were specified
454 } else if (strlen(str2) == 0) { // we have only one value
455 if (parseTextCoord(str1, y)) {
456 *x = TEXT_CENTER_VALUE;
460 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
466 *x = TEXT_MISSING_VALUE;
467 *y = TEXT_MISSING_VALUE;
471 // Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
472 // characters in str is a hex number in [0, 255], which are converted to
473 // floating point values in the range [0.0, 1.0] and placed in the
474 // corresponding elements of color.
476 // If the input string isn't valid, parseColor returns false and color is
478 static bool parseColor(const char str[7], float color[3]) {
480 for (int i = 0; i < 3; i++) {
482 for (int j = 0; j < 2; j++) {
484 char c = str[2*i + j];
485 if (c >= '0' && c <= '9') val += c - '0';
486 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
487 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
490 tmpColor[i] = static_cast<float>(val) / 255.0f;
492 memcpy(color, tmpColor, sizeof(tmpColor));
497 static bool readFile(ZipFileRO* zip, const char* name, String8& outString)
499 ZipEntryRO entry = zip->findEntryByName(name);
500 ALOGE_IF(!entry, "couldn't find %s", name);
505 FileMap* entryMap = zip->createEntryFileMap(entry);
506 zip->releaseEntry(entry);
507 ALOGE_IF(!entryMap, "entryMap is null");
512 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
517 // The font image should be a 96x2 array of character images. The
518 // columns are the printable ASCII characters 0x20 - 0x7f. The
519 // top row is regular text; the bottom row is bold.
520 status_t BootAnimation::initFont(Font* font, const char* fallback) {
521 status_t status = NO_ERROR;
523 if (font->map != nullptr) {
524 glGenTextures(1, &font->texture.name);
525 glBindTexture(GL_TEXTURE_2D, font->texture.name);
527 status = initTexture(font->map, &font->texture.w, &font->texture.h);
529 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
530 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
531 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
532 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
533 } else if (fallback != nullptr) {
534 status = initTexture(&font->texture, mAssets, fallback);
539 if (status == NO_ERROR) {
540 font->char_width = font->texture.w / FONT_NUM_COLS;
541 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
547 void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
548 glEnable(GL_BLEND); // Allow us to draw on top of the animation
549 glBindTexture(GL_TEXTURE_2D, font.texture.name);
551 const int len = strlen(str);
552 const int strWidth = font.char_width * len;
554 if (*x == TEXT_CENTER_VALUE) {
555 *x = (mWidth - strWidth) / 2;
557 *x = mWidth + *x - strWidth;
559 if (*y == TEXT_CENTER_VALUE) {
560 *y = (mHeight - font.char_height) / 2;
562 *y = mHeight + *y - font.char_height;
565 int cropRect[4] = { 0, 0, font.char_width, -font.char_height };
567 for (int i = 0; i < len; i++) {
570 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
574 // Crop the texture to only the pixels in the current glyph
575 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
576 const int row = charPos / FONT_NUM_COLS;
577 const int col = charPos % FONT_NUM_COLS;
578 cropRect[0] = col * font.char_width; // Left of column
579 cropRect[1] = row * font.char_height * 2; // Top of row
580 // Move down to bottom of regular (one char_heigh) or bold (two char_heigh) line
581 cropRect[1] += bold ? 2 * font.char_height : font.char_height;
582 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
584 glDrawTexiOES(*x, *y, 0, font.char_width, font.char_height);
586 *x += font.char_width;
589 glDisable(GL_BLEND); // Return to the animation's default behaviour
590 glBindTexture(GL_TEXTURE_2D, 0);
593 // We render 12 or 24 hour time.
594 void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
595 static constexpr char TIME_FORMAT_12[] = "%l:%M";
596 static constexpr char TIME_FORMAT_24[] = "%H:%M";
597 static constexpr int TIME_LENGTH = 6;
601 struct tm* timeInfo = localtime(&rawtime);
603 char timeBuff[TIME_LENGTH];
604 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
605 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
607 if (length != TIME_LENGTH - 1) {
608 ALOGE("Couldn't format time; abandoning boot animation clock");
609 mClockEnabled = false;
613 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
616 drawText(out, font, false, &x, &y);
619 bool BootAnimation::parseAnimationDesc(Animation& animation)
623 if (!readFile(animation.zip, "desc.txt", desString)) {
626 char const* s = desString.string();
628 // Parse the description file
630 const char* endl = strstr(s, "\n");
631 if (endl == NULL) break;
632 String8 line(s, endl - s);
633 const char* l = line.string();
639 char path[ANIM_ENTRY_NAME_MAX];
640 char color[7] = "000000"; // default to black if unspecified
641 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
642 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
645 if (sscanf(l, "%d %d %d", &width, &height, &fps) == 3) {
646 // ALOGD("> w=%d, h=%d, fps=%d", width, height, fps);
647 animation.width = width;
648 animation.height = height;
650 } else if (sscanf(l, " %c %d %d %s #%6s %16s %16s",
651 &pathType, &count, &pause, path, color, clockPos1, clockPos2) >= 4) {
652 //ALOGD("> type=%c, count=%d, pause=%d, path=%s, color=%s, clockPos1=%s, clockPos2=%s",
653 // pathType, count, pause, path, color, clockPos1, clockPos2);
654 Animation::Part part;
655 part.playUntilComplete = pathType == 'c';
659 part.audioData = NULL;
660 part.animation = NULL;
661 if (!parseColor(color, part.backgroundColor)) {
662 ALOGE("> invalid color '#%s'", color);
663 part.backgroundColor[0] = 0.0f;
664 part.backgroundColor[1] = 0.0f;
665 part.backgroundColor[2] = 0.0f;
667 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
668 animation.parts.add(part);
670 else if (strcmp(l, "$SYSTEM") == 0) {
671 // ALOGD("> SYSTEM");
672 Animation::Part part;
673 part.playUntilComplete = false;
676 part.audioData = NULL;
677 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
678 if (part.animation != NULL)
679 animation.parts.add(part);
687 bool BootAnimation::preloadZip(Animation& animation)
689 // read all the data structures
690 const size_t pcount = animation.parts.size();
692 ZipFileRO* zip = animation.zip;
693 if (!zip->startIteration(&cookie)) {
697 Animation::Part* partWithAudio = NULL;
699 char name[ANIM_ENTRY_NAME_MAX];
700 while ((entry = zip->nextEntry(cookie)) != NULL) {
701 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
702 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
703 ALOGE("Error fetching entry file name");
707 const String8 entryName(name);
708 const String8 path(entryName.getPathDir());
709 const String8 leaf(entryName.getPathLeaf());
710 if (leaf.size() > 0) {
711 if (entryName == CLOCK_FONT_ZIP_NAME) {
712 FileMap* map = zip->createEntryFileMap(entry);
714 animation.clockFont.map = map;
719 for (size_t j = 0; j < pcount; j++) {
720 if (path == animation.parts[j].path) {
722 // supports only stored png files
723 if (zip->getEntryInfo(entry, &method, NULL, NULL, NULL, NULL, NULL)) {
724 if (method == ZipFileRO::kCompressStored) {
725 FileMap* map = zip->createEntryFileMap(entry);
727 Animation::Part& part(animation.parts.editItemAt(j));
728 if (leaf == "audio.wav") {
729 // a part may have at most one audio file
730 part.audioData = (uint8_t *)map->getDataPtr();
731 part.audioLength = map->getDataLength();
732 partWithAudio = ∂
733 } else if (leaf == "trim.txt") {
734 part.trimData.setTo((char const*)map->getDataPtr(),
735 map->getDataLength());
737 Animation::Frame frame;
740 frame.trimWidth = animation.width;
741 frame.trimHeight = animation.height;
744 part.frames.add(frame);
748 ALOGE("bootanimation.zip is compressed; must be only stored");
756 // If there is trimData present, override the positioning defaults.
757 for (Animation::Part& part : animation.parts) {
758 const char* trimDataStr = part.trimData.string();
759 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
760 const char* endl = strstr(trimDataStr, "\n");
761 // No more trimData for this part.
765 String8 line(trimDataStr, endl - trimDataStr);
766 const char* lineStr = line.string();
767 trimDataStr = ++endl;
768 int width = 0, height = 0, x = 0, y = 0;
769 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
770 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
771 frame.trimWidth = width;
772 frame.trimHeight = height;
776 ALOGE("Error parsing trim.txt, line: %s", lineStr);
782 // Create and initialize audioplay if there is a wav file in any of the animations.
783 if (partWithAudio != NULL) {
784 ALOGD("found audio.wav, creating playback engine");
785 if (!audioplay::create(partWithAudio->audioData, partWithAudio->audioLength)) {
790 zip->endIteration(cookie);
795 bool BootAnimation::movie()
797 Animation* animation = loadAnimation(mZipFileName);
798 if (animation == NULL)
801 bool anyPartHasClock = false;
802 for (size_t i=0; i < animation->parts.size(); i++) {
803 if(validClock(animation->parts[i])) {
804 anyPartHasClock = true;
808 if (!anyPartHasClock) {
809 mClockEnabled = false;
812 // Check if npot textures are supported
813 mUseNpotTextures = false;
814 String8 gl_extensions;
815 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
819 gl_extensions.setTo(exts);
820 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
821 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
822 mUseNpotTextures = true;
826 // Blend required to draw time on top of animation frames.
827 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
828 glShadeModel(GL_FLAT);
829 glDisable(GL_DITHER);
830 glDisable(GL_SCISSOR_TEST);
833 glBindTexture(GL_TEXTURE_2D, 0);
834 glEnable(GL_TEXTURE_2D);
835 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
836 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
837 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
838 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
839 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
841 bool clockFontInitialized = false;
843 clockFontInitialized =
844 (initFont(&animation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
845 mClockEnabled = clockFontInitialized;
848 if (mClockEnabled && !updateIsTimeAccurate()) {
849 mTimeCheckThread = new TimeCheckThread(this);
850 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
853 playAnimation(*animation);
855 if (mTimeCheckThread != NULL) {
856 mTimeCheckThread->requestExit();
857 mTimeCheckThread = NULL;
860 releaseAnimation(animation);
862 if (clockFontInitialized) {
863 glDeleteTextures(1, &animation->clockFont.texture.name);
869 bool BootAnimation::playAnimation(const Animation& animation)
871 const size_t pcount = animation.parts.size();
872 nsecs_t frameDuration = s2ns(1) / animation.fps;
873 const int animationX = (mWidth - animation.width) / 2;
874 const int animationY = (mHeight - animation.height) / 2;
876 for (size_t i=0 ; i<pcount ; i++) {
877 const Animation::Part& part(animation.parts[i]);
878 const size_t fcount = part.frames.size();
879 glBindTexture(GL_TEXTURE_2D, 0);
881 // Handle animation package
882 if (part.animation != NULL) {
883 playAnimation(*part.animation);
886 continue; //to next part
889 for (int r=0 ; !part.count || r<part.count ; r++) {
890 // Exit any non playuntil complete parts immediately
891 if(exitPending() && !part.playUntilComplete)
894 // only play audio file the first time we animate the part
895 if (r == 0 && part.audioData && playSoundsAllowed()) {
896 ALOGD("playing clip for part%d, size=%d", (int) i, part.audioLength);
897 audioplay::playClip(part.audioData, part.audioLength);
901 part.backgroundColor[0],
902 part.backgroundColor[1],
903 part.backgroundColor[2],
906 for (size_t j=0 ; j<fcount && (!exitPending() || part.playUntilComplete) ; j++) {
907 const Animation::Frame& frame(part.frames[j]);
908 nsecs_t lastFrame = systemTime();
911 glBindTexture(GL_TEXTURE_2D, frame.tid);
913 if (part.count != 1) {
914 glGenTextures(1, &frame.tid);
915 glBindTexture(GL_TEXTURE_2D, frame.tid);
916 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
917 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
920 initTexture(frame.map, &w, &h);
923 const int xc = animationX + frame.trimX;
924 const int yc = animationY + frame.trimY;
925 Region clearReg(Rect(mWidth, mHeight));
926 clearReg.subtractSelf(Rect(xc, yc, xc+frame.trimWidth, yc+frame.trimHeight));
927 if (!clearReg.isEmpty()) {
928 Region::const_iterator head(clearReg.begin());
929 Region::const_iterator tail(clearReg.end());
930 glEnable(GL_SCISSOR_TEST);
931 while (head != tail) {
932 const Rect& r2(*head++);
933 glScissor(r2.left, mHeight - r2.bottom, r2.width(), r2.height());
934 glClear(GL_COLOR_BUFFER_BIT);
936 glDisable(GL_SCISSOR_TEST);
938 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
939 // which is equivalent to mHeight - (yc + frame.trimHeight)
940 glDrawTexiOES(xc, mHeight - (yc + frame.trimHeight),
941 0, frame.trimWidth, frame.trimHeight);
942 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
943 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
946 eglSwapBuffers(mDisplay, mSurface);
948 nsecs_t now = systemTime();
949 nsecs_t delay = frameDuration - (now - lastFrame);
950 //ALOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
954 struct timespec spec;
955 spec.tv_sec = (now + delay) / 1000000000;
956 spec.tv_nsec = (now + delay) % 1000000000;
959 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
960 } while (err<0 && errno == EINTR);
966 usleep(part.pause * ns2us(frameDuration));
968 // For infinite parts, we've now played them at least once, so perhaps exit
969 if(exitPending() && !part.count)
975 // Free textures created for looping parts now that the animation is done.
976 for (const Animation::Part& part : animation.parts) {
977 if (part.count != 1) {
978 const size_t fcount = part.frames.size();
979 for (size_t j = 0; j < fcount; j++) {
980 const Animation::Frame& frame(part.frames[j]);
981 glDeleteTextures(1, &frame.tid);
986 // we've finally played everything we're going to play
987 audioplay::setPlaying(false);
988 audioplay::destroy();
993 void BootAnimation::releaseAnimation(Animation* animation) const
995 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
996 e = animation->parts.end(); it != e; ++it) {
998 releaseAnimation(it->animation);
1001 delete animation->zip;
1005 BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn)
1007 if (mLoadedFiles.indexOf(fn) >= 0) {
1008 ALOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
1012 ZipFileRO *zip = ZipFileRO::open(fn);
1014 ALOGE("Failed to open animation zip \"%s\": %s",
1015 fn.string(), strerror(errno));
1019 Animation *animation = new Animation;
1020 animation->fileName = fn;
1021 animation->zip = zip;
1022 animation->clockFont.map = nullptr;
1023 mLoadedFiles.add(animation->fileName);
1025 parseAnimationDesc(*animation);
1026 if (!preloadZip(*animation)) {
1031 mLoadedFiles.remove(fn);
1035 bool BootAnimation::playSoundsAllowed() const {
1036 // Only play sounds for system boots, not runtime restarts.
1041 // Read the system property to see if we should play the sound.
1042 // If it's not present, default to allowed.
1043 if (!property_get_bool(PLAY_SOUND_PROP_NAME, 1)) {
1047 // Don't play sounds if this is a reboot due to an error.
1048 char bootreason[PROPERTY_VALUE_MAX];
1049 if (property_get(BOOTREASON_PROP_NAME, bootreason, nullptr) > 0) {
1050 for (const auto& str : PLAY_SOUND_BOOTREASON_BLACKLIST) {
1051 if (strcasecmp(str.c_str(), bootreason) == 0) {
1059 bool BootAnimation::updateIsTimeAccurate() {
1060 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1061 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1063 if (mTimeIsAccurate) {
1067 struct stat statResult;
1069 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1070 mTimeFormat12Hour = true;
1073 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1074 mTimeIsAccurate = true;
1078 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
1080 long long lastChangedTime = 0;
1081 fscanf(file, "%lld", &lastChangedTime);
1083 if (lastChangedTime > 0) {
1084 struct timespec now;
1085 clock_gettime(CLOCK_REALTIME, &now);
1086 // Match the Java timestamp format
1087 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
1088 if (ACCURATE_TIME_EPOCH < rtcNow
1089 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1090 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
1091 mTimeIsAccurate = true;
1096 return mTimeIsAccurate;
1099 BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1100 mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1102 BootAnimation::TimeCheckThread::~TimeCheckThread() {
1103 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1107 bool BootAnimation::TimeCheckThread::threadLoop() {
1108 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1109 && mBootAnimation->mClockEnabled;
1117 bool BootAnimation::TimeCheckThread::doThreadLoop() {
1118 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1120 // Poll instead of doing a blocking read so the Thread can exit if requested.
1121 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1122 ssize_t pollResult = poll(&pfd, 1, 1000);
1124 if (pollResult == 0) {
1126 } else if (pollResult < 0) {
1127 ALOGE("Could not poll inotify events");
1131 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1132 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1135 } else if (length < 0) {
1136 ALOGE("Could not read inotify events");
1140 const struct inotify_event *event;
1141 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1142 event = (const struct inotify_event *) ptr;
1143 if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
1145 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1146 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1147 return !mBootAnimation->updateIsTimeAccurate();
1154 void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1155 mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
1156 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1158 // No need to watch for the time directory to be created if it already exists
1159 inotify_rm_watch(mInotifyFd, mSystemWd);
1164 status_t BootAnimation::TimeCheckThread::readyToRun() {
1165 mInotifyFd = inotify_init();
1166 if (mInotifyFd < 0) {
1167 ALOGE("Could not initialize inotify fd");
1171 mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1172 if (mSystemWd < 0) {
1175 ALOGE("Could not add watch for %s", SYSTEM_DATA_DIR_PATH);
1181 if (mBootAnimation->updateIsTimeAccurate()) {
1184 return ALREADY_EXISTS;
1190 // ---------------------------------------------------------------------------
1193 ; // namespace android