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