blob: a8b6c0b708045a2a155d74a55a2969b0573c501b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -070017#define LOG_NDEBUG 0
Mathias Agopianbc726112009-09-23 15:44:05 -070018#define LOG_TAG "BootAnimation"
19
Nikita Ioffe06c986e2020-01-27 17:16:03 +000020#include <vector>
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022#include <stdint.h>
Wei Wanga90c54c2017-02-02 11:35:21 -080023#include <inttypes.h>
Damien Bargiacchi97480862016-03-29 14:55:55 -070024#include <sys/inotify.h>
25#include <sys/poll.h>
26#include <sys/stat.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#include <sys/types.h>
28#include <math.h>
29#include <fcntl.h>
30#include <utils/misc.h>
Mathias Agopianb4d5a722009-09-23 17:05:19 -070031#include <signal.h>
Elliott Hughesbb94f312014-10-21 10:41:33 -070032#include <time.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033
Steven Morelandfb7952f2018-02-23 14:58:50 -080034#include <cutils/atomic.h>
Jason parksbd9a08d2011-01-31 15:04:34 -060035#include <cutils/properties.h>
36
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -040037#include <android/imagedecoder.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080038#include <androidfw/AssetManager.h>
Mathias Agopianac31a3b2009-05-21 19:59:24 -070039#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040#include <utils/Errors.h>
41#include <utils/Log.h>
Wei Wanga90c54c2017-02-02 11:35:21 -080042#include <utils/SystemClock.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
Keun-young Parkb5938422017-03-23 13:46:24 -070044#include <android-base/properties.h>
45
Marin Shalamanovcb783ca2021-01-29 21:26:07 +010046#include <ui/DisplayMode.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047#include <ui/PixelFormat.h>
48#include <ui/Rect.h>
49#include <ui/Region.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050
Jeff Brown0b722fe2012-08-24 22:40:14 -070051#include <gui/ISurfaceComposer.h>
Marin Shalamanov9070c052020-05-18 19:05:17 +020052#include <gui/DisplayEventReceiver.h>
Mathias Agopian8335f1c2012-02-25 18:48:35 -080053#include <gui/Surface.h>
54#include <gui/SurfaceComposerClient.h>
Lucas Dupin8eedc022021-07-29 21:49:07 +000055#include <GLES2/gl2.h>
56#include <GLES2/gl2ext.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057#include <EGL/eglext.h>
58
59#include "BootAnimation.h"
60
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +090061#define ANIM_PATH_MAX 255
62#define STR(x) #x
63#define STRTO(x) STR(x)
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065namespace android {
66
Marin Shalamanovcb783ca2021-01-29 21:26:07 +010067using ui::DisplayMode;
68
Damien Bargiacchi97480862016-03-29 14:55:55 -070069static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
Beverly34ffe252019-05-17 11:03:54 -040070static const char PRODUCT_BOOTANIMATION_DARK_FILE[] = "/product/media/bootanimation-dark.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090071static const char PRODUCT_BOOTANIMATION_FILE[] = "/product/media/bootanimation.zip";
Damien Bargiacchi97480862016-03-29 14:55:55 -070072static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
Anders Fridlunde0b4d232018-11-06 14:23:25 +010073static const char APEX_BOOTANIMATION_FILE[] = "/apex/com.android.bootanimation/etc/bootanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070074static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090075static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070076static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
77
Nikita Ioffe06c986e2020-01-27 17:16:03 +000078static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
79static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
80static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
81
Josh Yangf95b2002021-12-23 14:32:28 -080082static const char BOOTANIM_DATA_DIR_PATH[] = "/data/bootanim";
83static const char BOOTANIM_TIME_DIR_NAME[] = "time";
84static const char BOOTANIM_TIME_DIR_PATH[] = "/data/bootanim/time";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070085static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
86static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +000087static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
88static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
Damien Bargiacchi97480862016-03-29 14:55:55 -070089static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
Josh Yangf95b2002021-12-23 14:32:28 -080090static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/bootanim/time/last_time_change";
Damien Bargiacchi97480862016-03-29 14:55:55 -070091static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
Josh Yangf95b2002021-12-23 14:32:28 -080092static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/bootanim/time/time_is_accurate";
93static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/bootanim/time/time_format_12_hour";
Damien Bargiacchi96762812016-07-12 15:53:40 -070094// Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
95static const long long ACCURATE_TIME_EPOCH = 946684800000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070096static constexpr char FONT_BEGIN_CHAR = ' ';
97static constexpr char FONT_END_CHAR = '~' + 1;
98static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
99static constexpr size_t FONT_NUM_COLS = 16;
100static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
101static const int TEXT_CENTER_VALUE = INT_MAX;
102static const int TEXT_MISSING_VALUE = INT_MIN;
Damien Bargiacchi97480862016-03-29 14:55:55 -0700103static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000104static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
Huihong Luod4a217e2020-01-16 15:56:33 -0800105static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
Thiébaud Weksteen08de4432021-11-18 13:25:59 +1100106static const char CLOCK_ENABLED_PROP_NAME[] = "persist.sys.bootanim.clock.enabled";
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +0900107static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
niuwenchao9cd6ac82022-12-23 17:34:22 +0800108static const int MAX_CHECK_EXIT_INTERVAL_US = 50000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700109static constexpr size_t TEXT_POS_LEN_MAX = 16;
Shan Huang2b31a362021-08-16 16:45:39 +0000110static const int DYNAMIC_COLOR_COUNT = 4;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000111static const char U_TEXTURE[] = "uTexture";
112static const char U_FADE[] = "uFade";
113static const char U_CROP_AREA[] = "uCropArea";
Shan Huang2b31a362021-08-16 16:45:39 +0000114static const char U_START_COLOR_PREFIX[] = "uStartColor";
115static const char U_END_COLOR_PREFIX[] = "uEndColor";
116static const char U_COLOR_PROGRESS[] = "uColorProgress";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000117static const char A_UV[] = "aUv";
118static const char A_POSITION[] = "aPosition";
119static 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 })";
Shan Huang2b31a362021-08-16 16:45:39 +0000128static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
129 precision mediump float;
Shan Huang81846ba2021-09-07 19:07:47 +0000130 const float cWhiteMaskThreshold = 0.05;
Shan Huang2b31a362021-08-16 16:45:39 +0000131 uniform sampler2D uTexture;
132 uniform float uFade;
133 uniform float uColorProgress;
Andrew Zengf9f58222022-11-08 11:10:48 -0800134 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;
Shan Huang2b31a362021-08-16 16:45:39 +0000142 varying highp vec2 vUv;
143 void main() {
144 vec4 mask = texture2D(uTexture, vUv);
Shan Huang488ff742021-08-25 20:10:46 +0000145 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);
Andrew Zengf9f58222022-11-08 11:10:48 -0800154 vec3 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
Shan Huang488ff742021-08-25 20:10:46 +0000155 + g * mix(uStartColor1, uEndColor1, uColorProgress)
156 + b * mix(uStartColor2, uEndColor2, uColorProgress)
157 + a * mix(uStartColor3, uEndColor3, uColorProgress);
Andrew Zengf9f58222022-11-08 11:10:48 -0800158 color = mix(color, vec3((r + g + b + a) * 0.25), useWhiteMask);
159 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade));
Shan Huang2b31a362021-08-16 16:45:39 +0000160 })";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000161static 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);
Shan Huang2b31a362021-08-16 16:45:39 +0000168 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000169 })";
170static 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
181static 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};
189static 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};
Narayan Kamathafd31e02013-12-03 13:16:03 +0000197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198// ---------------------------------------------------------------------------
199
Ed Coyne7464ac92017-06-08 12:26:48 -0700200BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200201 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700202 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700203 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400204
Keun-young Parkb5938422017-03-23 13:46:24 -0700205 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
206 if (powerCtl.empty()) {
207 mShuttingDown = false;
208 } else {
209 mShuttingDown = true;
210 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700211 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
212 elapsedRealtime());
213}
214
215BootAnimation::~BootAnimation() {
216 if (mAnimation != nullptr) {
217 releaseAnimation(mAnimation);
218 mAnimation = nullptr;
219 }
220 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
221 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222}
223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700225 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700226 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700227 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700228 // 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());
Mathias Agopianbc726112009-09-23 15:44:05 -0700235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236}
237
Mathias Agopianbc726112009-09-23 15:44:05 -0700238sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 return mSession;
240}
241
Marin Shalamanov9070c052020-05-18 19:05:17 +0200242void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700243 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700244 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700245
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
Shan Huang2b31a362021-08-16 16:45:39 +0000252static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
253 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400254 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
Shan Huang2b31a362021-08-16 16:45:39 +0000267 if (!premultiplyAlpha) {
268 AImageDecoder_setUnpremultipliedRequired(decoder, true);
269 }
270
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400271 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
Shan Huang2b31a362021-08-16 16:45:39 +0000284 const char* name, bool premultiplyAlpha) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700286 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400288
289 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000290 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
291 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400292 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 asset->close();
295 delete asset;
296
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400297 if (!pixels) {
298 return NO_INIT;
299 }
300
301 const int w = bitmapInfo.width;
302 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 texture->w = w;
305 texture->h = h;
306
307 glGenTextures(1, &texture->name);
308 glBindTexture(GL_TEXTURE_2D, texture->name);
309
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400310 switch (bitmapInfo.format) {
311 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400313 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400315 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400317 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400319 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400321 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400323 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400325 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 break;
327 default:
328 break;
329 }
330
Lucas Dupin8eedc022021-07-29 21:49:07 +0000331 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);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 return NO_ERROR;
337}
338
Shan Huang2b31a362021-08-16 16:45:39 +0000339status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
340 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400341 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000342 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
343 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400344 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700345
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200346 // 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.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700349 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200350
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400351 if (!pixels) {
352 return NO_INIT;
353 }
354
355 const int w = bitmapInfo.width;
356 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700357
Mathias Agopiana8826d62009-10-01 03:10:14 -0700358 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
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400363 switch (bitmapInfo.format) {
364 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530365 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700366 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700367 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700368 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400369 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700370 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530371 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400372 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700373 }
374 break;
375
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400376 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530377 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700378 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700379 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700380 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400381 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700382 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530383 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400384 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700385 }
386 break;
387 default:
388 break;
389 }
390
Lucas Dupin8eedc022021-07-29 21:49:07 +0000391 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);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700395
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700396 *width = w;
397 *height = h;
398
Mathias Agopiana8826d62009-10-01 03:10:14 -0700399 return NO_ERROR;
400}
401
Marin Shalamanov9070c052020-05-18 19:05:17 +0200402class BootAnimation::DisplayEventCallback : public LooperCallback {
403 BootAnimation* mBootAnimation;
404
405public:
406 DisplayEventCallback(BootAnimation* bootAnimation) {
407 mBootAnimation = bootAnimation;
408 }
409
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
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100444 DisplayMode displayMode;
445 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
446 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200447 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100448 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200449 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100450 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
451 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200452 }
453 }
454 } while (numEvents > 0);
455
456 return 1; // keep the callback
457 }
458};
459
460EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
461 const EGLint attribs[] = {
Andrii Chepurnyid93f7b22023-03-15 11:22:07 +0200462 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
Marin Shalamanov9070c052020-05-18 19:05:17 +0200463 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
Marin Shalamanov047802d2020-05-19 23:55:12 +0200475ui::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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494status_t BootAnimation::readyToRun() {
495 mAssets.addDefaultAssets();
496
Huihong Luo44305102022-09-26 11:16:20 -0700497 const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds();
498 if (ids.empty()) {
499 SLOGE("Failed to get ID for any displays\n");
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800500 return NAME_NOT_FOUND;
Huihong Luo44305102022-09-26 11:16:20 -0700501 }
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800502
Huihong Luo44305102022-09-26 11:16:20 -0700503 // this system property specifies multi-display IDs to show the boot animation
Huihong Luof97c9e22019-05-29 11:08:01 -0700504 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800505 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200506 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700507 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800508 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700509 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)
Huihong Luod4a217e2020-01-16 15:56:33 -0800520 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700521 }
522 if (isValid) {
523 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200524 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700525 physicalDisplayIds.add(id);
526 if (stream.peek() == ',')
527 stream.ignore();
528 }
529
Huihong Luo44305102022-09-26 11:16:20 -0700530 // 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) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700567 // In the case of multi-display, boot animation shows on the specified displays
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700568 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700569 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700570 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
571 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
572 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700573 }
574 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700575 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700576 }
577
Robert Carre13b58e2017-08-31 14:50:44 -0700578 t.setLayer(control, 0x40000000)
579 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580
Mathias Agopian17f638b2009-04-16 20:04:08 -0700581 sp<Surface> s = control->getSurface();
582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700585 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200586 EGLConfig config = getEglConfig(display);
587 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000588 // 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);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200591 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 eglQuerySurface(display, surface, EGL_WIDTH, &w);
593 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700594
Huihong Luo44305102022-09-26 11:16:20 -0700595 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
Mathias Agopianabac0102009-07-31 14:47:00 -0700596 return NO_INIT;
Huihong Luo44305102022-09-26 11:16:20 -0700597 }
Mathias Agopiana8826d62009-10-01 03:10:14 -0700598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 mDisplay = display;
600 mContext = context;
601 mSurface = surface;
joenchen764ea042022-04-11 23:58:34 +0800602 mInitWidth = mWidth = w;
603 mInitHeight = mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700604 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200606 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000608 // 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
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200617 projectSceneToWindow();
618
Marin Shalamanov9070c052020-05-18 19:05:17 +0200619 // 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
Huihong Luo50a2f362018-08-11 09:27:57 -0700627 return NO_ERROR;
628}
629
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000630void 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
652ui::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
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200674void BootAnimation::projectSceneToWindow() {
675 glViewport(0, 0, mWidth, mHeight);
676 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200677}
678
Marin Shalamanov9070c052020-05-18 19:05:17 +0200679void 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
joenchen764ea042022-04-11 23:58:34 +0800689 mFlingerSurfaceControl->updateDefaultBufferSize(newWidth, newHeight);
Marin Shalamanov047802d2020-05-19 23:55:12 +0200690 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
691 mWidth = limitedSize.width;
692 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200693
Marin Shalamanov9070c052020-05-18 19:05:17 +0200694 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 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200700
701 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200702
703 mSurface = surface;
704}
705
Huihong Luo50a2f362018-08-11 09:27:57 -0700706bool BootAnimation::preloadAnimation() {
707 findBootAnimationFile();
708 if (!mZipFileName.isEmpty()) {
709 mAnimation = loadAnimation(mZipFileName);
710 return (mAnimation != nullptr);
711 }
712
713 return false;
714}
715
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000716bool 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
Huihong Luo50a2f362018-08-11 09:27:57 -0700726void BootAnimation::findBootAnimationFile() {
Beverly34ffe252019-05-17 11:03:54 -0400727 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000728 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 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700739
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000740 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);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747}
748
Lucas Dupin8eedc022021-07-29 21:49:07 +0000749GLuint 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);
Shan Huang81846ba2021-09-07 19:07:47 +0000757 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]);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000762 return 0;
763 }
764 return shader;
765}
766
767GLuint 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
782void BootAnimation::initShaders() {
Shan Huang2b31a362021-08-16 16:45:39 +0000783 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000784 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
785 GLuint imageFragmentShader =
Shan Huang2b31a362021-08-16 16:45:39 +0000786 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
787 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
788 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000789 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
Marin Shalamanov9070c052020-05-18 19:05:17 +0200815bool BootAnimation::threadLoop() {
816 bool result;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000817 initShaders();
818
Narayan Kamathafd31e02013-12-03 13:16:03 +0000819 // We have no bootanimation file, so we use the stock android logo
820 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700821 if (mZipFileName.isEmpty()) {
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +0900822 ALOGD("No animation file");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200823 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700824 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200825 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700826 }
827
Philip Junker60600562020-11-25 18:16:16 +0100828 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
830 eglDestroyContext(mDisplay, mContext);
831 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700832 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700833 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700834 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530835 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700836 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200837 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838}
839
Marin Shalamanov9070c052020-05-18 19:05:17 +0200840bool BootAnimation::android() {
Lucas Dupin8eedc022021-07-29 21:49:07 +0000841 glActiveTexture(GL_TEXTURE0);
842
Wei Wang159a4102018-10-23 23:15:58 -0700843 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700844 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700845 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
846 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847
Ed Coyne7464ac92017-06-08 12:26:48 -0700848 mCallbacks->init({});
849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700851 glDisable(GL_DITHER);
852 glDisable(GL_SCISSOR_TEST);
Shan Huangbfd2d3c2021-09-09 23:19:04 +0000853 glUseProgram(mImageShader);
854
Mathias Agopian59f19e42011-05-06 19:22:12 -0700855 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 glClear(GL_COLOR_BUFFER_BIT);
857 eglSwapBuffers(mDisplay, mSurface);
858
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700859 // Blend state
860 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 const nsecs_t startTime = systemTime();
863 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200864 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
Mathias Agopian13796652009-03-24 22:49:21 -0700871 nsecs_t now = systemTime();
872 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700873 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876
Mathias Agopian81668642009-07-28 11:41:30 -0700877 glDisable(GL_SCISSOR_TEST);
878 glClear(GL_COLOR_BUFFER_BIT);
879
880 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000883 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
884 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700886 glEnable(GL_BLEND);
887 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000888 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889
Mathias Agopian627e7b52009-05-21 19:21:59 -0700890 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
891 if (res == EGL_FALSE)
892 break;
893
Mathias Agopian13796652009-03-24 22:49:21 -0700894 // 12fps: don't animate too fast to preserve CPU
895 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
896 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700897 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700898
899 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } while (!exitPending());
901
902 glDeleteTextures(1, &mAndroid[0].name);
903 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 return false;
905}
906
Kevin Hesterd3782b22012-04-26 10:38:55 -0700907void 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
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700917bool BootAnimation::validClock(const Animation::Part& part) {
918 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
919}
920
921bool 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.
937void 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
Jesse Hall083b84c2014-09-22 10:51:09 -0700958// 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.
965static 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
Shan Huang2b31a362021-08-16 16:45:39 +0000983// 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.
986static 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}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700997
Marin Shalamanov9070c052020-05-18 19:05:17 +0200998static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700999 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -07001000 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001001 if (!entry) {
1002 return false;
1003 }
1004
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001005 FileMap* entryMap = zip->createEntryFileMap(entry);
1006 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -07001007 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001008 if (!entryMap) {
1009 return false;
1010 }
1011
1012 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +00001013 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001014 return true;
1015}
1016
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001017// 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.
1020status_t BootAnimation::initFont(Font* font, const char* fallback) {
1021 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001022
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001023 if (font->map != nullptr) {
1024 glGenTextures(1, &font->texture.name);
1025 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001026
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001027 status = initTexture(font->map, &font->texture.w, &font->texture.h);
1028
Lucas Dupin8eedc022021-07-29 21:49:07 +00001029 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);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001033 } else if (fallback != nullptr) {
1034 status = initTexture(&font->texture, mAssets, fallback);
1035 } else {
1036 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001037 }
1038
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001039 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
1047void 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);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001050 glUseProgram(mTextShader);
1051 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001052
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
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001067 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;
Lucas Dupin8eedc022021-07-29 21:49:07 +00001078 // 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);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001085
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
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001093// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001094void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001095 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1096 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001097 static constexpr int TIME_LENGTH = 6;
1098
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001099 time_t rawtime;
1100 time(&rawtime);
1101 struct tm* timeInfo = localtime(&rawtime);
1102
1103 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001104 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1105 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001106
1107 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001108 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001109 mClockEnabled = false;
1110 return;
1111 }
1112
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001113 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001114 int x = xPos;
1115 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001116 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001117}
1118
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001119void 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
Marin Shalamanov9070c052020-05-18 19:05:17 +02001131bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001132 String8 desString;
1133
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001134 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001135 return false;
1136 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001137 char const* s = desString.string();
Shan Huang2b31a362021-08-16 16:45:39 +00001138 std::string dynamicColoringPartName = "";
1139 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001140
Mathias Agopiana8826d62009-10-01 03:10:14 -07001141 // Parse the description file
1142 for (;;) {
1143 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001144 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001145 String8 line(s, endl - s);
1146 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001147 int fps = 0;
1148 int width = 0;
1149 int height = 0;
1150 int count = 0;
1151 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001152 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001153 int framesToFadeCount = 0;
Shan Huang488ff742021-08-25 20:10:46 +00001154 int colorTransitionStart = 0;
1155 int colorTransitionEnd = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001156 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001157 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001158 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1159 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang2b31a362021-08-16 16:45:39 +00001160 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001161 char pathType;
Shan Huang2b31a362021-08-16 16:45:39 +00001162 // 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";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001167
1168 int nextReadPos;
1169
yidong zhang87bb3462022-12-07 15:55:31 +08001170 if (strlen(l) == 0) {
1171 s = ++endl;
1172 continue;
1173 }
1174
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001175 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);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001178 animation.width = width;
1179 animation.height = height;
1180 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001181 if (topLineNumbers == 4) {
1182 animation.progressEnabled = (progress != 0);
1183 } else {
1184 animation.progressEnabled = false;
1185 }
Shan Huang488ff742021-08-25 20:10:46 +00001186 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
Shan Huang2b31a362021-08-16 16:45:39 +00001187 dynamicColoringPartNameBuffer,
Shan Huang488ff742021-08-25 20:10:46 +00001188 start_color_0, start_color_1, start_color_2, start_color_3,
1189 &colorTransitionStart, &colorTransitionEnd)) {
Shan Huang2b31a362021-08-16 16:45:39 +00001190 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]);
Shan Huang488ff742021-08-25 20:10:46 +00001195 animation.colorTransitionStart = colorTransitionStart;
1196 animation.colorTransitionEnd = colorTransitionEnd;
Shan Huang2b31a362021-08-16 16:45:39 +00001197 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001198 } 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);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001209 Animation::Part part;
Shan Huang2b31a362021-08-16 16:45:39 +00001210 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 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001220 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001221 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001222 part.count = count;
1223 part.pause = pause;
1224 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001225 part.audioData = nullptr;
1226 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001227 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001228 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001229 part.backgroundColor[0] = 0.0f;
1230 part.backgroundColor[1] = 0.0f;
1231 part.backgroundColor[2] = 0.0f;
1232 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001233 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001234 animation.parts.add(part);
1235 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001236 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001237 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001238 Animation::Part part;
1239 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001240 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001241 part.count = 1;
1242 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001243 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001244 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001245 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001246 animation.parts.add(part);
1247 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001248 s = ++endl;
1249 }
1250
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001251 return true;
1252}
1253
Marin Shalamanov9070c052020-05-18 19:05:17 +02001254bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001255 // read all the data structures
1256 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001257 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001258 ZipFileRO* zip = animation.zip;
1259 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001260 return false;
1261 }
1262
1263 ZipEntryRO entry;
1264 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001265 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001266 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001267 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001268 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001269 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) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001276 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
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001284 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
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001292 for (size_t j = 0; j < pcount; j++) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001293 if (path == animation.parts[j].path) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001294 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001295 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001296 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001297 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001298 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001299 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001300 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001301 if (leaf == "audio.wav") {
1302 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001303 part.audioData = (uint8_t *)map->getDataPtr();
1304 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001305 } else if (leaf == "trim.txt") {
1306 part.trimData.setTo((char const*)map->getDataPtr(),
1307 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001308 } else {
1309 Animation::Frame frame;
1310 frame.name = leaf;
1311 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001312 frame.trimWidth = animation.width;
1313 frame.trimHeight = animation.height;
1314 frame.trimX = 0;
1315 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001316 part.frames.add(frame);
1317 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001318 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001319 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001320 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001321 }
1322 }
1323 }
1324 }
1325 }
1326 }
1327
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001328 // 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.
Yi Kong911ac232019-03-24 01:49:02 -07001334 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001335 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 {
Wei Wang159a4102018-10-23 23:15:58 -07001348 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001349 break;
1350 }
1351 }
1352 }
1353
1354 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001355
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001356 return true;
1357}
1358
Marin Shalamanov9070c052020-05-18 19:05:17 +02001359bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001360 if (mAnimation == nullptr) {
1361 mAnimation = loadAnimation(mZipFileName);
1362 }
1363
1364 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001365 return false;
1366
Huihong Luo50a2f362018-08-11 09:27:57 -07001367 // 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
Damien Bargiacchi97480862016-03-29 14:55:55 -07001376 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001377 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1378 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001379 anyPartHasClock = true;
1380 break;
1381 }
1382 }
1383 if (!anyPartHasClock) {
1384 mClockEnabled = false;
Thiébaud Weksteen08de4432021-11-18 13:25:59 +11001385 } else if (!android::base::GetBoolProperty(CLOCK_ENABLED_PROP_NAME, false)) {
1386 mClockEnabled = false;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001387 }
1388
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301389 // 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
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001403 // Blend required to draw time on top of animation frames.
1404 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001405 glDisable(GL_DITHER);
1406 glDisable(GL_SCISSOR_TEST);
1407 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001408
Greg Kaiser2ded8002021-07-19 17:03:27 +00001409 glEnable(GL_TEXTURE_2D);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001410 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);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001415 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001416 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001417 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001418 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001419 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001420 }
1421
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001422 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1423
Damien Bargiacchi97480862016-03-29 14:55:55 -07001424 if (mClockEnabled && !updateIsTimeAccurate()) {
1425 mTimeCheckThread = new TimeCheckThread(this);
1426 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1427 }
1428
George Burgess IV0f8e8112021-08-23 17:32:23 -07001429 if (mAnimation->dynamicColoringEnabled) {
Shan Huang7fee3522021-08-18 00:56:08 +00001430 initDynamicColors();
1431 }
1432
Huihong Luo50a2f362018-08-11 09:27:57 -07001433 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001434
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001435 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001436 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001437 mTimeCheckThread = nullptr;
1438 }
1439
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001440 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001441 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001442 }
1443
Huihong Luo50a2f362018-08-11 09:27:57 -07001444 releaseAnimation(mAnimation);
1445 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001446
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001447 return false;
1448}
1449
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001450bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1451 const int fadedFramesCount,
1452 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001453 // stop playing only if it is time to exit and it's a partial part which has been faded out
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001454 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1455 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001456}
1457
Lucas Dupin8eedc022021-07-29 21:49:07 +00001458// Linear mapping from range <a1, a2> to range <b1, b2>
1459float mapLinear(float x, float a1, float a2, float b1, float b2) {
1460 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1461}
1462
1463void 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
Shan Huang7fee3522021-08-18 00:56:08 +00001486void BootAnimation::initDynamicColors() {
1487 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
Lucas Dupincd256842022-03-29 15:46:36 -07001488 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,
Shan Huang7fee3522021-08-18 00:56:08 +00001495 mAnimation->endColors[i], mAnimation->startColors[i]);
1496 }
1497 glUseProgram(mImageShader);
Lucas Dupincd256842022-03-29 15:46:36 -07001498 SLOGI("Dynamically coloring boot animation. Sysprops loaded? %i", mDynamicColorsApplied);
Shan Huang7fee3522021-08-18 00:56:08 +00001499 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1500 float *startColor = mAnimation->startColors[i];
1501 float *endColor = mAnimation->endColors[i];
Andrew Zengf9f58222022-11-08 11:10:48 -08001502 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001503 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001504 startColor[0], startColor[1], startColor[2]);
1505 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001506 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001507 endColor[0], endColor[1], endColor[2]);
Shan Huang7fee3522021-08-18 00:56:08 +00001508 }
1509 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1510}
1511
Marin Shalamanov9070c052020-05-18 19:05:17 +02001512bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001513 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001514 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001515
Wei Wang159a4102018-10-23 23:15:58 -07001516 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001517 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001518
1519 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001520 int lastDisplayedProgress = 0;
Lucas Dupinbfd18122022-04-25 11:26:08 -07001521 int colorTransitionStart = animation.colorTransitionStart;
1522 int colorTransitionEnd = animation.colorTransitionEnd;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001523 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001524 const Animation::Part& part(animation.parts[i]);
1525 const size_t fcount = part.frames.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001526
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001527 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001528 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001529 playAnimation(*part.animation);
1530 if (exitPending())
1531 break;
1532 continue; //to next part
1533 }
1534
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001535 // 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++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001537 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001538
Lucas Dupinbfd18122022-04-25 11:26:08 -07001539 // 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
Ed Coyne7464ac92017-06-08 12:26:48 -07001556 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001557
Jesse Hall083b84c2014-09-22 10:51:09 -07001558 glClearColor(
1559 part.backgroundColor[0],
1560 part.backgroundColor[1],
1561 part.backgroundColor[2],
1562 1.0f);
1563
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001564 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
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001568 // 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
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001574 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001575 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001576
Shan Huang2b31a362021-08-16 16:45:39 +00001577 // Color progress is
Shan Huang488ff742021-08-25 20:10:46 +00001578 // - the animation progress, normalized from
1579 // [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1580 // part.
Shan Huang2b31a362021-08-16 16:45:39 +00001581 // - 0 for parts that come before,
1582 // - 1 for parts that come after.
1583 float colorProgress = part.useDynamicColoring
Shan Huang488ff742021-08-25 20:10:46 +00001584 ? fmin(fmax(
Lucas Dupinbfd18122022-04-25 11:26:08 -07001585 ((float)j - colorTransitionStart) /
1586 fmax(colorTransitionEnd - colorTransitionStart, 1.0f), 0.0f), 1.0f)
Shan Huang2b31a362021-08-16 16:45:39 +00001587 : (part.postDynamicColoring ? 1 : 0);
1588
Marin Shalamanov9070c052020-05-18 19:05:17 +02001589 processDisplayEvents();
1590
joenchen764ea042022-04-11 23:58:34 +08001591 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;
Marin Shalamanov9070c052020-05-18 19:05:17 +02001595
Mathias Agopiana8826d62009-10-01 03:10:14 -07001596 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001597 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001598
1599 if (r > 0) {
1600 glBindTexture(GL_TEXTURE_2D, frame.tid);
1601 } else {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001602 glGenTextures(1, &frame.tid);
1603 glBindTexture(GL_TEXTURE_2D, frame.tid);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001604 int w, h;
Shan Huang2b31a362021-08-16 16:45:39 +00001605 // 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 */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001608 }
1609
joenchen764ea042022-04-11 23:58:34 +08001610 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;
Shan Huang2b31a362021-08-16 16:45:39 +00001616 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001617 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1618 // which is equivalent to mHeight - (yc + frame.trimHeight)
joenchen764ea042022-04-11 23:58:34 +08001619 const int frameDrawY = mHeight - (yc + trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001620
Lucas Dupin8eedc022021-07-29 21:49:07 +00001621 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001622 // if the part hasn't been stopped yet then continue fading if necessary
1623 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001624 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001625 if (fadedFramesCount >= part.framesToFadeCount) {
1626 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1627 }
1628 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001629 glUseProgram(mImageShader);
1630 glUniform1i(mImageTextureLocation, 0);
1631 glUniform1f(mImageFadeLocation, fade);
Shan Huang2b31a362021-08-16 16:45:39 +00001632 if (animation.dynamicColoringEnabled) {
1633 glUniform1f(mImageColorProgressLocation, colorProgress);
1634 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001635 glEnable(GL_BLEND);
joenchen764ea042022-04-11 23:58:34 +08001636 drawTexturedQuad(xc, frameDrawY, trimWidth, trimHeight);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001637 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001638
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001639 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1640 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001641 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001642
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001643 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
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001660 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001661
Mathias Agopiana8826d62009-10-01 03:10:14 -07001662 eglSwapBuffers(mDisplay, mSurface);
1663
1664 nsecs_t now = systemTime();
1665 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001666 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001667 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001668
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 {
Yi Kong911ac232019-03-24 01:49:02 -07001675 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Keith Mok0f2e6682021-11-15 05:50:32 +00001676 } while (err == EINTR);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001677 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001678
1679 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001680 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001681
niuwenchao9cd6ac82022-12-23 17:34:22 +08001682 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 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001693
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001694 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1695 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001696 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1697 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1698 continue;
1699 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001700 break; // exit the infinite non-fading part when it has been played at least once
1701 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001702 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001703 }
1704
1705 // Free textures created for looping parts now that the animation is done.
1706 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001707 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001708 const size_t fcount = part.frames.size();
1709 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001710 const Animation::Frame& frame(part.frames[j]);
1711 glDeleteTextures(1, &frame.tid);
1712 }
1713 }
1714 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001715
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001716 ALOGD("%sAnimationShownTiming End time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1717 elapsedRealtime());
1718
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001719 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001720}
1721
Marin Shalamanov9070c052020-05-18 19:05:17 +02001722void 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
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001728void 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.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001754 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));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001760 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001761 t.apply();
1762
1763 mTargetInset = mCurrentInset = 0;
1764 }
1765
1766 int delta = timestep * mTargetInset / ms2ns(200);
1767 mCurrentInset += delta;
1768}
1769
Marin Shalamanov9070c052020-05-18 19:05:17 +02001770void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001771 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
Marin Shalamanov9070c052020-05-18 19:05:17 +02001781BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001782 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001783 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001784 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001785 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001786 }
1787 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001788 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001789 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001790 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001791 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001792 }
1793
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001794 ALOGD("%s is loaded successfully", fn.string());
1795
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001796 Animation *animation = new Animation;
1797 animation->fileName = fn;
1798 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001799 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001800 mLoadedFiles.add(animation->fileName);
1801
1802 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001803 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001804 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001805 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001806 }
1807
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001808 mLoadedFiles.remove(fn);
1809 return animation;
1810}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001811
1812bool 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 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001819 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001820 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001821
1822 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1823 mTimeFormat12Hour = true;
1824 }
1825
Damien Bargiacchi97480862016-03-29 14:55:55 -07001826 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");
Yi Kong911ac232019-03-24 01:49:02 -07001832 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001833 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);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001841 if (ACCURATE_TIME_EPOCH < rtcNow
1842 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1843 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001844 mTimeIsAccurate = true;
1845 }
1846 }
1847 }
1848
1849 return mTimeIsAccurate;
1850}
1851
1852BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
Josh Yangf95b2002021-12-23 14:32:28 -08001853 mInotifyFd(-1), mBootAnimWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001854
1855BootAnimation::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
1860bool 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
1870bool 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) {
Wei Wang159a4102018-10-23 23:15:58 -07001880 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001881 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) {
Wei Wang159a4102018-10-23 23:15:58 -07001889 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001890 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;
Josh Yangf95b2002021-12-23 14:32:28 -08001896 if (event->wd == mBootAnimWd && strcmp(BOOTANIM_TIME_DIR_NAME, event->name) == 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001897 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
1907void BootAnimation::TimeCheckThread::addTimeDirWatch() {
Josh Yangf95b2002021-12-23 14:32:28 -08001908 mTimeWd = inotify_add_watch(mInotifyFd, BOOTANIM_TIME_DIR_PATH,
Damien Bargiacchi97480862016-03-29 14:55:55 -07001909 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
Josh Yangf95b2002021-12-23 14:32:28 -08001912 inotify_rm_watch(mInotifyFd, mBootAnimWd);
1913 mBootAnimWd = -1;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001914 }
1915}
1916
1917status_t BootAnimation::TimeCheckThread::readyToRun() {
1918 mInotifyFd = inotify_init();
1919 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001920 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001921 return NO_INIT;
1922 }
1923
Josh Yangf95b2002021-12-23 14:32:28 -08001924 mBootAnimWd = inotify_add_watch(mInotifyFd, BOOTANIM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1925 if (mBootAnimWd < 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001926 close(mInotifyFd);
1927 mInotifyFd = -1;
Josh Yangf95b2002021-12-23 14:32:28 -08001928 SLOGE("Could not add watch for %s: %s", BOOTANIM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001929 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943// ---------------------------------------------------------------------------
1944
Marin Shalamanov9070c052020-05-18 19:05:17 +02001945} // namespace android