blob: fadf82afe8580944edd7693c55984aa13265f3a4 [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
Tomasz Wasilczyk9dcea572023-08-22 20:39:20 +000020#include <filesystem>
Nikita Ioffe06c986e2020-01-27 17:16:03 +000021#include <vector>
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023#include <stdint.h>
Wei Wanga90c54c2017-02-02 11:35:21 -080024#include <inttypes.h>
Damien Bargiacchi97480862016-03-29 14:55:55 -070025#include <sys/inotify.h>
26#include <sys/poll.h>
27#include <sys/stat.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028#include <sys/types.h>
29#include <math.h>
30#include <fcntl.h>
31#include <utils/misc.h>
Mathias Agopianb4d5a722009-09-23 17:05:19 -070032#include <signal.h>
Elliott Hughesbb94f312014-10-21 10:41:33 -070033#include <time.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034
Steven Morelandfb7952f2018-02-23 14:58:50 -080035#include <cutils/atomic.h>
Jason parksbd9a08d2011-01-31 15:04:34 -060036#include <cutils/properties.h>
37
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -040038#include <android/imagedecoder.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080039#include <androidfw/AssetManager.h>
Mathias Agopianac31a3b2009-05-21 19:59:24 -070040#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041#include <utils/Errors.h>
42#include <utils/Log.h>
Wei Wanga90c54c2017-02-02 11:35:21 -080043#include <utils/SystemClock.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
Keun-young Parkb5938422017-03-23 13:46:24 -070045#include <android-base/properties.h>
46
Marin Shalamanovcb783ca2021-01-29 21:26:07 +010047#include <ui/DisplayMode.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048#include <ui/PixelFormat.h>
49#include <ui/Rect.h>
50#include <ui/Region.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
Jeff Brown0b722fe2012-08-24 22:40:14 -070052#include <gui/ISurfaceComposer.h>
Marin Shalamanov9070c052020-05-18 19:05:17 +020053#include <gui/DisplayEventReceiver.h>
Mathias Agopian8335f1c2012-02-25 18:48:35 -080054#include <gui/Surface.h>
55#include <gui/SurfaceComposerClient.h>
Lucas Dupin8eedc022021-07-29 21:49:07 +000056#include <GLES2/gl2.h>
57#include <GLES2/gl2ext.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058#include <EGL/eglext.h>
59
60#include "BootAnimation.h"
61
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +090062#define ANIM_PATH_MAX 255
63#define STR(x) #x
64#define STRTO(x) STR(x)
65
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066namespace android {
67
Marin Shalamanovcb783ca2021-01-29 21:26:07 +010068using ui::DisplayMode;
69
Damien Bargiacchi97480862016-03-29 14:55:55 -070070static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
Beverly34ffe252019-05-17 11:03:54 -040071static const char PRODUCT_BOOTANIMATION_DARK_FILE[] = "/product/media/bootanimation-dark.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090072static const char PRODUCT_BOOTANIMATION_FILE[] = "/product/media/bootanimation.zip";
Damien Bargiacchi97480862016-03-29 14:55:55 -070073static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
Anders Fridlunde0b4d232018-11-06 14:23:25 +010074static const char APEX_BOOTANIMATION_FILE[] = "/apex/com.android.bootanimation/etc/bootanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090075static const char PRODUCT_ENCRYPTED_BOOTANIMATION_FILE[] = "/product/media/bootanimation-encrypted.zip";
Damien Bargiacchi97480862016-03-29 14:55:55 -070076static const char SYSTEM_ENCRYPTED_BOOTANIMATION_FILE[] = "/system/media/bootanimation-encrypted.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070077static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090078static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070079static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
80
Nikita Ioffe06c986e2020-01-27 17:16:03 +000081static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
82static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
83static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
84
Josh Yangf95b2002021-12-23 14:32:28 -080085static const char BOOTANIM_DATA_DIR_PATH[] = "/data/bootanim";
86static const char BOOTANIM_TIME_DIR_NAME[] = "time";
87static const char BOOTANIM_TIME_DIR_PATH[] = "/data/bootanim/time";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070088static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
89static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +000090static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
91static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
Damien Bargiacchi97480862016-03-29 14:55:55 -070092static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
Josh Yangf95b2002021-12-23 14:32:28 -080093static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/bootanim/time/last_time_change";
Damien Bargiacchi97480862016-03-29 14:55:55 -070094static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
Josh Yangf95b2002021-12-23 14:32:28 -080095static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/bootanim/time/time_is_accurate";
96static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/bootanim/time/time_format_12_hour";
Damien Bargiacchi96762812016-07-12 15:53:40 -070097// Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
98static const long long ACCURATE_TIME_EPOCH = 946684800000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070099static constexpr char FONT_BEGIN_CHAR = ' ';
100static constexpr char FONT_END_CHAR = '~' + 1;
101static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
102static constexpr size_t FONT_NUM_COLS = 16;
103static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
104static const int TEXT_CENTER_VALUE = INT_MAX;
105static const int TEXT_MISSING_VALUE = INT_MIN;
Damien Bargiacchi97480862016-03-29 14:55:55 -0700106static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000107static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
Huihong Luod4a217e2020-01-16 15:56:33 -0800108static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
Thiébaud Weksteen08de4432021-11-18 13:25:59 +1100109static const char CLOCK_ENABLED_PROP_NAME[] = "persist.sys.bootanim.clock.enabled";
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +0900110static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
niuwenchao9cd6ac82022-12-23 17:34:22 +0800111static const int MAX_CHECK_EXIT_INTERVAL_US = 50000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700112static constexpr size_t TEXT_POS_LEN_MAX = 16;
Shan Huang2b31a362021-08-16 16:45:39 +0000113static const int DYNAMIC_COLOR_COUNT = 4;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000114static const char U_TEXTURE[] = "uTexture";
115static const char U_FADE[] = "uFade";
116static const char U_CROP_AREA[] = "uCropArea";
Shan Huang2b31a362021-08-16 16:45:39 +0000117static const char U_START_COLOR_PREFIX[] = "uStartColor";
118static const char U_END_COLOR_PREFIX[] = "uEndColor";
119static const char U_COLOR_PROGRESS[] = "uColorProgress";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000120static const char A_UV[] = "aUv";
121static const char A_POSITION[] = "aPosition";
122static const char VERTEX_SHADER_SOURCE[] = R"(
123 precision mediump float;
124 attribute vec4 aPosition;
125 attribute highp vec2 aUv;
126 varying highp vec2 vUv;
127 void main() {
128 gl_Position = aPosition;
129 vUv = aUv;
130 })";
Shan Huang2b31a362021-08-16 16:45:39 +0000131static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
132 precision mediump float;
Shan Huang81846ba2021-09-07 19:07:47 +0000133 const float cWhiteMaskThreshold = 0.05;
Shan Huang2b31a362021-08-16 16:45:39 +0000134 uniform sampler2D uTexture;
135 uniform float uFade;
136 uniform float uColorProgress;
Andrew Zengf9f58222022-11-08 11:10:48 -0800137 uniform vec3 uStartColor0;
138 uniform vec3 uStartColor1;
139 uniform vec3 uStartColor2;
140 uniform vec3 uStartColor3;
141 uniform vec3 uEndColor0;
142 uniform vec3 uEndColor1;
143 uniform vec3 uEndColor2;
144 uniform vec3 uEndColor3;
Shan Huang2b31a362021-08-16 16:45:39 +0000145 varying highp vec2 vUv;
146 void main() {
147 vec4 mask = texture2D(uTexture, vUv);
Shan Huang488ff742021-08-25 20:10:46 +0000148 float r = mask.r;
149 float g = mask.g;
150 float b = mask.b;
151 float a = mask.a;
152 // If all channels have values, render pixel as a shade of white.
153 float useWhiteMask = step(cWhiteMaskThreshold, r)
154 * step(cWhiteMaskThreshold, g)
155 * step(cWhiteMaskThreshold, b)
156 * step(cWhiteMaskThreshold, a);
Andrew Zengf9f58222022-11-08 11:10:48 -0800157 vec3 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
Shan Huang488ff742021-08-25 20:10:46 +0000158 + g * mix(uStartColor1, uEndColor1, uColorProgress)
159 + b * mix(uStartColor2, uEndColor2, uColorProgress)
160 + a * mix(uStartColor3, uEndColor3, uColorProgress);
Andrew Zengf9f58222022-11-08 11:10:48 -0800161 color = mix(color, vec3((r + g + b + a) * 0.25), useWhiteMask);
162 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade));
Shan Huang2b31a362021-08-16 16:45:39 +0000163 })";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000164static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
165 precision mediump float;
166 uniform sampler2D uTexture;
167 uniform float uFade;
168 varying highp vec2 vUv;
169 void main() {
170 vec4 color = texture2D(uTexture, vUv);
Shan Huang2b31a362021-08-16 16:45:39 +0000171 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000172 })";
173static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
174 precision mediump float;
175 uniform sampler2D uTexture;
176 uniform vec4 uCropArea;
177 varying highp vec2 vUv;
178 void main() {
179 vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
180 mix(uCropArea.y, uCropArea.w, vUv.y));
181 gl_FragColor = texture2D(uTexture, uv);
182 })";
183
184static GLfloat quadPositions[] = {
185 -0.5f, -0.5f,
186 +0.5f, -0.5f,
187 +0.5f, +0.5f,
188 +0.5f, +0.5f,
189 -0.5f, +0.5f,
190 -0.5f, -0.5f
191};
192static GLfloat quadUVs[] = {
193 0.0f, 1.0f,
194 1.0f, 1.0f,
195 1.0f, 0.0f,
196 1.0f, 0.0f,
197 0.0f, 0.0f,
198 0.0f, 1.0f
199};
Narayan Kamathafd31e02013-12-03 13:16:03 +0000200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201// ---------------------------------------------------------------------------
202
Ed Coyne7464ac92017-06-08 12:26:48 -0700203BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200204 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700205 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700206 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400207
Keun-young Parkb5938422017-03-23 13:46:24 -0700208 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
209 if (powerCtl.empty()) {
210 mShuttingDown = false;
211 } else {
212 mShuttingDown = true;
213 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700214 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
215 elapsedRealtime());
216}
217
218BootAnimation::~BootAnimation() {
219 if (mAnimation != nullptr) {
220 releaseAnimation(mAnimation);
221 mAnimation = nullptr;
222 }
223 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
224 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225}
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700228 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700229 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700230 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700231 // Load the animation content -- this can be slow (eg 200ms)
232 // called before waitForSurfaceFlinger() in main() to avoid wait
233 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
234 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
235 preloadAnimation();
236 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
237 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
Mathias Agopianbc726112009-09-23 15:44:05 -0700238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239}
240
Mathias Agopianbc726112009-09-23 15:44:05 -0700241sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 return mSession;
243}
244
Marin Shalamanov9070c052020-05-18 19:05:17 +0200245void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700246 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700247 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700248
249 // calling requestExit() is not enough here because the Surface code
250 // might be blocked on a condition variable that will never be updated.
251 kill( getpid(), SIGKILL );
252 requestExit();
253}
254
Shan Huang2b31a362021-08-16 16:45:39 +0000255static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
256 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400257 AImageDecoder* decoder = nullptr;
258 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
259 if (!decoder) {
260 return nullptr;
261 }
262
263 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
264 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
265 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
266 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
267 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
268 outInfo->flags = 0;
269
Shan Huang2b31a362021-08-16 16:45:39 +0000270 if (!premultiplyAlpha) {
271 AImageDecoder_setUnpremultipliedRequired(decoder, true);
272 }
273
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400274 const size_t size = outInfo->stride * outInfo->height;
275 void* pixels = malloc(size);
276 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
277 AImageDecoder_delete(decoder);
278
279 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
280 free(pixels);
281 return nullptr;
282 }
283 return pixels;
284}
285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
Shan Huang2b31a362021-08-16 16:45:39 +0000287 const char* name, bool premultiplyAlpha) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700289 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400291
292 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000293 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
294 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400295 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 asset->close();
298 delete asset;
299
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400300 if (!pixels) {
301 return NO_INIT;
302 }
303
304 const int w = bitmapInfo.width;
305 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 texture->w = w;
308 texture->h = h;
309
310 glGenTextures(1, &texture->name);
311 glBindTexture(GL_TEXTURE_2D, texture->name);
312
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400313 switch (bitmapInfo.format) {
314 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400316 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400318 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400320 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400322 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400324 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400326 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400328 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 break;
330 default:
331 break;
332 }
333
Lucas Dupin8eedc022021-07-29 21:49:07 +0000334 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
335 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
336 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
337 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 return NO_ERROR;
340}
341
Shan Huang2b31a362021-08-16 16:45:39 +0000342status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
343 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400344 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000345 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
346 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400347 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700348
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200349 // FileMap memory is never released until application exit.
350 // Release it now as the texture is already loaded and the memory used for
351 // the packed resource can be released.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700352 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200353
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400354 if (!pixels) {
355 return NO_INIT;
356 }
357
358 const int w = bitmapInfo.width;
359 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700360
Mathias Agopiana8826d62009-10-01 03:10:14 -0700361 int tw = 1 << (31 - __builtin_clz(w));
362 int th = 1 << (31 - __builtin_clz(h));
363 if (tw < w) tw <<= 1;
364 if (th < h) th <<= 1;
365
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400366 switch (bitmapInfo.format) {
367 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530368 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700369 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700370 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700371 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400372 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700373 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530374 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400375 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700376 }
377 break;
378
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400379 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530380 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700381 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700382 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700383 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400384 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700385 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530386 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400387 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700388 }
389 break;
390 default:
391 break;
392 }
393
Lucas Dupin8eedc022021-07-29 21:49:07 +0000394 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
395 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
396 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
397 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700398
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700399 *width = w;
400 *height = h;
401
Mathias Agopiana8826d62009-10-01 03:10:14 -0700402 return NO_ERROR;
403}
404
Marin Shalamanov9070c052020-05-18 19:05:17 +0200405class BootAnimation::DisplayEventCallback : public LooperCallback {
406 BootAnimation* mBootAnimation;
407
408public:
409 DisplayEventCallback(BootAnimation* bootAnimation) {
410 mBootAnimation = bootAnimation;
411 }
412
413 int handleEvent(int /* fd */, int events, void* /* data */) {
414 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
415 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
416 events);
417 return 0; // remove the callback
418 }
419
420 if (!(events & Looper::EVENT_INPUT)) {
421 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
422 return 1; // keep the callback
423 }
424
425 constexpr int kBufferSize = 100;
426 DisplayEventReceiver::Event buffer[kBufferSize];
427 ssize_t numEvents;
428 do {
429 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
430 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
431 const auto& event = buffer[i];
432 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
433 SLOGV("Hotplug received");
434
435 if (!event.hotplug.connected) {
436 // ignore hotplug disconnect
437 continue;
438 }
439 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
440 event.header.displayId);
441
442 if (token != mBootAnimation->mDisplayToken) {
443 // ignore hotplug of a secondary display
444 continue;
445 }
446
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100447 DisplayMode displayMode;
448 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
449 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200450 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100451 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200452 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100453 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
454 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200455 }
456 }
457 } while (numEvents > 0);
458
459 return 1; // keep the callback
460 }
461};
462
463EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
464 const EGLint attribs[] = {
Andrii Chepurnyid93f7b22023-03-15 11:22:07 +0200465 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
Marin Shalamanov9070c052020-05-18 19:05:17 +0200466 EGL_RED_SIZE, 8,
467 EGL_GREEN_SIZE, 8,
468 EGL_BLUE_SIZE, 8,
469 EGL_DEPTH_SIZE, 0,
470 EGL_NONE
471 };
472 EGLint numConfigs;
473 EGLConfig config;
474 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
475 return config;
476}
477
Marin Shalamanov047802d2020-05-19 23:55:12 +0200478ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
479 ui::Size limited(width, height);
480 bool wasLimited = false;
481 const float aspectRatio = float(width) / float(height);
482 if (mMaxWidth != 0 && width > mMaxWidth) {
483 limited.height = mMaxWidth / aspectRatio;
484 limited.width = mMaxWidth;
485 wasLimited = true;
486 }
487 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
488 limited.height = mMaxHeight;
489 limited.width = mMaxHeight * aspectRatio;
490 wasLimited = true;
491 }
492 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
493 limited.width, limited.height, width, height);
494 return limited;
495}
496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497status_t BootAnimation::readyToRun() {
498 mAssets.addDefaultAssets();
499
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800500 mDisplayToken = SurfaceComposerClient::getInternalDisplayToken();
501 if (mDisplayToken == nullptr)
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800502 return NAME_NOT_FOUND;
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800503
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100504 DisplayMode displayMode;
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800505 const status_t error =
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100506 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800507 if (error != NO_ERROR)
508 return error;
509
Marin Shalamanov047802d2020-05-19 23:55:12 +0200510 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
511 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100512 ui::Size resolution = displayMode.resolution;
Marin Shalamanov047802d2020-05-19 23:55:12 +0200513 resolution = limitSurfaceSize(resolution.width, resolution.height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 // create the native surface
Jeff Brown0b722fe2012-08-24 22:40:14 -0700515 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
xi yuc3415442022-05-09 08:58:02 +0000516 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565,
517 ISurfaceComposerClient::eOpaque);
Mathias Agopian439863f2011-06-28 19:09:31 -0700518
Robert Carre13b58e2017-08-31 14:50:44 -0700519 SurfaceComposerClient::Transaction t;
Huihong Luof97c9e22019-05-29 11:08:01 -0700520
521 // this guest property specifies multi-display IDs to show the boot animation
522 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800523 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200524 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700525 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800526 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700527 bool isValid = displayValue[0] != '\0';
528 if (isValid) {
529 char *p = displayValue;
530 while (*p) {
531 if (!isdigit(*p) && *p != ',') {
532 isValid = false;
533 break;
534 }
535 p ++;
536 }
537 if (!isValid)
Huihong Luod4a217e2020-01-16 15:56:33 -0800538 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700539 }
540 if (isValid) {
541 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200542 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700543 physicalDisplayIds.add(id);
544 if (stream.peek() == ',')
545 stream.ignore();
546 }
547
548 // In the case of multi-display, boot animation shows on the specified displays
549 // in addition to the primary display
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700550 const auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
551 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700552 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700553 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
554 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
555 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700556 }
557 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700558 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700559 }
560
Robert Carre13b58e2017-08-31 14:50:44 -0700561 t.setLayer(control, 0x40000000)
562 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563
Mathias Agopian17f638b2009-04-16 20:04:08 -0700564 sp<Surface> s = control->getSurface();
565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700568 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200569 EGLConfig config = getEglConfig(display);
570 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000571 // Initialize egl context with client version number 2.0.
572 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
573 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200574 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 eglQuerySurface(display, surface, EGL_WIDTH, &w);
576 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700577
Mathias Agopianabac0102009-07-31 14:47:00 -0700578 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
579 return NO_INIT;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 mDisplay = display;
582 mContext = context;
583 mSurface = surface;
joenchen85b339f2022-04-11 23:58:34 +0800584 mInitWidth = mWidth = w;
585 mInitHeight = mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700586 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200588 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000590 // Rotate the boot animation according to the value specified in the sysprop
591 // ro.bootanim.set_orientation_<display_id>. Four values are supported: ORIENTATION_0,
592 // ORIENTATION_90, ORIENTATION_180 and ORIENTATION_270.
593 // If the value isn't specified or is ORIENTATION_0, nothing will be changed.
594 // This is needed to support having boot animation in orientations different from the natural
595 // device orientation. For example, on tablets that may want to keep natural orientation
596 // portrait for applications compatibility and to have the boot animation in landscape.
597 rotateAwayFromNaturalOrientationIfNeeded();
598
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200599 projectSceneToWindow();
600
Marin Shalamanov9070c052020-05-18 19:05:17 +0200601 // Register a display event receiver
602 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
603 status_t status = mDisplayEventReceiver->initCheck();
604 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
605 status);
606 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
607 new DisplayEventCallback(this), nullptr);
608
Huihong Luo50a2f362018-08-11 09:27:57 -0700609 return NO_ERROR;
610}
611
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000612void BootAnimation::rotateAwayFromNaturalOrientationIfNeeded() {
613 const auto orientation = parseOrientationProperty();
614
615 if (orientation == ui::ROTATION_0) {
616 // Do nothing if the sysprop isn't set or is set to ROTATION_0.
617 return;
618 }
619
620 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
621 std::swap(mWidth, mHeight);
622 std::swap(mInitWidth, mInitHeight);
623 mFlingerSurfaceControl->updateDefaultBufferSize(mWidth, mHeight);
624 }
625
626 Rect displayRect(0, 0, mWidth, mHeight);
627 Rect layerStackRect(0, 0, mWidth, mHeight);
628
629 SurfaceComposerClient::Transaction t;
630 t.setDisplayProjection(mDisplayToken, orientation, layerStackRect, displayRect);
631 t.apply();
632}
633
634ui::Rotation BootAnimation::parseOrientationProperty() {
635 const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
636 if (displayIds.size() == 0) {
637 return ui::ROTATION_0;
638 }
639 const auto displayId = displayIds[0];
640 const auto syspropName = [displayId] {
641 std::stringstream ss;
642 ss << "ro.bootanim.set_orientation_" << displayId.value;
643 return ss.str();
644 }();
645 const auto syspropValue = android::base::GetProperty(syspropName, "ORIENTATION_0");
646 if (syspropValue == "ORIENTATION_90") {
647 return ui::ROTATION_90;
648 } else if (syspropValue == "ORIENTATION_180") {
649 return ui::ROTATION_180;
650 } else if (syspropValue == "ORIENTATION_270") {
651 return ui::ROTATION_270;
652 }
653 return ui::ROTATION_0;
654}
655
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200656void BootAnimation::projectSceneToWindow() {
657 glViewport(0, 0, mWidth, mHeight);
658 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200659}
660
Marin Shalamanov9070c052020-05-18 19:05:17 +0200661void BootAnimation::resizeSurface(int newWidth, int newHeight) {
662 // We assume this function is called on the animation thread.
663 if (newWidth == mWidth && newHeight == mHeight) {
664 return;
665 }
666 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
667
668 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
669 eglDestroySurface(mDisplay, mSurface);
670
joenchen85b339f2022-04-11 23:58:34 +0800671 mFlingerSurfaceControl->updateDefaultBufferSize(newWidth, newHeight);
Marin Shalamanov047802d2020-05-19 23:55:12 +0200672 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
673 mWidth = limitedSize.width;
674 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200675
676 SurfaceComposerClient::Transaction t;
677 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
678 t.apply();
679
680 EGLConfig config = getEglConfig(mDisplay);
681 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
682 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
683 SLOGE("Can't make the new surface current. Error %d", eglGetError());
684 return;
685 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200686
687 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200688
689 mSurface = surface;
690}
691
Huihong Luo50a2f362018-08-11 09:27:57 -0700692bool BootAnimation::preloadAnimation() {
693 findBootAnimationFile();
Tomasz Wasilczyke8fb3c72023-08-24 19:11:22 +0000694 if (!mZipFileName.empty()) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700695 mAnimation = loadAnimation(mZipFileName);
696 return (mAnimation != nullptr);
697 }
698
699 return false;
700}
701
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000702bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
703 for (const std::string& f : files) {
704 if (access(f.c_str(), R_OK) == 0) {
705 mZipFileName = f.c_str();
706 return true;
707 }
708 }
709 return false;
710}
711
Huihong Luo50a2f362018-08-11 09:27:57 -0700712void BootAnimation::findBootAnimationFile() {
Elliott Hughesc367d482013-10-29 13:12:55 -0700713 // If the device has encryption turned on or is in process
Jason parksbd9a08d2011-01-31 15:04:34 -0600714 // of being encrypted we show the encrypted boot animation.
715 char decrypt[PROPERTY_VALUE_MAX];
716 property_get("vold.decrypt", decrypt, "");
717
Keun-young Parkb5938422017-03-23 13:46:24 -0700718 bool encryptedAnimation = atoi(decrypt) != 0 ||
719 !strcmp("trigger_restart_min_framework", decrypt);
Jason parksbd9a08d2011-01-31 15:04:34 -0600720
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900721 if (!mShuttingDown && encryptedAnimation) {
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000722 static const std::vector<std::string> encryptedBootFiles = {
723 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
724 };
725 if (findBootAnimationFileInternal(encryptedBootFiles)) {
726 return;
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900727 }
Jason parksbd9a08d2011-01-31 15:04:34 -0600728 }
Beverly34ffe252019-05-17 11:03:54 -0400729
730 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000731 static const std::vector<std::string> bootFiles = {
732 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
733 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
734 };
735 static const std::vector<std::string> shutdownFiles = {
736 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
737 };
738 static const std::vector<std::string> userspaceRebootFiles = {
739 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
740 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
741 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700742
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000743 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
744 findBootAnimationFileInternal(userspaceRebootFiles);
745 } else if (mShuttingDown) {
746 findBootAnimationFileInternal(shutdownFiles);
747 } else {
748 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750}
751
Lucas Dupin8eedc022021-07-29 21:49:07 +0000752GLuint compileShader(GLenum shaderType, const GLchar *source) {
753 GLuint shader = glCreateShader(shaderType);
754 glShaderSource(shader, 1, &source, 0);
755 glCompileShader(shader);
756 GLint isCompiled = 0;
757 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
758 if (isCompiled == GL_FALSE) {
759 SLOGE("Compile shader failed. Shader type: %d", shaderType);
Shan Huang81846ba2021-09-07 19:07:47 +0000760 GLint maxLength = 0;
761 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
762 std::vector<GLchar> errorLog(maxLength);
763 glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
764 SLOGE("Shader compilation error: %s", &errorLog[0]);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000765 return 0;
766 }
767 return shader;
768}
769
770GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
771 GLuint program = glCreateProgram();
772 glAttachShader(program, vertexShader);
773 glAttachShader(program, fragmentShader);
774 glLinkProgram(program);
775 GLint isLinked = 0;
776 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
777 if (isLinked == GL_FALSE) {
778 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
779 vertexShader, fragmentShader);
780 return 0;
781 }
782 return program;
783}
784
785void BootAnimation::initShaders() {
Shan Huang2b31a362021-08-16 16:45:39 +0000786 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000787 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
788 GLuint imageFragmentShader =
Shan Huang2b31a362021-08-16 16:45:39 +0000789 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
790 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
791 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000792 GLuint textFragmentShader =
793 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
794
795 // Initialize image shader.
796 mImageShader = linkShader(vertexShader, imageFragmentShader);
797 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
798 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
799 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
800 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
801 glEnableVertexAttribArray(positionLocation);
802 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
803 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
804 glEnableVertexAttribArray(uvLocation);
805
806 // Initialize text shader.
807 mTextShader = linkShader(vertexShader, textFragmentShader);
808 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
809 uvLocation = glGetAttribLocation(mTextShader, A_UV);
810 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
811 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
812 glEnableVertexAttribArray(positionLocation);
813 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
814 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
815 glEnableVertexAttribArray(uvLocation);
816}
817
Marin Shalamanov9070c052020-05-18 19:05:17 +0200818bool BootAnimation::threadLoop() {
819 bool result;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000820 initShaders();
821
Narayan Kamathafd31e02013-12-03 13:16:03 +0000822 // We have no bootanimation file, so we use the stock android logo
823 // animation.
Tomasz Wasilczyke8fb3c72023-08-24 19:11:22 +0000824 if (mZipFileName.empty()) {
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +0900825 ALOGD("No animation file");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200826 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700827 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200828 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700829 }
830
Philip Junker60600562020-11-25 18:16:16 +0100831 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
833 eglDestroyContext(mDisplay, mContext);
834 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700835 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700836 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700837 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530838 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700839 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200840 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841}
842
Marin Shalamanov9070c052020-05-18 19:05:17 +0200843bool BootAnimation::android() {
Lucas Dupin8eedc022021-07-29 21:49:07 +0000844 glActiveTexture(GL_TEXTURE0);
845
Wei Wang159a4102018-10-23 23:15:58 -0700846 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700847 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700848 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
849 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850
Ed Coyne7464ac92017-06-08 12:26:48 -0700851 mCallbacks->init({});
852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700854 glDisable(GL_DITHER);
855 glDisable(GL_SCISSOR_TEST);
Shan Huangbfd2d3c2021-09-09 23:19:04 +0000856 glUseProgram(mImageShader);
857
Mathias Agopian59f19e42011-05-06 19:22:12 -0700858 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 glClear(GL_COLOR_BUFFER_BIT);
860 eglSwapBuffers(mDisplay, mSurface);
861
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700862 // Blend state
863 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 const nsecs_t startTime = systemTime();
866 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200867 processDisplayEvents();
868 const GLint xc = (mWidth - mAndroid[0].w) / 2;
869 const GLint yc = (mHeight - mAndroid[0].h) / 2;
870 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
871 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
872 updateRect.height());
873
Mathias Agopian13796652009-03-24 22:49:21 -0700874 nsecs_t now = systemTime();
875 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700876 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
877 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
878 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879
Mathias Agopian81668642009-07-28 11:41:30 -0700880 glDisable(GL_SCISSOR_TEST);
881 glClear(GL_COLOR_BUFFER_BIT);
882
883 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000886 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
887 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700889 glEnable(GL_BLEND);
890 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000891 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892
Mathias Agopian627e7b52009-05-21 19:21:59 -0700893 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
894 if (res == EGL_FALSE)
895 break;
896
Mathias Agopian13796652009-03-24 22:49:21 -0700897 // 12fps: don't animate too fast to preserve CPU
898 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
899 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700900 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700901
902 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 } while (!exitPending());
904
905 glDeleteTextures(1, &mAndroid[0].name);
906 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 return false;
908}
909
Kevin Hesterd3782b22012-04-26 10:38:55 -0700910void BootAnimation::checkExit() {
911 // Allow surface flinger to gracefully request shutdown
912 char value[PROPERTY_VALUE_MAX];
913 property_get(EXIT_PROP_NAME, value, "0");
914 int exitnow = atoi(value);
915 if (exitnow) {
916 requestExit();
917 }
918}
919
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700920bool BootAnimation::validClock(const Animation::Part& part) {
921 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
922}
923
924bool parseTextCoord(const char* str, int* dest) {
925 if (strcmp("c", str) == 0) {
926 *dest = TEXT_CENTER_VALUE;
927 return true;
928 }
929
930 char* end;
931 int val = (int) strtol(str, &end, 0);
932 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
933 return false;
934 }
935 *dest = val;
936 return true;
937}
938
939// Parse two position coordinates. If only string is non-empty, treat it as the y value.
940void parsePosition(const char* str1, const char* str2, int* x, int* y) {
941 bool success = false;
942 if (strlen(str1) == 0) { // No values were specified
943 // success = false
944 } else if (strlen(str2) == 0) { // we have only one value
945 if (parseTextCoord(str1, y)) {
946 *x = TEXT_CENTER_VALUE;
947 success = true;
948 }
949 } else {
950 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
951 success = true;
952 }
953 }
954
955 if (!success) {
956 *x = TEXT_MISSING_VALUE;
957 *y = TEXT_MISSING_VALUE;
958 }
959}
960
Jesse Hall083b84c2014-09-22 10:51:09 -0700961// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
962// characters in str is a hex number in [0, 255], which are converted to
963// floating point values in the range [0.0, 1.0] and placed in the
964// corresponding elements of color.
965//
966// If the input string isn't valid, parseColor returns false and color is
967// left unchanged.
968static bool parseColor(const char str[7], float color[3]) {
969 float tmpColor[3];
970 for (int i = 0; i < 3; i++) {
971 int val = 0;
972 for (int j = 0; j < 2; j++) {
973 val *= 16;
974 char c = str[2*i + j];
975 if (c >= '0' && c <= '9') val += c - '0';
976 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
977 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
978 else return false;
979 }
980 tmpColor[i] = static_cast<float>(val) / 255.0f;
981 }
982 memcpy(color, tmpColor, sizeof(tmpColor));
983 return true;
984}
985
Shan Huang2b31a362021-08-16 16:45:39 +0000986// Parse a color represented as a signed decimal int string.
987// E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
988// If the input color string is empty, set color with values in defaultColor.
989static void parseColorDecimalString(const std::string& colorString,
990 float color[3], float defaultColor[3]) {
991 if (colorString == "") {
992 memcpy(color, defaultColor, sizeof(float) * 3);
993 return;
994 }
995 int colorInt = atoi(colorString.c_str());
996 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
997 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
998 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
999}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001000
Marin Shalamanov9070c052020-05-18 19:05:17 +02001001static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001002 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -07001003 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001004 if (!entry) {
1005 return false;
1006 }
1007
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001008 FileMap* entryMap = zip->createEntryFileMap(entry);
1009 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -07001010 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001011 if (!entryMap) {
1012 return false;
1013 }
1014
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001015 outString = String8((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +00001016 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001017 return true;
1018}
1019
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001020// The font image should be a 96x2 array of character images. The
1021// columns are the printable ASCII characters 0x20 - 0x7f. The
1022// top row is regular text; the bottom row is bold.
1023status_t BootAnimation::initFont(Font* font, const char* fallback) {
1024 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001025
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001026 if (font->map != nullptr) {
1027 glGenTextures(1, &font->texture.name);
1028 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001029
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001030 status = initTexture(font->map, &font->texture.w, &font->texture.h);
1031
Lucas Dupin8eedc022021-07-29 21:49:07 +00001032 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1033 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1034 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1035 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001036 } else if (fallback != nullptr) {
1037 status = initTexture(&font->texture, mAssets, fallback);
1038 } else {
1039 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001040 }
1041
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001042 if (status == NO_ERROR) {
1043 font->char_width = font->texture.w / FONT_NUM_COLS;
1044 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
1045 }
1046
1047 return status;
1048}
1049
1050void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
1051 glEnable(GL_BLEND); // Allow us to draw on top of the animation
1052 glBindTexture(GL_TEXTURE_2D, font.texture.name);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001053 glUseProgram(mTextShader);
1054 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001055
1056 const int len = strlen(str);
1057 const int strWidth = font.char_width * len;
1058
1059 if (*x == TEXT_CENTER_VALUE) {
1060 *x = (mWidth - strWidth) / 2;
1061 } else if (*x < 0) {
1062 *x = mWidth + *x - strWidth;
1063 }
1064 if (*y == TEXT_CENTER_VALUE) {
1065 *y = (mHeight - font.char_height) / 2;
1066 } else if (*y < 0) {
1067 *y = mHeight + *y - font.char_height;
1068 }
1069
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001070 for (int i = 0; i < len; i++) {
1071 char c = str[i];
1072
1073 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1074 c = '?';
1075 }
1076
1077 // Crop the texture to only the pixels in the current glyph
1078 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1079 const int row = charPos / FONT_NUM_COLS;
1080 const int col = charPos % FONT_NUM_COLS;
Lucas Dupin8eedc022021-07-29 21:49:07 +00001081 // Bold fonts are expected in the second half of each row.
1082 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1083 float u0 = ((float)col) / FONT_NUM_COLS;
1084 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1085 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1086 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1087 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001088
1089 *x += font.char_width;
1090 }
1091
1092 glDisable(GL_BLEND); // Return to the animation's default behaviour
1093 glBindTexture(GL_TEXTURE_2D, 0);
1094}
1095
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001096// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001097void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001098 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1099 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001100 static constexpr int TIME_LENGTH = 6;
1101
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001102 time_t rawtime;
1103 time(&rawtime);
1104 struct tm* timeInfo = localtime(&rawtime);
1105
1106 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001107 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1108 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001109
1110 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001111 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001112 mClockEnabled = false;
1113 return;
1114 }
1115
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001116 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001117 int x = xPos;
1118 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001119 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001120}
1121
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001122void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1123 static constexpr int PERCENT_LENGTH = 5;
1124
1125 char percentBuff[PERCENT_LENGTH];
1126 // ';' has the ascii code just after ':', and the font resource contains '%'
1127 // for that ascii code.
1128 sprintf(percentBuff, "%d;", percent);
1129 int x = xPos;
1130 int y = yPos;
1131 drawText(percentBuff, font, false, &x, &y);
1132}
1133
Marin Shalamanov9070c052020-05-18 19:05:17 +02001134bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001135 String8 desString;
1136
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001137 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001138 return false;
1139 }
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001140 char const* s = desString.c_str();
Shan Huang2b31a362021-08-16 16:45:39 +00001141 std::string dynamicColoringPartName = "";
1142 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001143
Mathias Agopiana8826d62009-10-01 03:10:14 -07001144 // Parse the description file
1145 for (;;) {
1146 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001147 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001148 String8 line(s, endl - s);
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001149 const char* l = line.c_str();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001150 int fps = 0;
1151 int width = 0;
1152 int height = 0;
1153 int count = 0;
1154 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001155 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001156 int framesToFadeCount = 0;
Shan Huang488ff742021-08-25 20:10:46 +00001157 int colorTransitionStart = 0;
1158 int colorTransitionEnd = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001159 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001160 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001161 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1162 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang2b31a362021-08-16 16:45:39 +00001163 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001164 char pathType;
Shan Huang2b31a362021-08-16 16:45:39 +00001165 // start colors default to black if unspecified
1166 char start_color_0[7] = "000000";
1167 char start_color_1[7] = "000000";
1168 char start_color_2[7] = "000000";
1169 char start_color_3[7] = "000000";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001170
1171 int nextReadPos;
1172
yidong zhang87bb3462022-12-07 15:55:31 +08001173 if (strlen(l) == 0) {
1174 s = ++endl;
1175 continue;
1176 }
1177
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001178 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1179 if (topLineNumbers == 3 || topLineNumbers == 4) {
1180 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001181 animation.width = width;
1182 animation.height = height;
1183 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001184 if (topLineNumbers == 4) {
1185 animation.progressEnabled = (progress != 0);
1186 } else {
1187 animation.progressEnabled = false;
1188 }
Shan Huang488ff742021-08-25 20:10:46 +00001189 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
Shan Huang2b31a362021-08-16 16:45:39 +00001190 dynamicColoringPartNameBuffer,
Shan Huang488ff742021-08-25 20:10:46 +00001191 start_color_0, start_color_1, start_color_2, start_color_3,
1192 &colorTransitionStart, &colorTransitionEnd)) {
Shan Huang2b31a362021-08-16 16:45:39 +00001193 animation.dynamicColoringEnabled = true;
1194 parseColor(start_color_0, animation.startColors[0]);
1195 parseColor(start_color_1, animation.startColors[1]);
1196 parseColor(start_color_2, animation.startColors[2]);
1197 parseColor(start_color_3, animation.startColors[3]);
Shan Huang488ff742021-08-25 20:10:46 +00001198 animation.colorTransitionStart = colorTransitionStart;
1199 animation.colorTransitionEnd = colorTransitionEnd;
Shan Huang2b31a362021-08-16 16:45:39 +00001200 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001201 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1202 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1203 if (pathType == 'f') {
1204 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1205 clockPos2);
1206 } else {
1207 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1208 }
1209 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1210 // "clockPos1=%s, clockPos2=%s",
1211 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001212 Animation::Part part;
Shan Huang2b31a362021-08-16 16:45:39 +00001213 if (path == dynamicColoringPartName) {
1214 // Part is specified to use dynamic coloring.
1215 part.useDynamicColoring = true;
1216 part.postDynamicColoring = false;
1217 postDynamicColoring = true;
1218 } else {
1219 // Part does not use dynamic coloring.
1220 part.useDynamicColoring = false;
1221 part.postDynamicColoring = postDynamicColoring;
1222 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001223 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001224 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001225 part.count = count;
1226 part.pause = pause;
1227 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001228 part.audioData = nullptr;
1229 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001230 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001231 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001232 part.backgroundColor[0] = 0.0f;
1233 part.backgroundColor[1] = 0.0f;
1234 part.backgroundColor[2] = 0.0f;
1235 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001236 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001237 animation.parts.add(part);
1238 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001239 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001240 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001241 Animation::Part part;
1242 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001243 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001244 part.count = 1;
1245 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001246 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001247 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001248 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001249 animation.parts.add(part);
1250 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001251 s = ++endl;
1252 }
1253
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001254 return true;
1255}
1256
Marin Shalamanov9070c052020-05-18 19:05:17 +02001257bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001258 // read all the data structures
1259 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001260 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001261 ZipFileRO* zip = animation.zip;
1262 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001263 return false;
1264 }
1265
1266 ZipEntryRO entry;
1267 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001268 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001269 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001270 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001271 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001272 continue;
1273 }
1274
Tomasz Wasilczyk9dcea572023-08-22 20:39:20 +00001275 const std::filesystem::path entryName(name);
1276 const std::filesystem::path path(entryName.parent_path());
1277 const std::filesystem::path leaf(entryName.filename());
1278 if (!leaf.empty()) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001279 if (entryName == CLOCK_FONT_ZIP_NAME) {
1280 FileMap* map = zip->createEntryFileMap(entry);
1281 if (map) {
1282 animation.clockFont.map = map;
1283 }
1284 continue;
1285 }
1286
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001287 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1288 FileMap* map = zip->createEntryFileMap(entry);
1289 if (map) {
1290 animation.progressFont.map = map;
1291 }
1292 continue;
1293 }
1294
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001295 for (size_t j = 0; j < pcount; j++) {
Tomasz Wasilczyk9dcea572023-08-22 20:39:20 +00001296 if (path.string() == animation.parts[j].path.c_str()) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001297 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001298 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001299 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001300 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001301 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001302 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001303 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001304 if (leaf == "audio.wav") {
1305 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001306 part.audioData = (uint8_t *)map->getDataPtr();
1307 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001308 } else if (leaf == "trim.txt") {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001309 part.trimData = String8((char const*)map->getDataPtr(),
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001310 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001311 } else {
1312 Animation::Frame frame;
Tomasz Wasilczyk9dcea572023-08-22 20:39:20 +00001313 frame.name = leaf.c_str();
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001314 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001315 frame.trimWidth = animation.width;
1316 frame.trimHeight = animation.height;
1317 frame.trimX = 0;
1318 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001319 part.frames.add(frame);
1320 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001321 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001322 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001323 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001324 }
1325 }
1326 }
1327 }
1328 }
1329 }
1330
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001331 // If there is trimData present, override the positioning defaults.
1332 for (Animation::Part& part : animation.parts) {
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001333 const char* trimDataStr = part.trimData.c_str();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001334 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1335 const char* endl = strstr(trimDataStr, "\n");
1336 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001337 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001338 break;
1339 }
1340 String8 line(trimDataStr, endl - trimDataStr);
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001341 const char* lineStr = line.c_str();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001342 trimDataStr = ++endl;
1343 int width = 0, height = 0, x = 0, y = 0;
1344 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1345 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1346 frame.trimWidth = width;
1347 frame.trimHeight = height;
1348 frame.trimX = x;
1349 frame.trimY = y;
1350 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001351 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001352 break;
1353 }
1354 }
1355 }
1356
1357 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001358
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001359 return true;
1360}
1361
Marin Shalamanov9070c052020-05-18 19:05:17 +02001362bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001363 if (mAnimation == nullptr) {
1364 mAnimation = loadAnimation(mZipFileName);
1365 }
1366
1367 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001368 return false;
1369
Huihong Luo50a2f362018-08-11 09:27:57 -07001370 // mCallbacks->init() may get called recursively,
1371 // this loop is needed to get the same results
1372 for (const Animation::Part& part : mAnimation->parts) {
1373 if (part.animation != nullptr) {
1374 mCallbacks->init(part.animation->parts);
1375 }
1376 }
1377 mCallbacks->init(mAnimation->parts);
1378
Damien Bargiacchi97480862016-03-29 14:55:55 -07001379 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001380 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1381 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001382 anyPartHasClock = true;
1383 break;
1384 }
1385 }
1386 if (!anyPartHasClock) {
1387 mClockEnabled = false;
Thiébaud Weksteen08de4432021-11-18 13:25:59 +11001388 } else if (!android::base::GetBoolProperty(CLOCK_ENABLED_PROP_NAME, false)) {
1389 mClockEnabled = false;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001390 }
1391
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301392 // Check if npot textures are supported
1393 mUseNpotTextures = false;
1394 String8 gl_extensions;
1395 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1396 if (!exts) {
1397 glGetError();
1398 } else {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001399 gl_extensions = exts;
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301400 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1401 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1402 mUseNpotTextures = true;
1403 }
1404 }
1405
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001406 // Blend required to draw time on top of animation frames.
1407 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001408 glDisable(GL_DITHER);
1409 glDisable(GL_SCISSOR_TEST);
1410 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001411
Greg Kaiser2ded8002021-07-19 17:03:27 +00001412 glEnable(GL_TEXTURE_2D);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001413 glBindTexture(GL_TEXTURE_2D, 0);
1414 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1415 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1416 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1417 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001418 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001419 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001420 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001421 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001422 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001423 }
1424
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001425 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1426
Damien Bargiacchi97480862016-03-29 14:55:55 -07001427 if (mClockEnabled && !updateIsTimeAccurate()) {
1428 mTimeCheckThread = new TimeCheckThread(this);
1429 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1430 }
1431
George Burgess IV0f8e8112021-08-23 17:32:23 -07001432 if (mAnimation->dynamicColoringEnabled) {
Shan Huang7fee3522021-08-18 00:56:08 +00001433 initDynamicColors();
1434 }
1435
Huihong Luo50a2f362018-08-11 09:27:57 -07001436 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001437
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001438 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001439 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001440 mTimeCheckThread = nullptr;
1441 }
1442
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001443 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001444 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001445 }
1446
Huihong Luo50a2f362018-08-11 09:27:57 -07001447 releaseAnimation(mAnimation);
1448 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001449
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001450 return false;
1451}
1452
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001453bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1454 const int fadedFramesCount,
1455 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001456 // 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 +01001457 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1458 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001459}
1460
Lucas Dupin8eedc022021-07-29 21:49:07 +00001461// Linear mapping from range <a1, a2> to range <b1, b2>
1462float mapLinear(float x, float a1, float a2, float b1, float b2) {
1463 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1464}
1465
1466void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1467 // Map coordinates from screen space to world space.
1468 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1469 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1470 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1471 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1472 // Update quad vertex positions.
1473 quadPositions[0] = x0;
1474 quadPositions[1] = y0;
1475 quadPositions[2] = x1;
1476 quadPositions[3] = y0;
1477 quadPositions[4] = x1;
1478 quadPositions[5] = y1;
1479 quadPositions[6] = x1;
1480 quadPositions[7] = y1;
1481 quadPositions[8] = x0;
1482 quadPositions[9] = y1;
1483 quadPositions[10] = x0;
1484 quadPositions[11] = y0;
1485 glDrawArrays(GL_TRIANGLES, 0,
1486 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1487}
1488
Shan Huang7fee3522021-08-18 00:56:08 +00001489void BootAnimation::initDynamicColors() {
1490 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
Lucas Dupincd256842022-03-29 15:46:36 -07001491 const auto syspropName = "persist.bootanim.color" + std::to_string(i + 1);
1492 const auto syspropValue = android::base::GetProperty(syspropName, "");
1493 if (syspropValue != "") {
1494 SLOGI("Loaded dynamic color: %s -> %s", syspropName.c_str(), syspropValue.c_str());
1495 mDynamicColorsApplied = true;
1496 }
1497 parseColorDecimalString(syspropValue,
Shan Huang7fee3522021-08-18 00:56:08 +00001498 mAnimation->endColors[i], mAnimation->startColors[i]);
1499 }
1500 glUseProgram(mImageShader);
Lucas Dupincd256842022-03-29 15:46:36 -07001501 SLOGI("Dynamically coloring boot animation. Sysprops loaded? %i", mDynamicColorsApplied);
Shan Huang7fee3522021-08-18 00:56:08 +00001502 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1503 float *startColor = mAnimation->startColors[i];
1504 float *endColor = mAnimation->endColors[i];
Andrew Zengf9f58222022-11-08 11:10:48 -08001505 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001506 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001507 startColor[0], startColor[1], startColor[2]);
1508 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001509 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001510 endColor[0], endColor[1], endColor[2]);
Shan Huang7fee3522021-08-18 00:56:08 +00001511 }
1512 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1513}
1514
Marin Shalamanov9070c052020-05-18 19:05:17 +02001515bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001516 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001517 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001518
Wei Wang159a4102018-10-23 23:15:58 -07001519 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001520 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001521
1522 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001523 int lastDisplayedProgress = 0;
Lucas Dupinbfd18122022-04-25 11:26:08 -07001524 int colorTransitionStart = animation.colorTransitionStart;
1525 int colorTransitionEnd = animation.colorTransitionEnd;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001526 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001527 const Animation::Part& part(animation.parts[i]);
1528 const size_t fcount = part.frames.size();
Oleg Lyovin6a4b84d2023-07-01 14:39:59 +03001529 glBindTexture(GL_TEXTURE_2D, 0);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001530
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001531 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001532 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001533 playAnimation(*part.animation);
1534 if (exitPending())
1535 break;
1536 continue; //to next part
1537 }
1538
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001539 // process the part not only while the count allows but also if already fading
1540 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001541 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001542
Lucas Dupinbfd18122022-04-25 11:26:08 -07001543 // It's possible that the sysprops were not loaded yet at this boot phase.
1544 // If that's the case, then we should keep trying until they are available.
1545 if (animation.dynamicColoringEnabled && !mDynamicColorsApplied
1546 && (part.useDynamicColoring || part.postDynamicColoring)) {
1547 SLOGD("Trying to load dynamic color sysprops.");
1548 initDynamicColors();
1549 if (mDynamicColorsApplied) {
1550 // Sysprops were loaded. Next step is to adjust the animation if we loaded
1551 // the colors after the animation should have started.
1552 const int transitionLength = colorTransitionEnd - colorTransitionStart;
1553 if (part.postDynamicColoring) {
1554 colorTransitionStart = 0;
1555 colorTransitionEnd = fmin(transitionLength, fcount - 1);
1556 }
1557 }
1558 }
1559
Ed Coyne7464ac92017-06-08 12:26:48 -07001560 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001561
Jesse Hall083b84c2014-09-22 10:51:09 -07001562 glClearColor(
1563 part.backgroundColor[0],
1564 part.backgroundColor[1],
1565 part.backgroundColor[2],
1566 1.0f);
1567
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001568 ALOGD("Playing files = %s/%s, Requested repeat = %d, playUntilComplete = %s",
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001569 animation.fileName.c_str(), part.path.c_str(), part.count,
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001570 part.playUntilComplete ? "true" : "false");
1571
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001572 // For the last animation, if we have progress indicator from
1573 // the system, display it.
1574 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1575 bool displayProgress = animation.progressEnabled &&
1576 (i == (pcount -1)) && currentProgress != 0;
1577
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001578 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001579 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001580
Shan Huang2b31a362021-08-16 16:45:39 +00001581 // Color progress is
Shan Huang488ff742021-08-25 20:10:46 +00001582 // - the animation progress, normalized from
1583 // [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1584 // part.
Shan Huang2b31a362021-08-16 16:45:39 +00001585 // - 0 for parts that come before,
1586 // - 1 for parts that come after.
1587 float colorProgress = part.useDynamicColoring
Shan Huang488ff742021-08-25 20:10:46 +00001588 ? fmin(fmax(
Lucas Dupinbfd18122022-04-25 11:26:08 -07001589 ((float)j - colorTransitionStart) /
1590 fmax(colorTransitionEnd - colorTransitionStart, 1.0f), 0.0f), 1.0f)
Shan Huang2b31a362021-08-16 16:45:39 +00001591 : (part.postDynamicColoring ? 1 : 0);
1592
Marin Shalamanov9070c052020-05-18 19:05:17 +02001593 processDisplayEvents();
1594
joenchen85b339f2022-04-11 23:58:34 +08001595 const double ratio_w = static_cast<double>(mWidth) / mInitWidth;
1596 const double ratio_h = static_cast<double>(mHeight) / mInitHeight;
1597 const int animationX = (mWidth - animation.width * ratio_w) / 2;
1598 const int animationY = (mHeight - animation.height * ratio_h) / 2;
Marin Shalamanov9070c052020-05-18 19:05:17 +02001599
Mathias Agopiana8826d62009-10-01 03:10:14 -07001600 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001601 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001602
1603 if (r > 0) {
1604 glBindTexture(GL_TEXTURE_2D, frame.tid);
1605 } else {
Oleg Lyovin6a4b84d2023-07-01 14:39:59 +03001606 if (part.count != 1) {
1607 glGenTextures(1, &frame.tid);
1608 glBindTexture(GL_TEXTURE_2D, frame.tid);
1609 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001610 int w, h;
Shan Huang2b31a362021-08-16 16:45:39 +00001611 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1612 // of transparent pixels are preserved.
1613 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001614 }
1615
joenchen85b339f2022-04-11 23:58:34 +08001616 const int trimWidth = frame.trimWidth * ratio_w;
1617 const int trimHeight = frame.trimHeight * ratio_h;
1618 const int trimX = frame.trimX * ratio_w;
1619 const int trimY = frame.trimY * ratio_h;
1620 const int xc = animationX + trimX;
1621 const int yc = animationY + trimY;
Shan Huang2b31a362021-08-16 16:45:39 +00001622 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001623 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1624 // which is equivalent to mHeight - (yc + frame.trimHeight)
joenchen85b339f2022-04-11 23:58:34 +08001625 const int frameDrawY = mHeight - (yc + trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001626
Lucas Dupin8eedc022021-07-29 21:49:07 +00001627 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001628 // if the part hasn't been stopped yet then continue fading if necessary
1629 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001630 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001631 if (fadedFramesCount >= part.framesToFadeCount) {
1632 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1633 }
1634 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001635 glUseProgram(mImageShader);
1636 glUniform1i(mImageTextureLocation, 0);
1637 glUniform1f(mImageFadeLocation, fade);
Shan Huang2b31a362021-08-16 16:45:39 +00001638 if (animation.dynamicColoringEnabled) {
1639 glUniform1f(mImageColorProgressLocation, colorProgress);
1640 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001641 glEnable(GL_BLEND);
joenchen85b339f2022-04-11 23:58:34 +08001642 drawTexturedQuad(xc, frameDrawY, trimWidth, trimHeight);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001643 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001644
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001645 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1646 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001647 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001648
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001649 if (displayProgress) {
1650 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1651 // In case the new progress jumped suddenly, still show an
1652 // increment of 1.
1653 if (lastDisplayedProgress != 100) {
1654 // Artificially sleep 1/10th a second to slow down the animation.
1655 usleep(100000);
1656 if (lastDisplayedProgress < newProgress) {
1657 lastDisplayedProgress++;
1658 }
1659 }
1660 // Put the progress percentage right below the animation.
1661 int posY = animation.height / 3;
1662 int posX = TEXT_CENTER_VALUE;
1663 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1664 }
1665
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001666 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001667
Mathias Agopiana8826d62009-10-01 03:10:14 -07001668 eglSwapBuffers(mDisplay, mSurface);
1669
1670 nsecs_t now = systemTime();
1671 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001672 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001673 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001674
1675 if (delay > 0) {
1676 struct timespec spec;
1677 spec.tv_sec = (now + delay) / 1000000000;
1678 spec.tv_nsec = (now + delay) % 1000000000;
1679 int err;
1680 do {
Yi Kong911ac232019-03-24 01:49:02 -07001681 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Keith Mok0f2e6682021-11-15 05:50:32 +00001682 } while (err == EINTR);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001683 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001684
1685 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001686 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001687
niuwenchao9cd6ac82022-12-23 17:34:22 +08001688 int pauseDuration = part.pause * ns2us(frameDuration);
1689 while(pauseDuration > 0 && !exitPending()){
1690 if (pauseDuration > MAX_CHECK_EXIT_INTERVAL_US) {
1691 usleep(MAX_CHECK_EXIT_INTERVAL_US);
1692 pauseDuration -= MAX_CHECK_EXIT_INTERVAL_US;
1693 } else {
1694 usleep(pauseDuration);
1695 break;
1696 }
1697 checkExit();
1698 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001699
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001700 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1701 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001702 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1703 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1704 continue;
1705 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001706 break; // exit the infinite non-fading part when it has been played at least once
1707 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001708 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001709 }
1710
1711 // Free textures created for looping parts now that the animation is done.
1712 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001713 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001714 const size_t fcount = part.frames.size();
1715 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001716 const Animation::Frame& frame(part.frames[j]);
1717 glDeleteTextures(1, &frame.tid);
1718 }
1719 }
1720 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001721
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001722 ALOGD("%sAnimationShownTiming End time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1723 elapsedRealtime());
1724
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001725 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001726}
1727
Marin Shalamanov9070c052020-05-18 19:05:17 +02001728void BootAnimation::processDisplayEvents() {
1729 // This will poll mDisplayEventReceiver and if there are new events it'll call
1730 // displayEventCallback synchronously.
1731 mLooper->pollOnce(0);
1732}
1733
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001734void BootAnimation::handleViewport(nsecs_t timestep) {
1735 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1736 return;
1737 }
1738 if (mTargetInset < 0) {
1739 // Poll the amount for the top display inset. This will return -1 until persistent properties
1740 // have been loaded.
1741 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1742 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1743 }
1744 if (mTargetInset <= 0) {
1745 return;
1746 }
1747
1748 if (mCurrentInset < mTargetInset) {
1749 // After the device boots, the inset will effectively be cropped away. We animate this here.
1750 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1751 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1752
1753 SurfaceComposerClient::Transaction()
1754 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1755 .apply();
1756 } else {
1757 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1758 // later. This changes the coordinate system, and means we must move the surface up by
1759 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001760 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1761 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1762
1763 SurfaceComposerClient::Transaction t;
1764 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1765 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001766 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001767 t.apply();
1768
1769 mTargetInset = mCurrentInset = 0;
1770 }
1771
1772 int delta = timestep * mTargetInset / ms2ns(200);
1773 mCurrentInset += delta;
1774}
1775
Marin Shalamanov9070c052020-05-18 19:05:17 +02001776void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001777 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1778 e = animation->parts.end(); it != e; ++it) {
1779 if (it->animation)
1780 releaseAnimation(it->animation);
1781 }
1782 if (animation->zip)
1783 delete animation->zip;
1784 delete animation;
1785}
1786
Marin Shalamanov9070c052020-05-18 19:05:17 +02001787BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001788 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001789 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001790 fn.c_str());
Yi Kong911ac232019-03-24 01:49:02 -07001791 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001792 }
1793 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001794 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001795 SLOGE("Failed to open animation zip \"%s\": %s",
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001796 fn.c_str(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001797 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001798 }
1799
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001800 ALOGD("%s is loaded successfully", fn.c_str());
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001801
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001802 Animation *animation = new Animation;
1803 animation->fileName = fn;
1804 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001805 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001806 mLoadedFiles.add(animation->fileName);
1807
1808 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001809 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001810 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001811 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001812 }
1813
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001814 mLoadedFiles.remove(fn);
1815 return animation;
1816}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001817
1818bool BootAnimation::updateIsTimeAccurate() {
1819 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1820 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1821
1822 if (mTimeIsAccurate) {
1823 return true;
1824 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001825 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001826 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001827
1828 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1829 mTimeFormat12Hour = true;
1830 }
1831
Damien Bargiacchi97480862016-03-29 14:55:55 -07001832 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1833 mTimeIsAccurate = true;
1834 return true;
1835 }
1836
1837 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001838 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001839 long long lastChangedTime = 0;
1840 fscanf(file, "%lld", &lastChangedTime);
1841 fclose(file);
1842 if (lastChangedTime > 0) {
1843 struct timespec now;
1844 clock_gettime(CLOCK_REALTIME, &now);
1845 // Match the Java timestamp format
1846 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001847 if (ACCURATE_TIME_EPOCH < rtcNow
1848 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1849 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001850 mTimeIsAccurate = true;
1851 }
1852 }
1853 }
1854
1855 return mTimeIsAccurate;
1856}
1857
1858BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
Josh Yangf95b2002021-12-23 14:32:28 -08001859 mInotifyFd(-1), mBootAnimWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001860
1861BootAnimation::TimeCheckThread::~TimeCheckThread() {
1862 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1863 close(mInotifyFd);
1864}
1865
1866bool BootAnimation::TimeCheckThread::threadLoop() {
1867 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1868 && mBootAnimation->mClockEnabled;
1869 if (!shouldLoop) {
1870 close(mInotifyFd);
1871 mInotifyFd = -1;
1872 }
1873 return shouldLoop;
1874}
1875
1876bool BootAnimation::TimeCheckThread::doThreadLoop() {
1877 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1878
1879 // Poll instead of doing a blocking read so the Thread can exit if requested.
1880 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1881 ssize_t pollResult = poll(&pfd, 1, 1000);
1882
1883 if (pollResult == 0) {
1884 return true;
1885 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001886 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001887 return false;
1888 }
1889
1890 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1891 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1892 if (length == 0) {
1893 return true;
1894 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001895 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001896 return false;
1897 }
1898
1899 const struct inotify_event *event;
1900 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1901 event = (const struct inotify_event *) ptr;
Josh Yangf95b2002021-12-23 14:32:28 -08001902 if (event->wd == mBootAnimWd && strcmp(BOOTANIM_TIME_DIR_NAME, event->name) == 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001903 addTimeDirWatch();
1904 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1905 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1906 return !mBootAnimation->updateIsTimeAccurate();
1907 }
1908 }
1909
1910 return true;
1911}
1912
1913void BootAnimation::TimeCheckThread::addTimeDirWatch() {
Josh Yangf95b2002021-12-23 14:32:28 -08001914 mTimeWd = inotify_add_watch(mInotifyFd, BOOTANIM_TIME_DIR_PATH,
Damien Bargiacchi97480862016-03-29 14:55:55 -07001915 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1916 if (mTimeWd > 0) {
1917 // No need to watch for the time directory to be created if it already exists
Josh Yangf95b2002021-12-23 14:32:28 -08001918 inotify_rm_watch(mInotifyFd, mBootAnimWd);
1919 mBootAnimWd = -1;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001920 }
1921}
1922
1923status_t BootAnimation::TimeCheckThread::readyToRun() {
1924 mInotifyFd = inotify_init();
1925 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001926 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001927 return NO_INIT;
1928 }
1929
Josh Yangf95b2002021-12-23 14:32:28 -08001930 mBootAnimWd = inotify_add_watch(mInotifyFd, BOOTANIM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1931 if (mBootAnimWd < 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001932 close(mInotifyFd);
1933 mInotifyFd = -1;
Josh Yangf95b2002021-12-23 14:32:28 -08001934 SLOGE("Could not add watch for %s: %s", BOOTANIM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001935 return NO_INIT;
1936 }
1937
1938 addTimeDirWatch();
1939
1940 if (mBootAnimation->updateIsTimeAccurate()) {
1941 close(mInotifyFd);
1942 mInotifyFd = -1;
1943 return ALREADY_EXISTS;
1944 }
1945
1946 return NO_ERROR;
1947}
1948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949// ---------------------------------------------------------------------------
1950
Marin Shalamanov9070c052020-05-18 19:05:17 +02001951} // namespace android