Debian Codegraph @

cmds/bootanimation/BootAnimation.cpp

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