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 <vector>
21
22 #include <stdint.h>
23 #include <inttypes.h>
24 #include <sys/inotify.h>
25 #include <sys/poll.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <math.h>
29 #include <fcntl.h>
30 #include <utils/misc.h>
31 #include <signal.h>
32 #include <time.h>
33
34 #include <cutils/atomic.h>
35 #include <cutils/properties.h>
36
37 #include <android/imagedecoder.h>
38 #include <androidfw/AssetManager.h>
39 #include <binder/IPCThreadState.h>
40 #include <utils/Errors.h>
41 #include <utils/Log.h>
42 #include <utils/SystemClock.h>
43
44 #include <android-base/properties.h>
45
46 #include <ui/DisplayMode.h>
47 #include <ui/PixelFormat.h>
48 #include <ui/Rect.h>
49 #include <ui/Region.h>
50
51 #include <gui/ISurfaceComposer.h>
52 #include <gui/DisplayEventReceiver.h>
53 #include <gui/Surface.h>
54 #include <gui/SurfaceComposerClient.h>
55 #include <GLES2/gl2.h>
56 #include <GLES2/gl2ext.h>
57 #include <EGL/eglext.h>
58
59 #include "BootAnimation.h"
60
61 #define ANIM_PATH_MAX 255
62 #define STR(x) #x
63 #define STRTO(x) STR(x)
64
65 namespace android {
66
67 using ui::DisplayMode;
68
69 static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
70 static const char PRODUCT_BOOTANIMATION_DARK_FILE[] = "/product/media/bootanimation-dark.zip";
71 static const char PRODUCT_BOOTANIMATION_FILE[] = "/product/media/bootanimation.zip";
72 static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
73 static const char APEX_BOOTANIMATION_FILE[] = "/apex/com.android.bootanimation/etc/bootanimation.zip";
74 static const char PRODUCT_ENCRYPTED_BOOTANIMATION_FILE[] = "/product/media/bootanimation-encrypted.zip";
75 static const char SYSTEM_ENCRYPTED_BOOTANIMATION_FILE[] = "/system/media/bootanimation-encrypted.zip";
76 static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
77 static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
78 static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
79
80 static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
81 static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
82 static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
83
84 static const char BOOTANIM_DATA_DIR_PATH[] = "/data/bootanim";
85 static const char BOOTANIM_TIME_DIR_NAME[] = "time";
86 static const char BOOTANIM_TIME_DIR_PATH[] = "/data/bootanim/time";
87 static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
88 static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
89 static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
90 static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
91 static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
92 static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/bootanim/time/last_time_change";
93 static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
94 static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/bootanim/time/time_is_accurate";
95 static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/bootanim/time/time_format_12_hour";
96 // Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
97 static const long long ACCURATE_TIME_EPOCH = 946684800000;
98 static constexpr char FONT_BEGIN_CHAR = ' ';
99 static constexpr char FONT_END_CHAR = '~' + 1;
100 static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
101 static constexpr size_t FONT_NUM_COLS = 16;
102 static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
103 static const int TEXT_CENTER_VALUE = INT_MAX;
104 static const int TEXT_MISSING_VALUE = INT_MIN;
105 static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
106 static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
107 static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
108 static const char CLOCK_ENABLED_PROP_NAME[] = "persist.sys.bootanim.clock.enabled";
109 static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
110 static constexpr size_t TEXT_POS_LEN_MAX = 16;
111 static const int DYNAMIC_COLOR_COUNT = 4;
112 static const char U_TEXTURE[] = "uTexture";
113 static const char U_FADE[] = "uFade";
114 static const char U_CROP_AREA[] = "uCropArea";
115 static const char U_START_COLOR_PREFIX[] = "uStartColor";
116 static const char U_END_COLOR_PREFIX[] = "uEndColor";
117 static const char U_COLOR_PROGRESS[] = "uColorProgress";
118 static const char A_UV[] = "aUv";
119 static const char A_POSITION[] = "aPosition";
120 static const char VERTEX_SHADER_SOURCE[] = R"(
121 precision mediump float;
122 attribute vec4 aPosition;
123 attribute highp vec2 aUv;
124 varying highp vec2 vUv;
125 void main() {
126 gl_Position = aPosition;
127 vUv = aUv;
128 })";
129 static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
130 precision mediump float;
131 const float cWhiteMaskThreshold = 0.05;
132 uniform sampler2D uTexture;
133 uniform float uFade;
134 uniform float uColorProgress;
135 uniform vec3 uStartColor0;
136 uniform vec3 uStartColor1;
137 uniform vec3 uStartColor2;
138 uniform vec3 uStartColor3;
139 uniform vec3 uEndColor0;
140 uniform vec3 uEndColor1;
141 uniform vec3 uEndColor2;
142 uniform vec3 uEndColor3;
143 varying highp vec2 vUv;
144 void main() {
145 vec4 mask = texture2D(uTexture, vUv);
146 float r = mask.r;
147 float g = mask.g;
148 float b = mask.b;
149 float a = mask.a;
150 // If all channels have values, render pixel as a shade of white.
151 float useWhiteMask = step(cWhiteMaskThreshold, r)
152 * step(cWhiteMaskThreshold, g)
153 * step(cWhiteMaskThreshold, b)
154 * step(cWhiteMaskThreshold, a);
155 vec3 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
156 + g * mix(uStartColor1, uEndColor1, uColorProgress)
157 + b * mix(uStartColor2, uEndColor2, uColorProgress)
158 + a * mix(uStartColor3, uEndColor3, uColorProgress);
159 color = mix(color, vec3((r + g + b + a) * 0.25), useWhiteMask);
160 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade));
161 })";
162 static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
163 precision mediump float;
164 uniform sampler2D uTexture;
165 uniform float uFade;
166 varying highp vec2 vUv;
167 void main() {
168 vec4 color = texture2D(uTexture, vUv);
169 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
170 })";
171 static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
172 precision mediump float;
173 uniform sampler2D uTexture;
174 uniform vec4 uCropArea;
175 varying highp vec2 vUv;
176 void main() {
177 vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
178 mix(uCropArea.y, uCropArea.w, vUv.y));
179 gl_FragColor = texture2D(uTexture, uv);
180 })";
181
182 static GLfloat quadPositions[] = {
183 -0.5f, -0.5f,
184 +0.5f, -0.5f,
185 +0.5f, +0.5f,
186 +0.5f, +0.5f,
187 -0.5f, +0.5f,
188 -0.5f, -0.5f
189 };
190 static GLfloat quadUVs[] = {
191 0.0f, 1.0f,
192 1.0f, 1.0f,
193 1.0f, 0.0f,
194 1.0f, 0.0f,
195 0.0f, 0.0f,
196 0.0f, 1.0f
197 };
198
199 // ---------------------------------------------------------------------------
200
BootAnimation(sp<Callbacks> callbacks)201 BootAnimation::BootAnimation(sp<Callbacks> callbacks)
202 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
203 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
204 mSession = new SurfaceComposerClient();
205
206 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
207 if (powerCtl.empty()) {
208 mShuttingDown = false;
209 } else {
210 mShuttingDown = true;
211 }
212 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
213 elapsedRealtime());
214 }
215
~BootAnimation()216 BootAnimation::~BootAnimation() {
217 if (mAnimation != nullptr) {
218 releaseAnimation(mAnimation);
219 mAnimation = nullptr;
220 }
221 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
222 elapsedRealtime());
223 }
224
onFirstRef()225 void BootAnimation::onFirstRef() {
226 status_t err = mSession->linkToComposerDeath(this);
227 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
228 if (err == NO_ERROR) {
229 // Load the animation content -- this can be slow (eg 200ms)
230 // called before waitForSurfaceFlinger() in main() to avoid wait
231 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
232 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
233 preloadAnimation();
234 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
235 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
236 }
237 }
238
session() const239 sp<SurfaceComposerClient> BootAnimation::session() const {
240 return mSession;
241 }
242
binderDied(const wp<IBinder> &)243 void BootAnimation::binderDied(const wp<IBinder>&) {
244 // woah, surfaceflinger died!
245 SLOGD("SurfaceFlinger died, exiting...");
246
247 // calling requestExit() is not enough here because the Surface code
248 // might be blocked on a condition variable that will never be updated.
249 kill( getpid(), SIGKILL );
250 requestExit();
251 }
252
decodeImage(const void * encodedData,size_t dataLength,AndroidBitmapInfo * outInfo,bool premultiplyAlpha)253 static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
254 bool premultiplyAlpha) {
255 AImageDecoder* decoder = nullptr;
256 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
257 if (!decoder) {
258 return nullptr;
259 }
260
261 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
262 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
263 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
264 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
265 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
266 outInfo->flags = 0;
267
268 if (!premultiplyAlpha) {
269 AImageDecoder_setUnpremultipliedRequired(decoder, true);
270 }
271
272 const size_t size = outInfo->stride * outInfo->height;
273 void* pixels = malloc(size);
274 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
275 AImageDecoder_delete(decoder);
276
277 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
278 free(pixels);
279 return nullptr;
280 }
281 return pixels;
282 }
283
initTexture(Texture * texture,AssetManager & assets,const char * name,bool premultiplyAlpha)284 status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
285 const char* name, bool premultiplyAlpha) {
286 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
287 if (asset == nullptr)
288 return NO_INIT;
289
290 AndroidBitmapInfo bitmapInfo;
291 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
292 premultiplyAlpha);
293 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
294
295 asset->close();
296 delete asset;
297
298 if (!pixels) {
299 return NO_INIT;
300 }
301
302 const int w = bitmapInfo.width;
303 const int h = bitmapInfo.height;
304
305 texture->w = w;
306 texture->h = h;
307
308 glGenTextures(1, &texture->name);
309 glBindTexture(GL_TEXTURE_2D, texture->name);
310
311 switch (bitmapInfo.format) {
312 case ANDROID_BITMAP_FORMAT_A_8:
313 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
314 GL_UNSIGNED_BYTE, pixels);
315 break;
316 case ANDROID_BITMAP_FORMAT_RGBA_4444:
317 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
318 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
319 break;
320 case ANDROID_BITMAP_FORMAT_RGBA_8888:
321 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
322 GL_UNSIGNED_BYTE, pixels);
323 break;
324 case ANDROID_BITMAP_FORMAT_RGB_565:
325 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
326 GL_UNSIGNED_SHORT_5_6_5, pixels);
327 break;
328 default:
329 break;
330 }
331
332 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
333 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
334 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
335 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
336
337 return NO_ERROR;
338 }
339
initTexture(FileMap * map,int * width,int * height,bool premultiplyAlpha)340 status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
341 bool premultiplyAlpha) {
342 AndroidBitmapInfo bitmapInfo;
343 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
344 premultiplyAlpha);
345 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
346
347 // FileMap memory is never released until application exit.
348 // Release it now as the texture is already loaded and the memory used for
349 // the packed resource can be released.
350 delete map;
351
352 if (!pixels) {
353 return NO_INIT;
354 }
355
356 const int w = bitmapInfo.width;
357 const int h = bitmapInfo.height;
358
359 int tw = 1 << (31 - __builtin_clz(w));
360 int th = 1 << (31 - __builtin_clz(h));
361 if (tw < w) tw <<= 1;
362 if (th < h) th <<= 1;
363
364 switch (bitmapInfo.format) {
365 case ANDROID_BITMAP_FORMAT_RGBA_8888:
366 if (!mUseNpotTextures && (tw != w || th != h)) {
367 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
368 GL_UNSIGNED_BYTE, nullptr);
369 glTexSubImage2D(GL_TEXTURE_2D, 0,
370 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
371 } else {
372 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
373 GL_UNSIGNED_BYTE, pixels);
374 }
375 break;
376
377 case ANDROID_BITMAP_FORMAT_RGB_565:
378 if (!mUseNpotTextures && (tw != w || th != h)) {
379 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
380 GL_UNSIGNED_SHORT_5_6_5, nullptr);
381 glTexSubImage2D(GL_TEXTURE_2D, 0,
382 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
383 } else {
384 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
385 GL_UNSIGNED_SHORT_5_6_5, pixels);
386 }
387 break;
388 default:
389 break;
390 }
391
392 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
393 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
394 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
395 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
396
397 *width = w;
398 *height = h;
399
400 return NO_ERROR;
401 }
402
403 class BootAnimation::DisplayEventCallback : public LooperCallback {
404 BootAnimation* mBootAnimation;
405
406 public:
DisplayEventCallback(BootAnimation * bootAnimation)407 DisplayEventCallback(BootAnimation* bootAnimation) {
408 mBootAnimation = bootAnimation;
409 }
410
handleEvent(int,int events,void *)411 int handleEvent(int /* fd */, int events, void* /* data */) {
412 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
413 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
414 events);
415 return 0; // remove the callback
416 }
417
418 if (!(events & Looper::EVENT_INPUT)) {
419 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
420 return 1; // keep the callback
421 }
422
423 constexpr int kBufferSize = 100;
424 DisplayEventReceiver::Event buffer[kBufferSize];
425 ssize_t numEvents;
426 do {
427 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
428 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
429 const auto& event = buffer[i];
430 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
431 SLOGV("Hotplug received");
432
433 if (!event.hotplug.connected) {
434 // ignore hotplug disconnect
435 continue;
436 }
437 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
438 event.header.displayId);
439
440 if (token != mBootAnimation->mDisplayToken) {
441 // ignore hotplug of a secondary display
442 continue;
443 }
444
445 DisplayMode displayMode;
446 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
447 mBootAnimation->mDisplayToken, &displayMode);
448 if (error != NO_ERROR) {
449 SLOGE("Can't get active display mode.");
450 }
451 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
452 displayMode.resolution.getHeight());
453 }
454 }
455 } while (numEvents > 0);
456
457 return 1; // keep the callback
458 }
459 };
460
getEglConfig(const EGLDisplay & display)461 EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
462 const EGLint attribs[] = {
463 EGL_RED_SIZE, 8,
464 EGL_GREEN_SIZE, 8,
465 EGL_BLUE_SIZE, 8,
466 EGL_DEPTH_SIZE, 0,
467 EGL_NONE
468 };
469 EGLint numConfigs;
470 EGLConfig config;
471 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
472 return config;
473 }
474
limitSurfaceSize(int width,int height) const475 ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
476 ui::Size limited(width, height);
477 bool wasLimited = false;
478 const float aspectRatio = float(width) / float(height);
479 if (mMaxWidth != 0 && width > mMaxWidth) {
480 limited.height = mMaxWidth / aspectRatio;
481 limited.width = mMaxWidth;
482 wasLimited = true;
483 }
484 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
485 limited.height = mMaxHeight;
486 limited.width = mMaxHeight * aspectRatio;
487 wasLimited = true;
488 }
489 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
490 limited.width, limited.height, width, height);
491 return limited;
492 }
493
readyToRun()494 status_t BootAnimation::readyToRun() {
495 mAssets.addDefaultAssets();
496
497 mDisplayToken = SurfaceComposerClient::getInternalDisplayToken();
498 if (mDisplayToken == nullptr)
499 return NAME_NOT_FOUND;
500
501 DisplayMode displayMode;
502 const status_t error =
503 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
504 if (error != NO_ERROR)
505 return error;
506
507 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
508 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
509 ui::Size resolution = displayMode.resolution;
510 resolution = limitSurfaceSize(resolution.width, resolution.height);
511 // create the native surface
512 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
513 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565);
514
515 SurfaceComposerClient::Transaction t;
516
517 // this guest property specifies multi-display IDs to show the boot animation
518 // multiple ids can be set with comma (,) as separator, for example:
519 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
520 Vector<PhysicalDisplayId> physicalDisplayIds;
521 char displayValue[PROPERTY_VALUE_MAX] = "";
522 property_get(DISPLAYS_PROP_NAME, displayValue, "");
523 bool isValid = displayValue[0] != '\0';
524 if (isValid) {
525 char *p = displayValue;
526 while (*p) {
527 if (!isdigit(*p) && *p != ',') {
528 isValid = false;
529 break;
530 }
531 p ++;
532 }
533 if (!isValid)
534 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
535 }
536 if (isValid) {
537 std::istringstream stream(displayValue);
538 for (PhysicalDisplayId id; stream >> id.value; ) {
539 physicalDisplayIds.add(id);
540 if (stream.peek() == ',')
541 stream.ignore();
542 }
543
544 // In the case of multi-display, boot animation shows on the specified displays
545 // in addition to the primary display
546 const auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
547 for (const auto id : physicalDisplayIds) {
548 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
549 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
550 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
551 }
552 }
553 }
554 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
555 }
556
557 t.setLayer(control, 0x40000000)
558 .apply();
559
560 sp<Surface> s = control->getSurface();
561
562 // initialize opengl and egl
563 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
564 eglInitialize(display, nullptr, nullptr);
565 EGLConfig config = getEglConfig(display);
566 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
567 // Initialize egl context with client version number 2.0.
568 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
569 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
570 EGLint w, h;
571 eglQuerySurface(display, surface, EGL_WIDTH, &w);
572 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
573
574 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
575 return NO_INIT;
576
577 mDisplay = display;
578 mContext = context;
579 mSurface = surface;
580 mInitWidth = mWidth = w;
581 mInitHeight = mHeight = h;
582 mFlingerSurfaceControl = control;
583 mFlingerSurface = s;
584 mTargetInset = -1;
585
586 // Rotate the boot animation according to the value specified in the sysprop
587 // ro.bootanim.set_orientation_<display_id>. Four values are supported: ORIENTATION_0,
588 // ORIENTATION_90, ORIENTATION_180 and ORIENTATION_270.
589 // If the value isn't specified or is ORIENTATION_0, nothing will be changed.
590 // This is needed to support having boot animation in orientations different from the natural
591 // device orientation. For example, on tablets that may want to keep natural orientation
592 // portrait for applications compatibility and to have the boot animation in landscape.
593 rotateAwayFromNaturalOrientationIfNeeded();
594
595 projectSceneToWindow();
596
597 // Register a display event receiver
598 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
599 status_t status = mDisplayEventReceiver->initCheck();
600 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
601 status);
602 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
603 new DisplayEventCallback(this), nullptr);
604
605 return NO_ERROR;
606 }
607
rotateAwayFromNaturalOrientationIfNeeded()608 void BootAnimation::rotateAwayFromNaturalOrientationIfNeeded() {
609 const auto orientation = parseOrientationProperty();
610
611 if (orientation == ui::ROTATION_0) {
612 // Do nothing if the sysprop isn't set or is set to ROTATION_0.
613 return;
614 }
615
616 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
617 std::swap(mWidth, mHeight);
618 std::swap(mInitWidth, mInitHeight);
619 mFlingerSurfaceControl->updateDefaultBufferSize(mWidth, mHeight);
620 }
621
622 Rect displayRect(0, 0, mWidth, mHeight);
623 Rect layerStackRect(0, 0, mWidth, mHeight);
624
625 SurfaceComposerClient::Transaction t;
626 t.setDisplayProjection(mDisplayToken, orientation, layerStackRect, displayRect);
627 t.apply();
628 }
629
parseOrientationProperty()630 ui::Rotation BootAnimation::parseOrientationProperty() {
631 const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
632 if (displayIds.size() == 0) {
633 return ui::ROTATION_0;
634 }
635 const auto displayId = displayIds[0];
636 const auto syspropName = [displayId] {
637 std::stringstream ss;
638 ss << "ro.bootanim.set_orientation_" << displayId.value;
639 return ss.str();
640 }();
641 const auto syspropValue = android::base::GetProperty(syspropName, "ORIENTATION_0");
642 if (syspropValue == "ORIENTATION_90") {
643 return ui::ROTATION_90;
644 } else if (syspropValue == "ORIENTATION_180") {
645 return ui::ROTATION_180;
646 } else if (syspropValue == "ORIENTATION_270") {
647 return ui::ROTATION_270;
648 }
649 return ui::ROTATION_0;
650 }
651
projectSceneToWindow()652 void BootAnimation::projectSceneToWindow() {
653 glViewport(0, 0, mWidth, mHeight);
654 glScissor(0, 0, mWidth, mHeight);
655 }
656
resizeSurface(int newWidth,int newHeight)657 void BootAnimation::resizeSurface(int newWidth, int newHeight) {
658 // We assume this function is called on the animation thread.
659 if (newWidth == mWidth && newHeight == mHeight) {
660 return;
661 }
662 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
663
664 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
665 eglDestroySurface(mDisplay, mSurface);
666
667 mFlingerSurfaceControl->updateDefaultBufferSize(newWidth, newHeight);
668 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
669 mWidth = limitedSize.width;
670 mHeight = limitedSize.height;
671
672 SurfaceComposerClient::Transaction t;
673 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
674 t.apply();
675
676 EGLConfig config = getEglConfig(mDisplay);
677 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
678 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
679 SLOGE("Can't make the new surface current. Error %d", eglGetError());
680 return;
681 }
682
683 projectSceneToWindow();
684
685 mSurface = surface;
686 }
687
preloadAnimation()688 bool BootAnimation::preloadAnimation() {
689 findBootAnimationFile();
690 if (!mZipFileName.isEmpty()) {
691 mAnimation = loadAnimation(mZipFileName);
692 return (mAnimation != nullptr);
693 }
694
695 return false;
696 }
697
findBootAnimationFileInternal(const std::vector<std::string> & files)698 bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
699 for (const std::string& f : files) {
700 if (access(f.c_str(), R_OK) == 0) {
701 mZipFileName = f.c_str();
702 return true;
703 }
704 }
705 return false;
706 }
707
findBootAnimationFile()708 void BootAnimation::findBootAnimationFile() {
709 // If the device has encryption turned on or is in process
710 // of being encrypted we show the encrypted boot animation.
711 char decrypt[PROPERTY_VALUE_MAX];
712 property_get("vold.decrypt", decrypt, "");
713
714 bool encryptedAnimation = atoi(decrypt) != 0 ||
715 !strcmp("trigger_restart_min_framework", decrypt);
716
717 if (!mShuttingDown && encryptedAnimation) {
718 static const std::vector<std::string> encryptedBootFiles = {
719 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
720 };
721 if (findBootAnimationFileInternal(encryptedBootFiles)) {
722 return;
723 }
724 }
725
726 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
727 static const std::vector<std::string> bootFiles = {
728 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
729 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
730 };
731 static const std::vector<std::string> shutdownFiles = {
732 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
733 };
734 static const std::vector<std::string> userspaceRebootFiles = {
735 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
736 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
737 };
738
739 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
740 findBootAnimationFileInternal(userspaceRebootFiles);
741 } else if (mShuttingDown) {
742 findBootAnimationFileInternal(shutdownFiles);
743 } else {
744 findBootAnimationFileInternal(bootFiles);
745 }
746 }
747
compileShader(GLenum shaderType,const GLchar * source)748 GLuint compileShader(GLenum shaderType, const GLchar *source) {
749 GLuint shader = glCreateShader(shaderType);
750 glShaderSource(shader, 1, &source, 0);
751 glCompileShader(shader);
752 GLint isCompiled = 0;
753 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
754 if (isCompiled == GL_FALSE) {
755 SLOGE("Compile shader failed. Shader type: %d", shaderType);
756 GLint maxLength = 0;
757 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
758 std::vector<GLchar> errorLog(maxLength);
759 glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
760 SLOGE("Shader compilation error: %s", &errorLog[0]);
761 return 0;
762 }
763 return shader;
764 }
765
linkShader(GLuint vertexShader,GLuint fragmentShader)766 GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
767 GLuint program = glCreateProgram();
768 glAttachShader(program, vertexShader);
769 glAttachShader(program, fragmentShader);
770 glLinkProgram(program);
771 GLint isLinked = 0;
772 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
773 if (isLinked == GL_FALSE) {
774 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
775 vertexShader, fragmentShader);
776 return 0;
777 }
778 return program;
779 }
780
initShaders()781 void BootAnimation::initShaders() {
782 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
783 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
784 GLuint imageFragmentShader =
785 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
786 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
787 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
788 GLuint textFragmentShader =
789 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
790
791 // Initialize image shader.
792 mImageShader = linkShader(vertexShader, imageFragmentShader);
793 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
794 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
795 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
796 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
797 glEnableVertexAttribArray(positionLocation);
798 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
799 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
800 glEnableVertexAttribArray(uvLocation);
801
802 // Initialize text shader.
803 mTextShader = linkShader(vertexShader, textFragmentShader);
804 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
805 uvLocation = glGetAttribLocation(mTextShader, A_UV);
806 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
807 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
808 glEnableVertexAttribArray(positionLocation);
809 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
810 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
811 glEnableVertexAttribArray(uvLocation);
812 }
813
threadLoop()814 bool BootAnimation::threadLoop() {
815 bool result;
816 initShaders();
817
818 // We have no bootanimation file, so we use the stock android logo
819 // animation.
820 if (mZipFileName.isEmpty()) {
821 ALOGD("No animation file");
822 result = android();
823 } else {
824 result = movie();
825 }
826
827 mCallbacks->shutdown();
828 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
829 eglDestroyContext(mDisplay, mContext);
830 eglDestroySurface(mDisplay, mSurface);
831 mFlingerSurface.clear();
832 mFlingerSurfaceControl.clear();
833 eglTerminate(mDisplay);
834 eglReleaseThread();
835 IPCThreadState::self()->stopProcess();
836 return result;
837 }
838
android()839 bool BootAnimation::android() {
840 glActiveTexture(GL_TEXTURE0);
841
842 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
843 elapsedRealtime());
844 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
845 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
846
847 mCallbacks->init({});
848
849 // clear screen
850 glDisable(GL_DITHER);
851 glDisable(GL_SCISSOR_TEST);
852 glUseProgram(mImageShader);
853
854 glClearColor(0,0,0,1);
855 glClear(GL_COLOR_BUFFER_BIT);
856 eglSwapBuffers(mDisplay, mSurface);
857
858 // Blend state
859 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
860
861 const nsecs_t startTime = systemTime();
862 do {
863 processDisplayEvents();
864 const GLint xc = (mWidth - mAndroid[0].w) / 2;
865 const GLint yc = (mHeight - mAndroid[0].h) / 2;
866 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
867 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
868 updateRect.height());
869
870 nsecs_t now = systemTime();
871 double time = now - startTime;
872 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
873 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
874 GLint x = xc - offset;
875
876 glDisable(GL_SCISSOR_TEST);
877 glClear(GL_COLOR_BUFFER_BIT);
878
879 glEnable(GL_SCISSOR_TEST);
880 glDisable(GL_BLEND);
881 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
882 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
883 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
884
885 glEnable(GL_BLEND);
886 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
887 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
888
889 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
890 if (res == EGL_FALSE)
891 break;
892
893 // 12fps: don't animate too fast to preserve CPU
894 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
895 if (sleepTime > 0)
896 usleep(sleepTime);
897
898 checkExit();
899 } while (!exitPending());
900
901 glDeleteTextures(1, &mAndroid[0].name);
902 glDeleteTextures(1, &mAndroid[1].name);
903 return false;
904 }
905
checkExit()906 void BootAnimation::checkExit() {
907 // Allow surface flinger to gracefully request shutdown
908 char value[PROPERTY_VALUE_MAX];
909 property_get(EXIT_PROP_NAME, value, "0");
910 int exitnow = atoi(value);
911 if (exitnow) {
912 requestExit();
913 }
914 }
915
validClock(const Animation::Part & part)916 bool BootAnimation::validClock(const Animation::Part& part) {
917 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
918 }
919
parseTextCoord(const char * str,int * dest)920 bool parseTextCoord(const char* str, int* dest) {
921 if (strcmp("c", str) == 0) {
922 *dest = TEXT_CENTER_VALUE;
923 return true;
924 }
925
926 char* end;
927 int val = (int) strtol(str, &end, 0);
928 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
929 return false;
930 }
931 *dest = val;
932 return true;
933 }
934
935 // Parse two position coordinates. If only string is non-empty, treat it as the y value.
parsePosition(const char * str1,const char * str2,int * x,int * y)936 void parsePosition(const char* str1, const char* str2, int* x, int* y) {
937 bool success = false;
938 if (strlen(str1) == 0) { // No values were specified
939 // success = false
940 } else if (strlen(str2) == 0) { // we have only one value
941 if (parseTextCoord(str1, y)) {
942 *x = TEXT_CENTER_VALUE;
943 success = true;
944 }
945 } else {
946 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
947 success = true;
948 }
949 }
950
951 if (!success) {
952 *x = TEXT_MISSING_VALUE;
953 *y = TEXT_MISSING_VALUE;
954 }
955 }
956
957 // Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
958 // characters in str is a hex number in [0, 255], which are converted to
959 // floating point values in the range [0.0, 1.0] and placed in the
960 // corresponding elements of color.
961 //
962 // If the input string isn't valid, parseColor returns false and color is
963 // left unchanged.
parseColor(const char str[7],float color[3])964 static bool parseColor(const char str[7], float color[3]) {
965 float tmpColor[3];
966 for (int i = 0; i < 3; i++) {
967 int val = 0;
968 for (int j = 0; j < 2; j++) {
969 val *= 16;
970 char c = str[2*i + j];
971 if (c >= '0' && c <= '9') val += c - '0';
972 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
973 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
974 else return false;
975 }
976 tmpColor[i] = static_cast<float>(val) / 255.0f;
977 }
978 memcpy(color, tmpColor, sizeof(tmpColor));
979 return true;
980 }
981
982 // Parse a color represented as a signed decimal int string.
983 // E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
984 // If the input color string is empty, set color with values in defaultColor.
parseColorDecimalString(const std::string & colorString,float color[3],float defaultColor[3])985 static void parseColorDecimalString(const std::string& colorString,
986 float color[3], float defaultColor[3]) {
987 if (colorString == "") {
988 memcpy(color, defaultColor, sizeof(float) * 3);
989 return;
990 }
991 int colorInt = atoi(colorString.c_str());
992 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
993 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
994 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
995 }
996
readFile(ZipFileRO * zip,const char * name,String8 & outString)997 static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
998 ZipEntryRO entry = zip->findEntryByName(name);
999 SLOGE_IF(!entry, "couldn't find %s", name);
1000 if (!entry) {
1001 return false;
1002 }
1003
1004 FileMap* entryMap = zip->createEntryFileMap(entry);
1005 zip->releaseEntry(entry);
1006 SLOGE_IF(!entryMap, "entryMap is null");
1007 if (!entryMap) {
1008 return false;
1009 }
1010
1011 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
1012 delete entryMap;
1013 return true;
1014 }
1015
1016 // The font image should be a 96x2 array of character images. The
1017 // columns are the printable ASCII characters 0x20 - 0x7f. The
1018 // top row is regular text; the bottom row is bold.
initFont(Font * font,const char * fallback)1019 status_t BootAnimation::initFont(Font* font, const char* fallback) {
1020 status_t status = NO_ERROR;
1021
1022 if (font->map != nullptr) {
1023 glGenTextures(1, &font->texture.name);
1024 glBindTexture(GL_TEXTURE_2D, font->texture.name);
1025
1026 status = initTexture(font->map, &font->texture.w, &font->texture.h);
1027
1028 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1029 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1030 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1031 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1032 } else if (fallback != nullptr) {
1033 status = initTexture(&font->texture, mAssets, fallback);
1034 } else {
1035 return NO_INIT;
1036 }
1037
1038 if (status == NO_ERROR) {
1039 font->char_width = font->texture.w / FONT_NUM_COLS;
1040 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
1041 }
1042
1043 return status;
1044 }
1045
drawText(const char * str,const Font & font,bool bold,int * x,int * y)1046 void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
1047 glEnable(GL_BLEND); // Allow us to draw on top of the animation
1048 glBindTexture(GL_TEXTURE_2D, font.texture.name);
1049 glUseProgram(mTextShader);
1050 glUniform1i(mTextTextureLocation, 0);
1051
1052 const int len = strlen(str);
1053 const int strWidth = font.char_width * len;
1054
1055 if (*x == TEXT_CENTER_VALUE) {
1056 *x = (mWidth - strWidth) / 2;
1057 } else if (*x < 0) {
1058 *x = mWidth + *x - strWidth;
1059 }
1060 if (*y == TEXT_CENTER_VALUE) {
1061 *y = (mHeight - font.char_height) / 2;
1062 } else if (*y < 0) {
1063 *y = mHeight + *y - font.char_height;
1064 }
1065
1066 for (int i = 0; i < len; i++) {
1067 char c = str[i];
1068
1069 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1070 c = '?';
1071 }
1072
1073 // Crop the texture to only the pixels in the current glyph
1074 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1075 const int row = charPos / FONT_NUM_COLS;
1076 const int col = charPos % FONT_NUM_COLS;
1077 // Bold fonts are expected in the second half of each row.
1078 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1079 float u0 = ((float)col) / FONT_NUM_COLS;
1080 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1081 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1082 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1083 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
1084
1085 *x += font.char_width;
1086 }
1087
1088 glDisable(GL_BLEND); // Return to the animation's default behaviour
1089 glBindTexture(GL_TEXTURE_2D, 0);
1090 }
1091
1092 // We render 12 or 24 hour time.
drawClock(const Font & font,const int xPos,const int yPos)1093 void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
1094 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1095 static constexpr char TIME_FORMAT_24[] = "%H:%M";
1096 static constexpr int TIME_LENGTH = 6;
1097
1098 time_t rawtime;
1099 time(&rawtime);
1100 struct tm* timeInfo = localtime(&rawtime);
1101
1102 char timeBuff[TIME_LENGTH];
1103 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1104 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
1105
1106 if (length != TIME_LENGTH - 1) {
1107 SLOGE("Couldn't format time; abandoning boot animation clock");
1108 mClockEnabled = false;
1109 return;
1110 }
1111
1112 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
1113 int x = xPos;
1114 int y = yPos;
1115 drawText(out, font, false, &x, &y);
1116 }
1117
drawProgress(int percent,const Font & font,const int xPos,const int yPos)1118 void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1119 static constexpr int PERCENT_LENGTH = 5;
1120
1121 char percentBuff[PERCENT_LENGTH];
1122 // ';' has the ascii code just after ':', and the font resource contains '%'
1123 // for that ascii code.
1124 sprintf(percentBuff, "%d;", percent);
1125 int x = xPos;
1126 int y = yPos;
1127 drawText(percentBuff, font, false, &x, &y);
1128 }
1129
parseAnimationDesc(Animation & animation)1130 bool BootAnimation::parseAnimationDesc(Animation& animation) {
1131 String8 desString;
1132
1133 if (!readFile(animation.zip, "desc.txt", desString)) {
1134 return false;
1135 }
1136 char const* s = desString.string();
1137 std::string dynamicColoringPartName = "";
1138 bool postDynamicColoring = false;
1139
1140 // Parse the description file
1141 for (;;) {
1142 const char* endl = strstr(s, "\n");
1143 if (endl == nullptr) break;
1144 String8 line(s, endl - s);
1145 const char* l = line.string();
1146 int fps = 0;
1147 int width = 0;
1148 int height = 0;
1149 int count = 0;
1150 int pause = 0;
1151 int progress = 0;
1152 int framesToFadeCount = 0;
1153 int colorTransitionStart = 0;
1154 int colorTransitionEnd = 0;
1155 char path[ANIM_ENTRY_NAME_MAX];
1156 char color[7] = "000000"; // default to black if unspecified
1157 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1158 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
1159 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
1160 char pathType;
1161 // start colors default to black if unspecified
1162 char start_color_0[7] = "000000";
1163 char start_color_1[7] = "000000";
1164 char start_color_2[7] = "000000";
1165 char start_color_3[7] = "000000";
1166
1167 int nextReadPos;
1168
1169 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1170 if (topLineNumbers == 3 || topLineNumbers == 4) {
1171 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
1172 animation.width = width;
1173 animation.height = height;
1174 animation.fps = fps;
1175 if (topLineNumbers == 4) {
1176 animation.progressEnabled = (progress != 0);
1177 } else {
1178 animation.progressEnabled = false;
1179 }
1180 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
1181 dynamicColoringPartNameBuffer,
1182 start_color_0, start_color_1, start_color_2, start_color_3,
1183 &colorTransitionStart, &colorTransitionEnd)) {
1184 animation.dynamicColoringEnabled = true;
1185 parseColor(start_color_0, animation.startColors[0]);
1186 parseColor(start_color_1, animation.startColors[1]);
1187 parseColor(start_color_2, animation.startColors[2]);
1188 parseColor(start_color_3, animation.startColors[3]);
1189 animation.colorTransitionStart = colorTransitionStart;
1190 animation.colorTransitionEnd = colorTransitionEnd;
1191 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
1192 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1193 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1194 if (pathType == 'f') {
1195 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1196 clockPos2);
1197 } else {
1198 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1199 }
1200 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1201 // "clockPos1=%s, clockPos2=%s",
1202 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
1203 Animation::Part part;
1204 if (path == dynamicColoringPartName) {
1205 // Part is specified to use dynamic coloring.
1206 part.useDynamicColoring = true;
1207 part.postDynamicColoring = false;
1208 postDynamicColoring = true;
1209 } else {
1210 // Part does not use dynamic coloring.
1211 part.useDynamicColoring = false;
1212 part.postDynamicColoring = postDynamicColoring;
1213 }
1214 part.playUntilComplete = pathType == 'c';
1215 part.framesToFadeCount = framesToFadeCount;
1216 part.count = count;
1217 part.pause = pause;
1218 part.path = path;
1219 part.audioData = nullptr;
1220 part.animation = nullptr;
1221 if (!parseColor(color, part.backgroundColor)) {
1222 SLOGE("> invalid color '#%s'", color);
1223 part.backgroundColor[0] = 0.0f;
1224 part.backgroundColor[1] = 0.0f;
1225 part.backgroundColor[2] = 0.0f;
1226 }
1227 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
1228 animation.parts.add(part);
1229 }
1230 else if (strcmp(l, "$SYSTEM") == 0) {
1231 // SLOGD("> SYSTEM");
1232 Animation::Part part;
1233 part.playUntilComplete = false;
1234 part.framesToFadeCount = 0;
1235 part.count = 1;
1236 part.pause = 0;
1237 part.audioData = nullptr;
1238 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
1239 if (part.animation != nullptr)
1240 animation.parts.add(part);
1241 }
1242 s = ++endl;
1243 }
1244
1245 return true;
1246 }
1247
preloadZip(Animation & animation)1248 bool BootAnimation::preloadZip(Animation& animation) {
1249 // read all the data structures
1250 const size_t pcount = animation.parts.size();
1251 void *cookie = nullptr;
1252 ZipFileRO* zip = animation.zip;
1253 if (!zip->startIteration(&cookie)) {
1254 return false;
1255 }
1256
1257 ZipEntryRO entry;
1258 char name[ANIM_ENTRY_NAME_MAX];
1259 while ((entry = zip->nextEntry(cookie)) != nullptr) {
1260 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
1261 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
1262 SLOGE("Error fetching entry file name");
1263 continue;
1264 }
1265
1266 const String8 entryName(name);
1267 const String8 path(entryName.getPathDir());
1268 const String8 leaf(entryName.getPathLeaf());
1269 if (leaf.size() > 0) {
1270 if (entryName == CLOCK_FONT_ZIP_NAME) {
1271 FileMap* map = zip->createEntryFileMap(entry);
1272 if (map) {
1273 animation.clockFont.map = map;
1274 }
1275 continue;
1276 }
1277
1278 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1279 FileMap* map = zip->createEntryFileMap(entry);
1280 if (map) {
1281 animation.progressFont.map = map;
1282 }
1283 continue;
1284 }
1285
1286 for (size_t j = 0; j < pcount; j++) {
1287 if (path == animation.parts[j].path) {
1288 uint16_t method;
1289 // supports only stored png files
1290 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
1291 if (method == ZipFileRO::kCompressStored) {
1292 FileMap* map = zip->createEntryFileMap(entry);
1293 if (map) {
1294 Animation::Part& part(animation.parts.editItemAt(j));
1295 if (leaf == "audio.wav") {
1296 // a part may have at most one audio file
1297 part.audioData = (uint8_t *)map->getDataPtr();
1298 part.audioLength = map->getDataLength();
1299 } else if (leaf == "trim.txt") {
1300 part.trimData.setTo((char const*)map->getDataPtr(),
1301 map->getDataLength());
1302 } else {
1303 Animation::Frame frame;
1304 frame.name = leaf;
1305 frame.map = map;
1306 frame.trimWidth = animation.width;
1307 frame.trimHeight = animation.height;
1308 frame.trimX = 0;
1309 frame.trimY = 0;
1310 part.frames.add(frame);
1311 }
1312 }
1313 } else {
1314 SLOGE("bootanimation.zip is compressed; must be only stored");
1315 }
1316 }
1317 }
1318 }
1319 }
1320 }
1321
1322 // If there is trimData present, override the positioning defaults.
1323 for (Animation::Part& part : animation.parts) {
1324 const char* trimDataStr = part.trimData.string();
1325 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1326 const char* endl = strstr(trimDataStr, "\n");
1327 // No more trimData for this part.
1328 if (endl == nullptr) {
1329 break;
1330 }
1331 String8 line(trimDataStr, endl - trimDataStr);
1332 const char* lineStr = line.string();
1333 trimDataStr = ++endl;
1334 int width = 0, height = 0, x = 0, y = 0;
1335 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1336 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1337 frame.trimWidth = width;
1338 frame.trimHeight = height;
1339 frame.trimX = x;
1340 frame.trimY = y;
1341 } else {
1342 SLOGE("Error parsing trim.txt, line: %s", lineStr);
1343 break;
1344 }
1345 }
1346 }
1347
1348 zip->endIteration(cookie);
1349
1350 return true;
1351 }
1352
movie()1353 bool BootAnimation::movie() {
1354 if (mAnimation == nullptr) {
1355 mAnimation = loadAnimation(mZipFileName);
1356 }
1357
1358 if (mAnimation == nullptr)
1359 return false;
1360
1361 // mCallbacks->init() may get called recursively,
1362 // this loop is needed to get the same results
1363 for (const Animation::Part& part : mAnimation->parts) {
1364 if (part.animation != nullptr) {
1365 mCallbacks->init(part.animation->parts);
1366 }
1367 }
1368 mCallbacks->init(mAnimation->parts);
1369
1370 bool anyPartHasClock = false;
1371 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1372 if(validClock(mAnimation->parts[i])) {
1373 anyPartHasClock = true;
1374 break;
1375 }
1376 }
1377 if (!anyPartHasClock) {
1378 mClockEnabled = false;
1379 } else if (!android::base::GetBoolProperty(CLOCK_ENABLED_PROP_NAME, false)) {
1380 mClockEnabled = false;
1381 }
1382
1383 // Check if npot textures are supported
1384 mUseNpotTextures = false;
1385 String8 gl_extensions;
1386 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1387 if (!exts) {
1388 glGetError();
1389 } else {
1390 gl_extensions.setTo(exts);
1391 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1392 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1393 mUseNpotTextures = true;
1394 }
1395 }
1396
1397 // Blend required to draw time on top of animation frames.
1398 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1399 glDisable(GL_DITHER);
1400 glDisable(GL_SCISSOR_TEST);
1401 glDisable(GL_BLEND);
1402
1403 glEnable(GL_TEXTURE_2D);
1404 glBindTexture(GL_TEXTURE_2D, 0);
1405 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1406 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1407 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1408 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1409 bool clockFontInitialized = false;
1410 if (mClockEnabled) {
1411 clockFontInitialized =
1412 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
1413 mClockEnabled = clockFontInitialized;
1414 }
1415
1416 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1417
1418 if (mClockEnabled && !updateIsTimeAccurate()) {
1419 mTimeCheckThread = new TimeCheckThread(this);
1420 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1421 }
1422
1423 if (mAnimation->dynamicColoringEnabled) {
1424 initDynamicColors();
1425 }
1426
1427 playAnimation(*mAnimation);
1428
1429 if (mTimeCheckThread != nullptr) {
1430 mTimeCheckThread->requestExit();
1431 mTimeCheckThread = nullptr;
1432 }
1433
1434 if (clockFontInitialized) {
1435 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
1436 }
1437
1438 releaseAnimation(mAnimation);
1439 mAnimation = nullptr;
1440
1441 return false;
1442 }
1443
shouldStopPlayingPart(const Animation::Part & part,const int fadedFramesCount,const int lastDisplayedProgress)1444 bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1445 const int fadedFramesCount,
1446 const int lastDisplayedProgress) {
1447 // stop playing only if it is time to exit and it's a partial part which has been faded out
1448 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1449 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
1450 }
1451
1452 // Linear mapping from range <a1, a2> to range <b1, b2>
mapLinear(float x,float a1,float a2,float b1,float b2)1453 float mapLinear(float x, float a1, float a2, float b1, float b2) {
1454 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1455 }
1456
drawTexturedQuad(float xStart,float yStart,float width,float height)1457 void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1458 // Map coordinates from screen space to world space.
1459 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1460 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1461 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1462 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1463 // Update quad vertex positions.
1464 quadPositions[0] = x0;
1465 quadPositions[1] = y0;
1466 quadPositions[2] = x1;
1467 quadPositions[3] = y0;
1468 quadPositions[4] = x1;
1469 quadPositions[5] = y1;
1470 quadPositions[6] = x1;
1471 quadPositions[7] = y1;
1472 quadPositions[8] = x0;
1473 quadPositions[9] = y1;
1474 quadPositions[10] = x0;
1475 quadPositions[11] = y0;
1476 glDrawArrays(GL_TRIANGLES, 0,
1477 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1478 }
1479
initDynamicColors()1480 void BootAnimation::initDynamicColors() {
1481 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1482 const auto syspropName = "persist.bootanim.color" + std::to_string(i + 1);
1483 const auto syspropValue = android::base::GetProperty(syspropName, "");
1484 if (syspropValue != "") {
1485 SLOGI("Loaded dynamic color: %s -> %s", syspropName.c_str(), syspropValue.c_str());
1486 mDynamicColorsApplied = true;
1487 }
1488 parseColorDecimalString(syspropValue,
1489 mAnimation->endColors[i], mAnimation->startColors[i]);
1490 }
1491 glUseProgram(mImageShader);
1492 SLOGI("Dynamically coloring boot animation. Sysprops loaded? %i", mDynamicColorsApplied);
1493 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1494 float *startColor = mAnimation->startColors[i];
1495 float *endColor = mAnimation->endColors[i];
1496 glUniform3f(glGetUniformLocation(mImageShader,
1497 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
1498 startColor[0], startColor[1], startColor[2]);
1499 glUniform3f(glGetUniformLocation(mImageShader,
1500 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
1501 endColor[0], endColor[1], endColor[2]);
1502 }
1503 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1504 }
1505
playAnimation(const Animation & animation)1506 bool BootAnimation::playAnimation(const Animation& animation) {
1507 const size_t pcount = animation.parts.size();
1508 nsecs_t frameDuration = s2ns(1) / animation.fps;
1509
1510 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1511 elapsedRealtime());
1512
1513 int fadedFramesCount = 0;
1514 int lastDisplayedProgress = 0;
1515 int colorTransitionStart = animation.colorTransitionStart;
1516 int colorTransitionEnd = animation.colorTransitionEnd;
1517 for (size_t i=0 ; i<pcount ; i++) {
1518 const Animation::Part& part(animation.parts[i]);
1519 const size_t fcount = part.frames.size();
1520
1521 // Handle animation package
1522 if (part.animation != nullptr) {
1523 playAnimation(*part.animation);
1524 if (exitPending())
1525 break;
1526 continue; //to next part
1527 }
1528
1529 // process the part not only while the count allows but also if already fading
1530 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
1531 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
1532
1533 // It's possible that the sysprops were not loaded yet at this boot phase.
1534 // If that's the case, then we should keep trying until they are available.
1535 if (animation.dynamicColoringEnabled && !mDynamicColorsApplied
1536 && (part.useDynamicColoring || part.postDynamicColoring)) {
1537 SLOGD("Trying to load dynamic color sysprops.");
1538 initDynamicColors();
1539 if (mDynamicColorsApplied) {
1540 // Sysprops were loaded. Next step is to adjust the animation if we loaded
1541 // the colors after the animation should have started.
1542 const int transitionLength = colorTransitionEnd - colorTransitionStart;
1543 if (part.postDynamicColoring) {
1544 colorTransitionStart = 0;
1545 colorTransitionEnd = fmin(transitionLength, fcount - 1);
1546 }
1547 }
1548 }
1549
1550 mCallbacks->playPart(i, part, r);
1551
1552 glClearColor(
1553 part.backgroundColor[0],
1554 part.backgroundColor[1],
1555 part.backgroundColor[2],
1556 1.0f);
1557
1558 ALOGD("Playing files = %s/%s, Requested repeat = %d, playUntilComplete = %s",
1559 animation.fileName.string(), part.path.string(), part.count,
1560 part.playUntilComplete ? "true" : "false");
1561
1562 // For the last animation, if we have progress indicator from
1563 // the system, display it.
1564 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1565 bool displayProgress = animation.progressEnabled &&
1566 (i == (pcount -1)) && currentProgress != 0;
1567
1568 for (size_t j=0 ; j<fcount ; j++) {
1569 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
1570
1571 // Color progress is
1572 // - the animation progress, normalized from
1573 // [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1574 // part.
1575 // - 0 for parts that come before,
1576 // - 1 for parts that come after.
1577 float colorProgress = part.useDynamicColoring
1578 ? fmin(fmax(
1579 ((float)j - colorTransitionStart) /
1580 fmax(colorTransitionEnd - colorTransitionStart, 1.0f), 0.0f), 1.0f)
1581 : (part.postDynamicColoring ? 1 : 0);
1582
1583 processDisplayEvents();
1584
1585 const double ratio_w = static_cast<double>(mWidth) / mInitWidth;
1586 const double ratio_h = static_cast<double>(mHeight) / mInitHeight;
1587 const int animationX = (mWidth - animation.width * ratio_w) / 2;
1588 const int animationY = (mHeight - animation.height * ratio_h) / 2;
1589
1590 const Animation::Frame& frame(part.frames[j]);
1591 nsecs_t lastFrame = systemTime();
1592
1593 if (r > 0) {
1594 glBindTexture(GL_TEXTURE_2D, frame.tid);
1595 } else {
1596 glGenTextures(1, &frame.tid);
1597 glBindTexture(GL_TEXTURE_2D, frame.tid);
1598 int w, h;
1599 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1600 // of transparent pixels are preserved.
1601 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
1602 }
1603
1604 const int trimWidth = frame.trimWidth * ratio_w;
1605 const int trimHeight = frame.trimHeight * ratio_h;
1606 const int trimX = frame.trimX * ratio_w;
1607 const int trimY = frame.trimY * ratio_h;
1608 const int xc = animationX + trimX;
1609 const int yc = animationY + trimY;
1610 glClear(GL_COLOR_BUFFER_BIT);
1611 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1612 // which is equivalent to mHeight - (yc + frame.trimHeight)
1613 const int frameDrawY = mHeight - (yc + trimHeight);
1614
1615 float fade = 0;
1616 // if the part hasn't been stopped yet then continue fading if necessary
1617 if (exitPending() && part.hasFadingPhase()) {
1618 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
1619 if (fadedFramesCount >= part.framesToFadeCount) {
1620 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1621 }
1622 }
1623 glUseProgram(mImageShader);
1624 glUniform1i(mImageTextureLocation, 0);
1625 glUniform1f(mImageFadeLocation, fade);
1626 if (animation.dynamicColoringEnabled) {
1627 glUniform1f(mImageColorProgressLocation, colorProgress);
1628 }
1629 glEnable(GL_BLEND);
1630 drawTexturedQuad(xc, frameDrawY, trimWidth, trimHeight);
1631 glDisable(GL_BLEND);
1632
1633 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1634 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
1635 }
1636
1637 if (displayProgress) {
1638 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1639 // In case the new progress jumped suddenly, still show an
1640 // increment of 1.
1641 if (lastDisplayedProgress != 100) {
1642 // Artificially sleep 1/10th a second to slow down the animation.
1643 usleep(100000);
1644 if (lastDisplayedProgress < newProgress) {
1645 lastDisplayedProgress++;
1646 }
1647 }
1648 // Put the progress percentage right below the animation.
1649 int posY = animation.height / 3;
1650 int posX = TEXT_CENTER_VALUE;
1651 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1652 }
1653
1654 handleViewport(frameDuration);
1655
1656 eglSwapBuffers(mDisplay, mSurface);
1657
1658 nsecs_t now = systemTime();
1659 nsecs_t delay = frameDuration - (now - lastFrame);
1660 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
1661 lastFrame = now;
1662
1663 if (delay > 0) {
1664 struct timespec spec;
1665 spec.tv_sec = (now + delay) / 1000000000;
1666 spec.tv_nsec = (now + delay) % 1000000000;
1667 int err;
1668 do {
1669 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
1670 } while (err == EINTR);
1671 }
1672
1673 checkExit();
1674 }
1675
1676 usleep(part.pause * ns2us(frameDuration));
1677
1678 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1679 !part.hasFadingPhase()) {
1680 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1681 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1682 continue;
1683 }
1684 break; // exit the infinite non-fading part when it has been played at least once
1685 }
1686 }
1687 }
1688
1689 // Free textures created for looping parts now that the animation is done.
1690 for (const Animation::Part& part : animation.parts) {
1691 if (part.count != 1) {
1692 const size_t fcount = part.frames.size();
1693 for (size_t j = 0; j < fcount; j++) {
1694 const Animation::Frame& frame(part.frames[j]);
1695 glDeleteTextures(1, &frame.tid);
1696 }
1697 }
1698 }
1699
1700 ALOGD("%sAnimationShownTiming End time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1701 elapsedRealtime());
1702
1703 return true;
1704 }
1705
processDisplayEvents()1706 void BootAnimation::processDisplayEvents() {
1707 // This will poll mDisplayEventReceiver and if there are new events it'll call
1708 // displayEventCallback synchronously.
1709 mLooper->pollOnce(0);
1710 }
1711
handleViewport(nsecs_t timestep)1712 void BootAnimation::handleViewport(nsecs_t timestep) {
1713 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1714 return;
1715 }
1716 if (mTargetInset < 0) {
1717 // Poll the amount for the top display inset. This will return -1 until persistent properties
1718 // have been loaded.
1719 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1720 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1721 }
1722 if (mTargetInset <= 0) {
1723 return;
1724 }
1725
1726 if (mCurrentInset < mTargetInset) {
1727 // After the device boots, the inset will effectively be cropped away. We animate this here.
1728 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1729 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1730
1731 SurfaceComposerClient::Transaction()
1732 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1733 .apply();
1734 } else {
1735 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1736 // later. This changes the coordinate system, and means we must move the surface up by
1737 // the inset amount.
1738 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1739 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1740
1741 SurfaceComposerClient::Transaction t;
1742 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1743 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
1744 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
1745 t.apply();
1746
1747 mTargetInset = mCurrentInset = 0;
1748 }
1749
1750 int delta = timestep * mTargetInset / ms2ns(200);
1751 mCurrentInset += delta;
1752 }
1753
releaseAnimation(Animation * animation) const1754 void BootAnimation::releaseAnimation(Animation* animation) const {
1755 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1756 e = animation->parts.end(); it != e; ++it) {
1757 if (it->animation)
1758 releaseAnimation(it->animation);
1759 }
1760 if (animation->zip)
1761 delete animation->zip;
1762 delete animation;
1763 }
1764
loadAnimation(const String8 & fn)1765 BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
1766 if (mLoadedFiles.indexOf(fn) >= 0) {
1767 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
1768 fn.string());
1769 return nullptr;
1770 }
1771 ZipFileRO *zip = ZipFileRO::open(fn);
1772 if (zip == nullptr) {
1773 SLOGE("Failed to open animation zip \"%s\": %s",
1774 fn.string(), strerror(errno));
1775 return nullptr;
1776 }
1777
1778 ALOGD("%s is loaded successfully", fn.string());
1779
1780 Animation *animation = new Animation;
1781 animation->fileName = fn;
1782 animation->zip = zip;
1783 animation->clockFont.map = nullptr;
1784 mLoadedFiles.add(animation->fileName);
1785
1786 parseAnimationDesc(*animation);
1787 if (!preloadZip(*animation)) {
1788 releaseAnimation(animation);
1789 return nullptr;
1790 }
1791
1792 mLoadedFiles.remove(fn);
1793 return animation;
1794 }
1795
updateIsTimeAccurate()1796 bool BootAnimation::updateIsTimeAccurate() {
1797 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1798 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1799
1800 if (mTimeIsAccurate) {
1801 return true;
1802 }
1803 if (mShuttingDown) return true;
1804 struct stat statResult;
1805
1806 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1807 mTimeFormat12Hour = true;
1808 }
1809
1810 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1811 mTimeIsAccurate = true;
1812 return true;
1813 }
1814
1815 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
1816 if (file != nullptr) {
1817 long long lastChangedTime = 0;
1818 fscanf(file, "%lld", &lastChangedTime);
1819 fclose(file);
1820 if (lastChangedTime > 0) {
1821 struct timespec now;
1822 clock_gettime(CLOCK_REALTIME, &now);
1823 // Match the Java timestamp format
1824 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
1825 if (ACCURATE_TIME_EPOCH < rtcNow
1826 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1827 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
1828 mTimeIsAccurate = true;
1829 }
1830 }
1831 }
1832
1833 return mTimeIsAccurate;
1834 }
1835
TimeCheckThread(BootAnimation * bootAnimation)1836 BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1837 mInotifyFd(-1), mBootAnimWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1838
~TimeCheckThread()1839 BootAnimation::TimeCheckThread::~TimeCheckThread() {
1840 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1841 close(mInotifyFd);
1842 }
1843
threadLoop()1844 bool BootAnimation::TimeCheckThread::threadLoop() {
1845 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1846 && mBootAnimation->mClockEnabled;
1847 if (!shouldLoop) {
1848 close(mInotifyFd);
1849 mInotifyFd = -1;
1850 }
1851 return shouldLoop;
1852 }
1853
doThreadLoop()1854 bool BootAnimation::TimeCheckThread::doThreadLoop() {
1855 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1856
1857 // Poll instead of doing a blocking read so the Thread can exit if requested.
1858 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1859 ssize_t pollResult = poll(&pfd, 1, 1000);
1860
1861 if (pollResult == 0) {
1862 return true;
1863 } else if (pollResult < 0) {
1864 SLOGE("Could not poll inotify events");
1865 return false;
1866 }
1867
1868 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1869 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1870 if (length == 0) {
1871 return true;
1872 } else if (length < 0) {
1873 SLOGE("Could not read inotify events");
1874 return false;
1875 }
1876
1877 const struct inotify_event *event;
1878 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1879 event = (const struct inotify_event *) ptr;
1880 if (event->wd == mBootAnimWd && strcmp(BOOTANIM_TIME_DIR_NAME, event->name) == 0) {
1881 addTimeDirWatch();
1882 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1883 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1884 return !mBootAnimation->updateIsTimeAccurate();
1885 }
1886 }
1887
1888 return true;
1889 }
1890
addTimeDirWatch()1891 void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1892 mTimeWd = inotify_add_watch(mInotifyFd, BOOTANIM_TIME_DIR_PATH,
1893 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1894 if (mTimeWd > 0) {
1895 // No need to watch for the time directory to be created if it already exists
1896 inotify_rm_watch(mInotifyFd, mBootAnimWd);
1897 mBootAnimWd = -1;
1898 }
1899 }
1900
readyToRun()1901 status_t BootAnimation::TimeCheckThread::readyToRun() {
1902 mInotifyFd = inotify_init();
1903 if (mInotifyFd < 0) {
1904 SLOGE("Could not initialize inotify fd");
1905 return NO_INIT;
1906 }
1907
1908 mBootAnimWd = inotify_add_watch(mInotifyFd, BOOTANIM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1909 if (mBootAnimWd < 0) {
1910 close(mInotifyFd);
1911 mInotifyFd = -1;
1912 SLOGE("Could not add watch for %s: %s", BOOTANIM_DATA_DIR_PATH, strerror(errno));
1913 return NO_INIT;
1914 }
1915
1916 addTimeDirWatch();
1917
1918 if (mBootAnimation->updateIsTimeAccurate()) {
1919 close(mInotifyFd);
1920 mInotifyFd = -1;
1921 return ALREADY_EXISTS;
1922 }
1923
1924 return NO_ERROR;
1925 }
1926
1927 // ---------------------------------------------------------------------------
1928
1929 } // namespace android
1930