blob: f8706b3e65d6ce59185d698f9e041e31a30e9869 [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";
Keun-young Parkb5938422017-03-23 13:46:24 -070075static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090076static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070077static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
78
Nikita Ioffe06c986e2020-01-27 17:16:03 +000079static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
80static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
81static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
82
Josh Yangf95b2002021-12-23 14:32:28 -080083static const char BOOTANIM_DATA_DIR_PATH[] = "/data/bootanim";
84static const char BOOTANIM_TIME_DIR_NAME[] = "time";
85static const char BOOTANIM_TIME_DIR_PATH[] = "/data/bootanim/time";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070086static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
87static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +000088static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
89static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
Damien Bargiacchi97480862016-03-29 14:55:55 -070090static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
Josh Yangf95b2002021-12-23 14:32:28 -080091static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/bootanim/time/last_time_change";
Damien Bargiacchi97480862016-03-29 14:55:55 -070092static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
Josh Yangf95b2002021-12-23 14:32:28 -080093static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/bootanim/time/time_is_accurate";
94static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/bootanim/time/time_format_12_hour";
Damien Bargiacchi96762812016-07-12 15:53:40 -070095// Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
96static const long long ACCURATE_TIME_EPOCH = 946684800000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070097static constexpr char FONT_BEGIN_CHAR = ' ';
98static constexpr char FONT_END_CHAR = '~' + 1;
99static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
100static constexpr size_t FONT_NUM_COLS = 16;
101static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
102static const int TEXT_CENTER_VALUE = INT_MAX;
103static const int TEXT_MISSING_VALUE = INT_MIN;
Damien Bargiacchi97480862016-03-29 14:55:55 -0700104static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000105static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
Huihong Luod4a217e2020-01-16 15:56:33 -0800106static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
Thiébaud Weksteen08de4432021-11-18 13:25:59 +1100107static const char CLOCK_ENABLED_PROP_NAME[] = "persist.sys.bootanim.clock.enabled";
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +0900108static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
niuwenchao9cd6ac82022-12-23 17:34:22 +0800109static const int MAX_CHECK_EXIT_INTERVAL_US = 50000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700110static constexpr size_t TEXT_POS_LEN_MAX = 16;
Shan Huang2b31a362021-08-16 16:45:39 +0000111static const int DYNAMIC_COLOR_COUNT = 4;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000112static const char U_TEXTURE[] = "uTexture";
113static const char U_FADE[] = "uFade";
114static const char U_CROP_AREA[] = "uCropArea";
Shan Huang2b31a362021-08-16 16:45:39 +0000115static const char U_START_COLOR_PREFIX[] = "uStartColor";
116static const char U_END_COLOR_PREFIX[] = "uEndColor";
117static const char U_COLOR_PROGRESS[] = "uColorProgress";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000118static const char A_UV[] = "aUv";
119static const char A_POSITION[] = "aPosition";
120static const char VERTEX_SHADER_SOURCE[] = R"(
121 precision mediump float;
122 attribute vec4 aPosition;
123 attribute highp vec2 aUv;
124 varying highp vec2 vUv;
125 void main() {
126 gl_Position = aPosition;
127 vUv = aUv;
128 })";
Shan Huang2b31a362021-08-16 16:45:39 +0000129static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
130 precision mediump float;
Shan Huang81846ba2021-09-07 19:07:47 +0000131 const float cWhiteMaskThreshold = 0.05;
Shan Huang2b31a362021-08-16 16:45:39 +0000132 uniform sampler2D uTexture;
133 uniform float uFade;
134 uniform float uColorProgress;
Andrew Zengf9f58222022-11-08 11:10:48 -0800135 uniform vec3 uStartColor0;
136 uniform vec3 uStartColor1;
137 uniform vec3 uStartColor2;
138 uniform vec3 uStartColor3;
139 uniform vec3 uEndColor0;
140 uniform vec3 uEndColor1;
141 uniform vec3 uEndColor2;
142 uniform vec3 uEndColor3;
Shan Huang2b31a362021-08-16 16:45:39 +0000143 varying highp vec2 vUv;
144 void main() {
145 vec4 mask = texture2D(uTexture, vUv);
Shan Huang488ff742021-08-25 20:10:46 +0000146 float r = mask.r;
147 float g = mask.g;
148 float b = mask.b;
149 float a = mask.a;
150 // If all channels have values, render pixel as a shade of white.
151 float useWhiteMask = step(cWhiteMaskThreshold, r)
152 * step(cWhiteMaskThreshold, g)
153 * step(cWhiteMaskThreshold, b)
154 * step(cWhiteMaskThreshold, a);
Andrew Zengf9f58222022-11-08 11:10:48 -0800155 vec3 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
Shan Huang488ff742021-08-25 20:10:46 +0000156 + g * mix(uStartColor1, uEndColor1, uColorProgress)
157 + b * mix(uStartColor2, uEndColor2, uColorProgress)
158 + a * mix(uStartColor3, uEndColor3, uColorProgress);
Andrew Zengf9f58222022-11-08 11:10:48 -0800159 color = mix(color, vec3((r + g + b + a) * 0.25), useWhiteMask);
160 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade));
Shan Huang2b31a362021-08-16 16:45:39 +0000161 })";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000162static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
163 precision mediump float;
164 uniform sampler2D uTexture;
165 uniform float uFade;
166 varying highp vec2 vUv;
167 void main() {
168 vec4 color = texture2D(uTexture, vUv);
Shan Huang2b31a362021-08-16 16:45:39 +0000169 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000170 })";
171static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
172 precision mediump float;
173 uniform sampler2D uTexture;
174 uniform vec4 uCropArea;
175 varying highp vec2 vUv;
176 void main() {
177 vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
178 mix(uCropArea.y, uCropArea.w, vUv.y));
179 gl_FragColor = texture2D(uTexture, uv);
180 })";
181
182static GLfloat quadPositions[] = {
183 -0.5f, -0.5f,
184 +0.5f, -0.5f,
185 +0.5f, +0.5f,
186 +0.5f, +0.5f,
187 -0.5f, +0.5f,
188 -0.5f, -0.5f
189};
190static GLfloat quadUVs[] = {
191 0.0f, 1.0f,
192 1.0f, 1.0f,
193 1.0f, 0.0f,
194 1.0f, 0.0f,
195 0.0f, 0.0f,
196 0.0f, 1.0f
197};
Narayan Kamathafd31e02013-12-03 13:16:03 +0000198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199// ---------------------------------------------------------------------------
200
Ed Coyne7464ac92017-06-08 12:26:48 -0700201BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200202 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700203 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700204 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400205
Keun-young Parkb5938422017-03-23 13:46:24 -0700206 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
207 if (powerCtl.empty()) {
208 mShuttingDown = false;
209 } else {
210 mShuttingDown = true;
211 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700212 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
213 elapsedRealtime());
214}
215
216BootAnimation::~BootAnimation() {
217 if (mAnimation != nullptr) {
218 releaseAnimation(mAnimation);
219 mAnimation = nullptr;
220 }
221 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
222 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223}
224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700226 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700227 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700228 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700229 // Load the animation content -- this can be slow (eg 200ms)
230 // called before waitForSurfaceFlinger() in main() to avoid wait
231 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
232 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
233 preloadAnimation();
234 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
235 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
Mathias Agopianbc726112009-09-23 15:44:05 -0700236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237}
238
Mathias Agopianbc726112009-09-23 15:44:05 -0700239sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 return mSession;
241}
242
Marin Shalamanov9070c052020-05-18 19:05:17 +0200243void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700244 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700245 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700246
247 // calling requestExit() is not enough here because the Surface code
248 // might be blocked on a condition variable that will never be updated.
249 kill( getpid(), SIGKILL );
250 requestExit();
251}
252
Shan Huang2b31a362021-08-16 16:45:39 +0000253static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
254 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400255 AImageDecoder* decoder = nullptr;
256 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
257 if (!decoder) {
258 return nullptr;
259 }
260
261 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
262 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
263 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
264 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
265 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
266 outInfo->flags = 0;
267
Shan Huang2b31a362021-08-16 16:45:39 +0000268 if (!premultiplyAlpha) {
269 AImageDecoder_setUnpremultipliedRequired(decoder, true);
270 }
271
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400272 const size_t size = outInfo->stride * outInfo->height;
273 void* pixels = malloc(size);
274 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
275 AImageDecoder_delete(decoder);
276
277 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
278 free(pixels);
279 return nullptr;
280 }
281 return pixels;
282}
283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
Shan Huang2b31a362021-08-16 16:45:39 +0000285 const char* name, bool premultiplyAlpha) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700287 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400289
290 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000291 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
292 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400293 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 asset->close();
296 delete asset;
297
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400298 if (!pixels) {
299 return NO_INIT;
300 }
301
302 const int w = bitmapInfo.width;
303 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 texture->w = w;
306 texture->h = h;
307
308 glGenTextures(1, &texture->name);
309 glBindTexture(GL_TEXTURE_2D, texture->name);
310
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400311 switch (bitmapInfo.format) {
312 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400314 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400316 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400318 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400320 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400322 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400324 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400326 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 break;
328 default:
329 break;
330 }
331
Lucas Dupin8eedc022021-07-29 21:49:07 +0000332 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
333 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
334 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
335 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 return NO_ERROR;
338}
339
Shan Huang2b31a362021-08-16 16:45:39 +0000340status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
341 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400342 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000343 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
344 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400345 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700346
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200347 // FileMap memory is never released until application exit.
348 // Release it now as the texture is already loaded and the memory used for
349 // the packed resource can be released.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700350 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200351
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400352 if (!pixels) {
353 return NO_INIT;
354 }
355
356 const int w = bitmapInfo.width;
357 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700358
Mathias Agopiana8826d62009-10-01 03:10:14 -0700359 int tw = 1 << (31 - __builtin_clz(w));
360 int th = 1 << (31 - __builtin_clz(h));
361 if (tw < w) tw <<= 1;
362 if (th < h) th <<= 1;
363
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400364 switch (bitmapInfo.format) {
365 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530366 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700367 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700368 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700369 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400370 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700371 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530372 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400373 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700374 }
375 break;
376
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400377 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530378 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700379 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700380 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700381 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400382 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700383 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530384 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400385 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700386 }
387 break;
388 default:
389 break;
390 }
391
niuwenchaoa76df892023-09-11 17:19:04 +0800392 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
393 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000394 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
395 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700396
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700397 *width = w;
398 *height = h;
399
Mathias Agopiana8826d62009-10-01 03:10:14 -0700400 return NO_ERROR;
401}
402
Marin Shalamanov9070c052020-05-18 19:05:17 +0200403class BootAnimation::DisplayEventCallback : public LooperCallback {
404 BootAnimation* mBootAnimation;
405
406public:
407 DisplayEventCallback(BootAnimation* bootAnimation) {
408 mBootAnimation = bootAnimation;
409 }
410
411 int handleEvent(int /* fd */, int events, void* /* data */) {
412 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
413 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
414 events);
415 return 0; // remove the callback
416 }
417
418 if (!(events & Looper::EVENT_INPUT)) {
419 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
420 return 1; // keep the callback
421 }
422
423 constexpr int kBufferSize = 100;
424 DisplayEventReceiver::Event buffer[kBufferSize];
425 ssize_t numEvents;
426 do {
427 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
428 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
429 const auto& event = buffer[i];
430 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
431 SLOGV("Hotplug received");
432
433 if (!event.hotplug.connected) {
434 // ignore hotplug disconnect
435 continue;
436 }
437 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
438 event.header.displayId);
439
440 if (token != mBootAnimation->mDisplayToken) {
441 // ignore hotplug of a secondary display
442 continue;
443 }
444
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100445 DisplayMode displayMode;
446 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
447 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200448 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100449 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200450 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100451 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
452 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200453 }
454 }
455 } while (numEvents > 0);
456
457 return 1; // keep the callback
458 }
459};
460
461EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
462 const EGLint attribs[] = {
Andrii Chepurnyid93f7b22023-03-15 11:22:07 +0200463 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
Marin Shalamanov9070c052020-05-18 19:05:17 +0200464 EGL_RED_SIZE, 8,
465 EGL_GREEN_SIZE, 8,
466 EGL_BLUE_SIZE, 8,
467 EGL_DEPTH_SIZE, 0,
468 EGL_NONE
469 };
470 EGLint numConfigs;
471 EGLConfig config;
472 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
473 return config;
474}
475
Marin Shalamanov047802d2020-05-19 23:55:12 +0200476ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
477 ui::Size limited(width, height);
478 bool wasLimited = false;
479 const float aspectRatio = float(width) / float(height);
480 if (mMaxWidth != 0 && width > mMaxWidth) {
481 limited.height = mMaxWidth / aspectRatio;
482 limited.width = mMaxWidth;
483 wasLimited = true;
484 }
485 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
486 limited.height = mMaxHeight;
487 limited.width = mMaxHeight * aspectRatio;
488 wasLimited = true;
489 }
490 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
491 limited.width, limited.height, width, height);
492 return limited;
493}
494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495status_t BootAnimation::readyToRun() {
496 mAssets.addDefaultAssets();
497
Huihong Luo44305102022-09-26 11:16:20 -0700498 const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds();
499 if (ids.empty()) {
500 SLOGE("Failed to get ID for any displays\n");
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800501 return NAME_NOT_FOUND;
Huihong Luo44305102022-09-26 11:16:20 -0700502 }
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800503
Huihong Luo44305102022-09-26 11:16:20 -0700504 // this system property specifies multi-display IDs to show the boot animation
Huihong Luof97c9e22019-05-29 11:08:01 -0700505 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800506 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200507 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700508 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800509 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700510 bool isValid = displayValue[0] != '\0';
511 if (isValid) {
512 char *p = displayValue;
513 while (*p) {
514 if (!isdigit(*p) && *p != ',') {
515 isValid = false;
516 break;
517 }
518 p ++;
519 }
520 if (!isValid)
Huihong Luod4a217e2020-01-16 15:56:33 -0800521 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700522 }
523 if (isValid) {
524 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200525 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700526 physicalDisplayIds.add(id);
527 if (stream.peek() == ',')
528 stream.ignore();
529 }
530
Huihong Luo44305102022-09-26 11:16:20 -0700531 // the first specified display id is used to retrieve mDisplayToken
532 for (const auto id : physicalDisplayIds) {
533 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
534 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
535 mDisplayToken = token;
536 break;
537 }
538 }
539 }
540 }
541
542 // If the system property is not present or invalid, display 0 is used
543 if (mDisplayToken == nullptr) {
544 mDisplayToken = SurfaceComposerClient::getPhysicalDisplayToken(ids.front());
545 if (mDisplayToken == nullptr) {
546 return NAME_NOT_FOUND;
547 }
548 }
549
550 DisplayMode displayMode;
551 const status_t error =
552 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
553 if (error != NO_ERROR) {
554 return error;
555 }
556
557 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
558 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
559 ui::Size resolution = displayMode.resolution;
560 resolution = limitSurfaceSize(resolution.width, resolution.height);
561 // create the native surface
562 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
563 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565,
564 ISurfaceComposerClient::eOpaque);
565
566 SurfaceComposerClient::Transaction t;
567 if (isValid) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700568 // In the case of multi-display, boot animation shows on the specified displays
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700569 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700570 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700571 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
572 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
573 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700574 }
575 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700576 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700577 }
578
Robert Carre13b58e2017-08-31 14:50:44 -0700579 t.setLayer(control, 0x40000000)
580 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581
Mathias Agopian17f638b2009-04-16 20:04:08 -0700582 sp<Surface> s = control->getSurface();
583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700586 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200587 EGLConfig config = getEglConfig(display);
588 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000589 // Initialize egl context with client version number 2.0.
590 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
591 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200592 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 eglQuerySurface(display, surface, EGL_WIDTH, &w);
594 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700595
Huihong Luo44305102022-09-26 11:16:20 -0700596 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
Mathias Agopianabac0102009-07-31 14:47:00 -0700597 return NO_INIT;
Huihong Luo44305102022-09-26 11:16:20 -0700598 }
Mathias Agopiana8826d62009-10-01 03:10:14 -0700599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 mDisplay = display;
601 mContext = context;
602 mSurface = surface;
joenchen85b339f2022-04-11 23:58:34 +0800603 mInitWidth = mWidth = w;
604 mInitHeight = mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700605 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200607 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000609 // Rotate the boot animation according to the value specified in the sysprop
610 // ro.bootanim.set_orientation_<display_id>. Four values are supported: ORIENTATION_0,
611 // ORIENTATION_90, ORIENTATION_180 and ORIENTATION_270.
612 // If the value isn't specified or is ORIENTATION_0, nothing will be changed.
613 // This is needed to support having boot animation in orientations different from the natural
614 // device orientation. For example, on tablets that may want to keep natural orientation
615 // portrait for applications compatibility and to have the boot animation in landscape.
616 rotateAwayFromNaturalOrientationIfNeeded();
617
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200618 projectSceneToWindow();
619
Marin Shalamanov9070c052020-05-18 19:05:17 +0200620 // Register a display event receiver
621 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
622 status_t status = mDisplayEventReceiver->initCheck();
623 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
624 status);
625 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
626 new DisplayEventCallback(this), nullptr);
627
Huihong Luo50a2f362018-08-11 09:27:57 -0700628 return NO_ERROR;
629}
630
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000631void BootAnimation::rotateAwayFromNaturalOrientationIfNeeded() {
632 const auto orientation = parseOrientationProperty();
633
634 if (orientation == ui::ROTATION_0) {
635 // Do nothing if the sysprop isn't set or is set to ROTATION_0.
636 return;
637 }
638
639 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
640 std::swap(mWidth, mHeight);
641 std::swap(mInitWidth, mInitHeight);
642 mFlingerSurfaceControl->updateDefaultBufferSize(mWidth, mHeight);
643 }
644
645 Rect displayRect(0, 0, mWidth, mHeight);
646 Rect layerStackRect(0, 0, mWidth, mHeight);
647
648 SurfaceComposerClient::Transaction t;
649 t.setDisplayProjection(mDisplayToken, orientation, layerStackRect, displayRect);
650 t.apply();
651}
652
653ui::Rotation BootAnimation::parseOrientationProperty() {
654 const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
655 if (displayIds.size() == 0) {
656 return ui::ROTATION_0;
657 }
658 const auto displayId = displayIds[0];
659 const auto syspropName = [displayId] {
660 std::stringstream ss;
661 ss << "ro.bootanim.set_orientation_" << displayId.value;
662 return ss.str();
663 }();
664 const auto syspropValue = android::base::GetProperty(syspropName, "ORIENTATION_0");
665 if (syspropValue == "ORIENTATION_90") {
666 return ui::ROTATION_90;
667 } else if (syspropValue == "ORIENTATION_180") {
668 return ui::ROTATION_180;
669 } else if (syspropValue == "ORIENTATION_270") {
670 return ui::ROTATION_270;
671 }
672 return ui::ROTATION_0;
673}
674
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200675void BootAnimation::projectSceneToWindow() {
676 glViewport(0, 0, mWidth, mHeight);
677 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200678}
679
Marin Shalamanov9070c052020-05-18 19:05:17 +0200680void BootAnimation::resizeSurface(int newWidth, int newHeight) {
681 // We assume this function is called on the animation thread.
682 if (newWidth == mWidth && newHeight == mHeight) {
683 return;
684 }
685 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
686
687 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
688 eglDestroySurface(mDisplay, mSurface);
689
joenchen85b339f2022-04-11 23:58:34 +0800690 mFlingerSurfaceControl->updateDefaultBufferSize(newWidth, newHeight);
Marin Shalamanov047802d2020-05-19 23:55:12 +0200691 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
692 mWidth = limitedSize.width;
693 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200694
Marin Shalamanov9070c052020-05-18 19:05:17 +0200695 EGLConfig config = getEglConfig(mDisplay);
696 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
697 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
698 SLOGE("Can't make the new surface current. Error %d", eglGetError());
699 return;
700 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200701
702 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200703
704 mSurface = surface;
705}
706
Huihong Luo50a2f362018-08-11 09:27:57 -0700707bool BootAnimation::preloadAnimation() {
708 findBootAnimationFile();
Tomasz Wasilczyke8fb3c72023-08-24 19:11:22 +0000709 if (!mZipFileName.empty()) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700710 mAnimation = loadAnimation(mZipFileName);
711 return (mAnimation != nullptr);
712 }
713
714 return false;
715}
716
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000717bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
718 for (const std::string& f : files) {
719 if (access(f.c_str(), R_OK) == 0) {
720 mZipFileName = f.c_str();
721 return true;
722 }
723 }
724 return false;
725}
726
Huihong Luo50a2f362018-08-11 09:27:57 -0700727void BootAnimation::findBootAnimationFile() {
Beverly34ffe252019-05-17 11:03:54 -0400728 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000729 static const std::vector<std::string> bootFiles = {
730 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
731 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
732 };
733 static const std::vector<std::string> shutdownFiles = {
734 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
735 };
736 static const std::vector<std::string> userspaceRebootFiles = {
737 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
738 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
739 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700740
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000741 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
742 findBootAnimationFileInternal(userspaceRebootFiles);
743 } else if (mShuttingDown) {
744 findBootAnimationFileInternal(shutdownFiles);
745 } else {
746 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748}
749
Lucas Dupin8eedc022021-07-29 21:49:07 +0000750GLuint compileShader(GLenum shaderType, const GLchar *source) {
751 GLuint shader = glCreateShader(shaderType);
752 glShaderSource(shader, 1, &source, 0);
753 glCompileShader(shader);
754 GLint isCompiled = 0;
755 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
756 if (isCompiled == GL_FALSE) {
757 SLOGE("Compile shader failed. Shader type: %d", shaderType);
Shan Huang81846ba2021-09-07 19:07:47 +0000758 GLint maxLength = 0;
759 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
760 std::vector<GLchar> errorLog(maxLength);
761 glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
762 SLOGE("Shader compilation error: %s", &errorLog[0]);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000763 return 0;
764 }
765 return shader;
766}
767
768GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
769 GLuint program = glCreateProgram();
770 glAttachShader(program, vertexShader);
771 glAttachShader(program, fragmentShader);
772 glLinkProgram(program);
773 GLint isLinked = 0;
774 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
775 if (isLinked == GL_FALSE) {
776 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
777 vertexShader, fragmentShader);
778 return 0;
779 }
780 return program;
781}
782
783void BootAnimation::initShaders() {
Shan Huang2b31a362021-08-16 16:45:39 +0000784 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000785 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
786 GLuint imageFragmentShader =
Shan Huang2b31a362021-08-16 16:45:39 +0000787 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
788 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
789 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000790 GLuint textFragmentShader =
791 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
792
793 // Initialize image shader.
794 mImageShader = linkShader(vertexShader, imageFragmentShader);
795 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
796 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
797 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
798 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
799 glEnableVertexAttribArray(positionLocation);
800 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
801 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
802 glEnableVertexAttribArray(uvLocation);
803
804 // Initialize text shader.
805 mTextShader = linkShader(vertexShader, textFragmentShader);
806 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
807 uvLocation = glGetAttribLocation(mTextShader, A_UV);
808 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
809 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
810 glEnableVertexAttribArray(positionLocation);
811 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
812 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
813 glEnableVertexAttribArray(uvLocation);
814}
815
Marin Shalamanov9070c052020-05-18 19:05:17 +0200816bool BootAnimation::threadLoop() {
817 bool result;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000818 initShaders();
819
Narayan Kamathafd31e02013-12-03 13:16:03 +0000820 // We have no bootanimation file, so we use the stock android logo
821 // animation.
Tomasz Wasilczyke8fb3c72023-08-24 19:11:22 +0000822 if (mZipFileName.empty()) {
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +0900823 ALOGD("No animation file");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200824 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700825 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200826 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700827 }
828
Philip Junker60600562020-11-25 18:16:16 +0100829 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
831 eglDestroyContext(mDisplay, mContext);
832 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700833 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700834 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700835 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530836 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700837 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200838 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839}
840
Marin Shalamanov9070c052020-05-18 19:05:17 +0200841bool BootAnimation::android() {
Lucas Dupin8eedc022021-07-29 21:49:07 +0000842 glActiveTexture(GL_TEXTURE0);
843
Wei Wang159a4102018-10-23 23:15:58 -0700844 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700845 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700846 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
847 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848
Ed Coyne7464ac92017-06-08 12:26:48 -0700849 mCallbacks->init({});
850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700852 glDisable(GL_DITHER);
853 glDisable(GL_SCISSOR_TEST);
Shan Huangbfd2d3c2021-09-09 23:19:04 +0000854 glUseProgram(mImageShader);
855
Mathias Agopian59f19e42011-05-06 19:22:12 -0700856 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 glClear(GL_COLOR_BUFFER_BIT);
858 eglSwapBuffers(mDisplay, mSurface);
859
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700860 // Blend state
861 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 const nsecs_t startTime = systemTime();
864 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200865 processDisplayEvents();
866 const GLint xc = (mWidth - mAndroid[0].w) / 2;
867 const GLint yc = (mHeight - mAndroid[0].h) / 2;
868 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
869 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
870 updateRect.height());
871
Mathias Agopian13796652009-03-24 22:49:21 -0700872 nsecs_t now = systemTime();
873 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700874 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
875 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
876 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877
Mathias Agopian81668642009-07-28 11:41:30 -0700878 glDisable(GL_SCISSOR_TEST);
879 glClear(GL_COLOR_BUFFER_BIT);
880
881 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000884 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
885 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700887 glEnable(GL_BLEND);
888 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000889 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890
Mathias Agopian627e7b52009-05-21 19:21:59 -0700891 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
892 if (res == EGL_FALSE)
893 break;
894
Mathias Agopian13796652009-03-24 22:49:21 -0700895 // 12fps: don't animate too fast to preserve CPU
896 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
897 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700898 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700899
900 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 } while (!exitPending());
902
903 glDeleteTextures(1, &mAndroid[0].name);
904 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 return false;
906}
907
Kevin Hesterd3782b22012-04-26 10:38:55 -0700908void BootAnimation::checkExit() {
909 // Allow surface flinger to gracefully request shutdown
910 char value[PROPERTY_VALUE_MAX];
911 property_get(EXIT_PROP_NAME, value, "0");
912 int exitnow = atoi(value);
913 if (exitnow) {
914 requestExit();
915 }
916}
917
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700918bool BootAnimation::validClock(const Animation::Part& part) {
919 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
920}
921
922bool parseTextCoord(const char* str, int* dest) {
923 if (strcmp("c", str) == 0) {
924 *dest = TEXT_CENTER_VALUE;
925 return true;
926 }
927
928 char* end;
929 int val = (int) strtol(str, &end, 0);
930 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
931 return false;
932 }
933 *dest = val;
934 return true;
935}
936
937// Parse two position coordinates. If only string is non-empty, treat it as the y value.
938void parsePosition(const char* str1, const char* str2, int* x, int* y) {
939 bool success = false;
940 if (strlen(str1) == 0) { // No values were specified
941 // success = false
942 } else if (strlen(str2) == 0) { // we have only one value
943 if (parseTextCoord(str1, y)) {
944 *x = TEXT_CENTER_VALUE;
945 success = true;
946 }
947 } else {
948 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
949 success = true;
950 }
951 }
952
953 if (!success) {
954 *x = TEXT_MISSING_VALUE;
955 *y = TEXT_MISSING_VALUE;
956 }
957}
958
Jesse Hall083b84c2014-09-22 10:51:09 -0700959// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
960// characters in str is a hex number in [0, 255], which are converted to
961// floating point values in the range [0.0, 1.0] and placed in the
962// corresponding elements of color.
963//
964// If the input string isn't valid, parseColor returns false and color is
965// left unchanged.
966static bool parseColor(const char str[7], float color[3]) {
967 float tmpColor[3];
968 for (int i = 0; i < 3; i++) {
969 int val = 0;
970 for (int j = 0; j < 2; j++) {
971 val *= 16;
972 char c = str[2*i + j];
973 if (c >= '0' && c <= '9') val += c - '0';
974 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
975 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
976 else return false;
977 }
978 tmpColor[i] = static_cast<float>(val) / 255.0f;
979 }
980 memcpy(color, tmpColor, sizeof(tmpColor));
981 return true;
982}
983
Shan Huang2b31a362021-08-16 16:45:39 +0000984// Parse a color represented as a signed decimal int string.
985// E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
986// If the input color string is empty, set color with values in defaultColor.
987static void parseColorDecimalString(const std::string& colorString,
988 float color[3], float defaultColor[3]) {
989 if (colorString == "") {
990 memcpy(color, defaultColor, sizeof(float) * 3);
991 return;
992 }
993 int colorInt = atoi(colorString.c_str());
994 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
995 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
996 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
997}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700998
Marin Shalamanov9070c052020-05-18 19:05:17 +0200999static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001000 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -07001001 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001002 if (!entry) {
1003 return false;
1004 }
1005
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001006 FileMap* entryMap = zip->createEntryFileMap(entry);
1007 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -07001008 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001009 if (!entryMap) {
1010 return false;
1011 }
1012
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001013 outString = String8((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +00001014 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001015 return true;
1016}
1017
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001018// The font image should be a 96x2 array of character images. The
1019// columns are the printable ASCII characters 0x20 - 0x7f. The
1020// top row is regular text; the bottom row is bold.
1021status_t BootAnimation::initFont(Font* font, const char* fallback) {
1022 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001023
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001024 if (font->map != nullptr) {
1025 glGenTextures(1, &font->texture.name);
1026 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001027
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001028 status = initTexture(font->map, &font->texture.w, &font->texture.h);
1029
Lucas Dupin8eedc022021-07-29 21:49:07 +00001030 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1031 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1032 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1033 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001034 } else if (fallback != nullptr) {
1035 status = initTexture(&font->texture, mAssets, fallback);
1036 } else {
1037 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001038 }
1039
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001040 if (status == NO_ERROR) {
1041 font->char_width = font->texture.w / FONT_NUM_COLS;
1042 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
1043 }
1044
1045 return status;
1046}
1047
1048void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
1049 glEnable(GL_BLEND); // Allow us to draw on top of the animation
1050 glBindTexture(GL_TEXTURE_2D, font.texture.name);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001051 glUseProgram(mTextShader);
1052 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001053
1054 const int len = strlen(str);
1055 const int strWidth = font.char_width * len;
1056
1057 if (*x == TEXT_CENTER_VALUE) {
1058 *x = (mWidth - strWidth) / 2;
1059 } else if (*x < 0) {
1060 *x = mWidth + *x - strWidth;
1061 }
1062 if (*y == TEXT_CENTER_VALUE) {
1063 *y = (mHeight - font.char_height) / 2;
1064 } else if (*y < 0) {
1065 *y = mHeight + *y - font.char_height;
1066 }
1067
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001068 for (int i = 0; i < len; i++) {
1069 char c = str[i];
1070
1071 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1072 c = '?';
1073 }
1074
1075 // Crop the texture to only the pixels in the current glyph
1076 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1077 const int row = charPos / FONT_NUM_COLS;
1078 const int col = charPos % FONT_NUM_COLS;
Lucas Dupin8eedc022021-07-29 21:49:07 +00001079 // Bold fonts are expected in the second half of each row.
1080 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1081 float u0 = ((float)col) / FONT_NUM_COLS;
1082 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1083 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1084 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1085 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001086
1087 *x += font.char_width;
1088 }
1089
1090 glDisable(GL_BLEND); // Return to the animation's default behaviour
1091 glBindTexture(GL_TEXTURE_2D, 0);
1092}
1093
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001094// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001095void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001096 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1097 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001098 static constexpr int TIME_LENGTH = 6;
1099
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001100 time_t rawtime;
1101 time(&rawtime);
1102 struct tm* timeInfo = localtime(&rawtime);
1103
1104 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001105 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1106 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001107
1108 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001109 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001110 mClockEnabled = false;
1111 return;
1112 }
1113
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001114 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001115 int x = xPos;
1116 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001117 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001118}
1119
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001120void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1121 static constexpr int PERCENT_LENGTH = 5;
1122
1123 char percentBuff[PERCENT_LENGTH];
1124 // ';' has the ascii code just after ':', and the font resource contains '%'
1125 // for that ascii code.
1126 sprintf(percentBuff, "%d;", percent);
1127 int x = xPos;
1128 int y = yPos;
1129 drawText(percentBuff, font, false, &x, &y);
1130}
1131
Marin Shalamanov9070c052020-05-18 19:05:17 +02001132bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001133 String8 desString;
1134
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001135 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001136 return false;
1137 }
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001138 char const* s = desString.c_str();
Shan Huang2b31a362021-08-16 16:45:39 +00001139 std::string dynamicColoringPartName = "";
1140 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001141
Mathias Agopiana8826d62009-10-01 03:10:14 -07001142 // Parse the description file
1143 for (;;) {
1144 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001145 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001146 String8 line(s, endl - s);
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001147 const char* l = line.c_str();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001148 int fps = 0;
1149 int width = 0;
1150 int height = 0;
1151 int count = 0;
1152 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001153 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001154 int framesToFadeCount = 0;
Shan Huang488ff742021-08-25 20:10:46 +00001155 int colorTransitionStart = 0;
1156 int colorTransitionEnd = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001157 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001158 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001159 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1160 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang2b31a362021-08-16 16:45:39 +00001161 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001162 char pathType;
Shan Huang2b31a362021-08-16 16:45:39 +00001163 // start colors default to black if unspecified
1164 char start_color_0[7] = "000000";
1165 char start_color_1[7] = "000000";
1166 char start_color_2[7] = "000000";
1167 char start_color_3[7] = "000000";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001168
1169 int nextReadPos;
1170
yidong zhang87bb3462022-12-07 15:55:31 +08001171 if (strlen(l) == 0) {
1172 s = ++endl;
1173 continue;
1174 }
1175
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001176 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1177 if (topLineNumbers == 3 || topLineNumbers == 4) {
1178 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001179 animation.width = width;
1180 animation.height = height;
1181 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001182 if (topLineNumbers == 4) {
1183 animation.progressEnabled = (progress != 0);
1184 } else {
1185 animation.progressEnabled = false;
1186 }
Shan Huang488ff742021-08-25 20:10:46 +00001187 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
Shan Huang2b31a362021-08-16 16:45:39 +00001188 dynamicColoringPartNameBuffer,
Shan Huang488ff742021-08-25 20:10:46 +00001189 start_color_0, start_color_1, start_color_2, start_color_3,
1190 &colorTransitionStart, &colorTransitionEnd)) {
Shan Huang2b31a362021-08-16 16:45:39 +00001191 animation.dynamicColoringEnabled = true;
1192 parseColor(start_color_0, animation.startColors[0]);
1193 parseColor(start_color_1, animation.startColors[1]);
1194 parseColor(start_color_2, animation.startColors[2]);
1195 parseColor(start_color_3, animation.startColors[3]);
Shan Huang488ff742021-08-25 20:10:46 +00001196 animation.colorTransitionStart = colorTransitionStart;
1197 animation.colorTransitionEnd = colorTransitionEnd;
Shan Huang2b31a362021-08-16 16:45:39 +00001198 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001199 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1200 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1201 if (pathType == 'f') {
1202 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1203 clockPos2);
1204 } else {
1205 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1206 }
1207 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1208 // "clockPos1=%s, clockPos2=%s",
1209 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001210 Animation::Part part;
Shan Huang2b31a362021-08-16 16:45:39 +00001211 if (path == dynamicColoringPartName) {
1212 // Part is specified to use dynamic coloring.
1213 part.useDynamicColoring = true;
1214 part.postDynamicColoring = false;
1215 postDynamicColoring = true;
1216 } else {
1217 // Part does not use dynamic coloring.
1218 part.useDynamicColoring = false;
1219 part.postDynamicColoring = postDynamicColoring;
1220 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001221 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001222 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001223 part.count = count;
1224 part.pause = pause;
1225 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001226 part.audioData = nullptr;
1227 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001228 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001229 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001230 part.backgroundColor[0] = 0.0f;
1231 part.backgroundColor[1] = 0.0f;
1232 part.backgroundColor[2] = 0.0f;
1233 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001234 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001235 animation.parts.add(part);
1236 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001237 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001238 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001239 Animation::Part part;
1240 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001241 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001242 part.count = 1;
1243 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001244 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001245 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001246 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001247 animation.parts.add(part);
1248 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001249 s = ++endl;
1250 }
1251
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001252 return true;
1253}
1254
Marin Shalamanov9070c052020-05-18 19:05:17 +02001255bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001256 // read all the data structures
1257 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001258 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001259 ZipFileRO* zip = animation.zip;
1260 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001261 return false;
1262 }
1263
1264 ZipEntryRO entry;
1265 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001266 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001267 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001268 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001269 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001270 continue;
1271 }
1272
Tomasz Wasilczyk9dcea572023-08-22 20:39:20 +00001273 const std::filesystem::path entryName(name);
1274 const std::filesystem::path path(entryName.parent_path());
1275 const std::filesystem::path leaf(entryName.filename());
1276 if (!leaf.empty()) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001277 if (entryName == CLOCK_FONT_ZIP_NAME) {
1278 FileMap* map = zip->createEntryFileMap(entry);
1279 if (map) {
1280 animation.clockFont.map = map;
1281 }
1282 continue;
1283 }
1284
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001285 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1286 FileMap* map = zip->createEntryFileMap(entry);
1287 if (map) {
1288 animation.progressFont.map = map;
1289 }
1290 continue;
1291 }
1292
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001293 for (size_t j = 0; j < pcount; j++) {
Tomasz Wasilczyk9dcea572023-08-22 20:39:20 +00001294 if (path.string() == animation.parts[j].path.c_str()) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001295 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001296 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001297 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001298 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001299 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001300 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001301 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001302 if (leaf == "audio.wav") {
1303 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001304 part.audioData = (uint8_t *)map->getDataPtr();
1305 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001306 } else if (leaf == "trim.txt") {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001307 part.trimData = String8((char const*)map->getDataPtr(),
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001308 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001309 } else {
1310 Animation::Frame frame;
Tomasz Wasilczyk9dcea572023-08-22 20:39:20 +00001311 frame.name = leaf.c_str();
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001312 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001313 frame.trimWidth = animation.width;
1314 frame.trimHeight = animation.height;
1315 frame.trimX = 0;
1316 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001317 part.frames.add(frame);
1318 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001319 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001320 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001321 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001322 }
1323 }
1324 }
1325 }
1326 }
1327 }
1328
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001329 // If there is trimData present, override the positioning defaults.
1330 for (Animation::Part& part : animation.parts) {
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001331 const char* trimDataStr = part.trimData.c_str();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001332 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1333 const char* endl = strstr(trimDataStr, "\n");
1334 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001335 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001336 break;
1337 }
1338 String8 line(trimDataStr, endl - trimDataStr);
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001339 const char* lineStr = line.c_str();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001340 trimDataStr = ++endl;
1341 int width = 0, height = 0, x = 0, y = 0;
1342 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1343 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1344 frame.trimWidth = width;
1345 frame.trimHeight = height;
1346 frame.trimX = x;
1347 frame.trimY = y;
1348 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001349 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001350 break;
1351 }
1352 }
1353 }
1354
1355 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001356
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001357 return true;
1358}
1359
Marin Shalamanov9070c052020-05-18 19:05:17 +02001360bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001361 if (mAnimation == nullptr) {
1362 mAnimation = loadAnimation(mZipFileName);
1363 }
1364
1365 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001366 return false;
1367
Huihong Luo50a2f362018-08-11 09:27:57 -07001368 // mCallbacks->init() may get called recursively,
1369 // this loop is needed to get the same results
1370 for (const Animation::Part& part : mAnimation->parts) {
1371 if (part.animation != nullptr) {
1372 mCallbacks->init(part.animation->parts);
1373 }
1374 }
1375 mCallbacks->init(mAnimation->parts);
1376
Damien Bargiacchi97480862016-03-29 14:55:55 -07001377 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001378 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1379 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001380 anyPartHasClock = true;
1381 break;
1382 }
1383 }
1384 if (!anyPartHasClock) {
1385 mClockEnabled = false;
Thiébaud Weksteen08de4432021-11-18 13:25:59 +11001386 } else if (!android::base::GetBoolProperty(CLOCK_ENABLED_PROP_NAME, false)) {
1387 mClockEnabled = false;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001388 }
1389
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301390 // Check if npot textures are supported
1391 mUseNpotTextures = false;
1392 String8 gl_extensions;
1393 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1394 if (!exts) {
1395 glGetError();
1396 } else {
Tomasz Wasilczyk31eb3c892023-08-23 22:12:33 +00001397 gl_extensions = exts;
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301398 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1399 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1400 mUseNpotTextures = true;
1401 }
1402 }
1403
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001404 // Blend required to draw time on top of animation frames.
1405 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001406 glDisable(GL_DITHER);
1407 glDisable(GL_SCISSOR_TEST);
1408 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001409
Greg Kaiser2ded8002021-07-19 17:03:27 +00001410 glEnable(GL_TEXTURE_2D);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001411 glBindTexture(GL_TEXTURE_2D, 0);
1412 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1413 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1414 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1415 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001416 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001417 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001418 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001419 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001420 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001421 }
1422
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001423 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1424
Damien Bargiacchi97480862016-03-29 14:55:55 -07001425 if (mClockEnabled && !updateIsTimeAccurate()) {
1426 mTimeCheckThread = new TimeCheckThread(this);
1427 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1428 }
1429
George Burgess IV0f8e8112021-08-23 17:32:23 -07001430 if (mAnimation->dynamicColoringEnabled) {
Shan Huang7fee3522021-08-18 00:56:08 +00001431 initDynamicColors();
1432 }
1433
Huihong Luo50a2f362018-08-11 09:27:57 -07001434 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001435
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001436 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001437 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001438 mTimeCheckThread = nullptr;
1439 }
1440
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001441 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001442 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001443 }
1444
Huihong Luo50a2f362018-08-11 09:27:57 -07001445 releaseAnimation(mAnimation);
1446 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001447
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001448 return false;
1449}
1450
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001451bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1452 const int fadedFramesCount,
1453 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001454 // 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 +01001455 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1456 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001457}
1458
Lucas Dupin8eedc022021-07-29 21:49:07 +00001459// Linear mapping from range <a1, a2> to range <b1, b2>
1460float mapLinear(float x, float a1, float a2, float b1, float b2) {
1461 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1462}
1463
1464void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1465 // Map coordinates from screen space to world space.
1466 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1467 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1468 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1469 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1470 // Update quad vertex positions.
1471 quadPositions[0] = x0;
1472 quadPositions[1] = y0;
1473 quadPositions[2] = x1;
1474 quadPositions[3] = y0;
1475 quadPositions[4] = x1;
1476 quadPositions[5] = y1;
1477 quadPositions[6] = x1;
1478 quadPositions[7] = y1;
1479 quadPositions[8] = x0;
1480 quadPositions[9] = y1;
1481 quadPositions[10] = x0;
1482 quadPositions[11] = y0;
1483 glDrawArrays(GL_TRIANGLES, 0,
1484 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1485}
1486
Shan Huang7fee3522021-08-18 00:56:08 +00001487void BootAnimation::initDynamicColors() {
1488 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
Lucas Dupincd256842022-03-29 15:46:36 -07001489 const auto syspropName = "persist.bootanim.color" + std::to_string(i + 1);
1490 const auto syspropValue = android::base::GetProperty(syspropName, "");
1491 if (syspropValue != "") {
1492 SLOGI("Loaded dynamic color: %s -> %s", syspropName.c_str(), syspropValue.c_str());
1493 mDynamicColorsApplied = true;
1494 }
1495 parseColorDecimalString(syspropValue,
Shan Huang7fee3522021-08-18 00:56:08 +00001496 mAnimation->endColors[i], mAnimation->startColors[i]);
1497 }
1498 glUseProgram(mImageShader);
Lucas Dupincd256842022-03-29 15:46:36 -07001499 SLOGI("Dynamically coloring boot animation. Sysprops loaded? %i", mDynamicColorsApplied);
Shan Huang7fee3522021-08-18 00:56:08 +00001500 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1501 float *startColor = mAnimation->startColors[i];
1502 float *endColor = mAnimation->endColors[i];
Andrew Zengf9f58222022-11-08 11:10:48 -08001503 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001504 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001505 startColor[0], startColor[1], startColor[2]);
1506 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001507 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001508 endColor[0], endColor[1], endColor[2]);
Shan Huang7fee3522021-08-18 00:56:08 +00001509 }
1510 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1511}
1512
Marin Shalamanov9070c052020-05-18 19:05:17 +02001513bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001514 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001515 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001516
Wei Wang159a4102018-10-23 23:15:58 -07001517 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001518 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001519
1520 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001521 int lastDisplayedProgress = 0;
Lucas Dupinbfd18122022-04-25 11:26:08 -07001522 int colorTransitionStart = animation.colorTransitionStart;
1523 int colorTransitionEnd = animation.colorTransitionEnd;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001524 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001525 const Animation::Part& part(animation.parts[i]);
1526 const size_t fcount = part.frames.size();
Oleg Lyovin6a4b84d2023-07-01 14:39:59 +03001527 glBindTexture(GL_TEXTURE_2D, 0);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001528
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001529 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001530 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001531 playAnimation(*part.animation);
1532 if (exitPending())
1533 break;
1534 continue; //to next part
1535 }
1536
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001537 // process the part not only while the count allows but also if already fading
1538 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001539 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001540
Lucas Dupinbfd18122022-04-25 11:26:08 -07001541 // It's possible that the sysprops were not loaded yet at this boot phase.
1542 // If that's the case, then we should keep trying until they are available.
1543 if (animation.dynamicColoringEnabled && !mDynamicColorsApplied
1544 && (part.useDynamicColoring || part.postDynamicColoring)) {
1545 SLOGD("Trying to load dynamic color sysprops.");
1546 initDynamicColors();
1547 if (mDynamicColorsApplied) {
1548 // Sysprops were loaded. Next step is to adjust the animation if we loaded
1549 // the colors after the animation should have started.
1550 const int transitionLength = colorTransitionEnd - colorTransitionStart;
1551 if (part.postDynamicColoring) {
1552 colorTransitionStart = 0;
1553 colorTransitionEnd = fmin(transitionLength, fcount - 1);
1554 }
1555 }
1556 }
1557
Ed Coyne7464ac92017-06-08 12:26:48 -07001558 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001559
Jesse Hall083b84c2014-09-22 10:51:09 -07001560 glClearColor(
1561 part.backgroundColor[0],
1562 part.backgroundColor[1],
1563 part.backgroundColor[2],
1564 1.0f);
1565
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001566 ALOGD("Playing files = %s/%s, Requested repeat = %d, playUntilComplete = %s",
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001567 animation.fileName.c_str(), part.path.c_str(), part.count,
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001568 part.playUntilComplete ? "true" : "false");
1569
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001570 // For the last animation, if we have progress indicator from
1571 // the system, display it.
1572 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1573 bool displayProgress = animation.progressEnabled &&
1574 (i == (pcount -1)) && currentProgress != 0;
1575
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001576 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001577 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001578
Shan Huang2b31a362021-08-16 16:45:39 +00001579 // Color progress is
Shan Huang488ff742021-08-25 20:10:46 +00001580 // - the animation progress, normalized from
1581 // [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1582 // part.
Shan Huang2b31a362021-08-16 16:45:39 +00001583 // - 0 for parts that come before,
1584 // - 1 for parts that come after.
1585 float colorProgress = part.useDynamicColoring
Shan Huang488ff742021-08-25 20:10:46 +00001586 ? fmin(fmax(
Lucas Dupinbfd18122022-04-25 11:26:08 -07001587 ((float)j - colorTransitionStart) /
1588 fmax(colorTransitionEnd - colorTransitionStart, 1.0f), 0.0f), 1.0f)
Shan Huang2b31a362021-08-16 16:45:39 +00001589 : (part.postDynamicColoring ? 1 : 0);
1590
Marin Shalamanov9070c052020-05-18 19:05:17 +02001591 processDisplayEvents();
1592
joenchen85b339f2022-04-11 23:58:34 +08001593 const double ratio_w = static_cast<double>(mWidth) / mInitWidth;
1594 const double ratio_h = static_cast<double>(mHeight) / mInitHeight;
1595 const int animationX = (mWidth - animation.width * ratio_w) / 2;
1596 const int animationY = (mHeight - animation.height * ratio_h) / 2;
Marin Shalamanov9070c052020-05-18 19:05:17 +02001597
Mathias Agopiana8826d62009-10-01 03:10:14 -07001598 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001599 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001600
1601 if (r > 0) {
1602 glBindTexture(GL_TEXTURE_2D, frame.tid);
1603 } else {
Oleg Lyovin6a4b84d2023-07-01 14:39:59 +03001604 if (part.count != 1) {
1605 glGenTextures(1, &frame.tid);
1606 glBindTexture(GL_TEXTURE_2D, frame.tid);
1607 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001608 int w, h;
Shan Huang2b31a362021-08-16 16:45:39 +00001609 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1610 // of transparent pixels are preserved.
1611 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001612 }
1613
joenchen85b339f2022-04-11 23:58:34 +08001614 const int trimWidth = frame.trimWidth * ratio_w;
1615 const int trimHeight = frame.trimHeight * ratio_h;
1616 const int trimX = frame.trimX * ratio_w;
1617 const int trimY = frame.trimY * ratio_h;
1618 const int xc = animationX + trimX;
1619 const int yc = animationY + trimY;
Shan Huang2b31a362021-08-16 16:45:39 +00001620 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001621 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1622 // which is equivalent to mHeight - (yc + frame.trimHeight)
joenchen85b339f2022-04-11 23:58:34 +08001623 const int frameDrawY = mHeight - (yc + trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001624
Lucas Dupin8eedc022021-07-29 21:49:07 +00001625 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001626 // if the part hasn't been stopped yet then continue fading if necessary
1627 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001628 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001629 if (fadedFramesCount >= part.framesToFadeCount) {
1630 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1631 }
1632 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001633 glUseProgram(mImageShader);
1634 glUniform1i(mImageTextureLocation, 0);
1635 glUniform1f(mImageFadeLocation, fade);
Shan Huang2b31a362021-08-16 16:45:39 +00001636 if (animation.dynamicColoringEnabled) {
1637 glUniform1f(mImageColorProgressLocation, colorProgress);
1638 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001639 glEnable(GL_BLEND);
joenchen85b339f2022-04-11 23:58:34 +08001640 drawTexturedQuad(xc, frameDrawY, trimWidth, trimHeight);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001641 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001642
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001643 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1644 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001645 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001646
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001647 if (displayProgress) {
1648 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1649 // In case the new progress jumped suddenly, still show an
1650 // increment of 1.
1651 if (lastDisplayedProgress != 100) {
1652 // Artificially sleep 1/10th a second to slow down the animation.
1653 usleep(100000);
1654 if (lastDisplayedProgress < newProgress) {
1655 lastDisplayedProgress++;
1656 }
1657 }
1658 // Put the progress percentage right below the animation.
1659 int posY = animation.height / 3;
1660 int posX = TEXT_CENTER_VALUE;
1661 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1662 }
1663
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001664 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001665
Mathias Agopiana8826d62009-10-01 03:10:14 -07001666 eglSwapBuffers(mDisplay, mSurface);
1667
1668 nsecs_t now = systemTime();
1669 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001670 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001671 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001672
1673 if (delay > 0) {
1674 struct timespec spec;
1675 spec.tv_sec = (now + delay) / 1000000000;
1676 spec.tv_nsec = (now + delay) % 1000000000;
1677 int err;
1678 do {
Yi Kong911ac232019-03-24 01:49:02 -07001679 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Keith Mok0f2e6682021-11-15 05:50:32 +00001680 } while (err == EINTR);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001681 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001682
1683 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001684 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001685
niuwenchao9cd6ac82022-12-23 17:34:22 +08001686 int pauseDuration = part.pause * ns2us(frameDuration);
1687 while(pauseDuration > 0 && !exitPending()){
1688 if (pauseDuration > MAX_CHECK_EXIT_INTERVAL_US) {
1689 usleep(MAX_CHECK_EXIT_INTERVAL_US);
1690 pauseDuration -= MAX_CHECK_EXIT_INTERVAL_US;
1691 } else {
1692 usleep(pauseDuration);
1693 break;
1694 }
1695 checkExit();
1696 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001697
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001698 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1699 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001700 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1701 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1702 continue;
1703 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001704 break; // exit the infinite non-fading part when it has been played at least once
1705 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001706 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001707 }
1708
1709 // Free textures created for looping parts now that the animation is done.
1710 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001711 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001712 const size_t fcount = part.frames.size();
1713 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001714 const Animation::Frame& frame(part.frames[j]);
1715 glDeleteTextures(1, &frame.tid);
1716 }
1717 }
1718 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001719
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001720 ALOGD("%sAnimationShownTiming End time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1721 elapsedRealtime());
1722
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001723 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001724}
1725
Marin Shalamanov9070c052020-05-18 19:05:17 +02001726void BootAnimation::processDisplayEvents() {
1727 // This will poll mDisplayEventReceiver and if there are new events it'll call
1728 // displayEventCallback synchronously.
1729 mLooper->pollOnce(0);
1730}
1731
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001732void BootAnimation::handleViewport(nsecs_t timestep) {
1733 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1734 return;
1735 }
1736 if (mTargetInset < 0) {
1737 // Poll the amount for the top display inset. This will return -1 until persistent properties
1738 // have been loaded.
1739 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1740 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1741 }
1742 if (mTargetInset <= 0) {
1743 return;
1744 }
1745
1746 if (mCurrentInset < mTargetInset) {
1747 // After the device boots, the inset will effectively be cropped away. We animate this here.
1748 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1749 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1750
1751 SurfaceComposerClient::Transaction()
1752 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1753 .apply();
1754 } else {
1755 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1756 // later. This changes the coordinate system, and means we must move the surface up by
1757 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001758 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1759 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1760
1761 SurfaceComposerClient::Transaction t;
1762 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1763 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001764 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001765 t.apply();
1766
1767 mTargetInset = mCurrentInset = 0;
1768 }
1769
1770 int delta = timestep * mTargetInset / ms2ns(200);
1771 mCurrentInset += delta;
1772}
1773
Marin Shalamanov9070c052020-05-18 19:05:17 +02001774void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001775 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1776 e = animation->parts.end(); it != e; ++it) {
1777 if (it->animation)
1778 releaseAnimation(it->animation);
1779 }
1780 if (animation->zip)
1781 delete animation->zip;
1782 delete animation;
1783}
1784
Marin Shalamanov9070c052020-05-18 19:05:17 +02001785BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001786 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001787 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001788 fn.c_str());
Yi Kong911ac232019-03-24 01:49:02 -07001789 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001790 }
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +00001791 ZipFileRO *zip = ZipFileRO::open(fn.c_str());
Yi Kong911ac232019-03-24 01:49:02 -07001792 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001793 SLOGE("Failed to open animation zip \"%s\": %s",
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001794 fn.c_str(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001795 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001796 }
1797
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001798 ALOGD("%s is loaded successfully", fn.c_str());
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001799
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001800 Animation *animation = new Animation;
1801 animation->fileName = fn;
1802 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001803 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001804 mLoadedFiles.add(animation->fileName);
1805
1806 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001807 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001808 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001809 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001810 }
1811
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001812 mLoadedFiles.remove(fn);
1813 return animation;
1814}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001815
1816bool BootAnimation::updateIsTimeAccurate() {
1817 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1818 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1819
1820 if (mTimeIsAccurate) {
1821 return true;
1822 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001823 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001824 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001825
1826 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1827 mTimeFormat12Hour = true;
1828 }
1829
Damien Bargiacchi97480862016-03-29 14:55:55 -07001830 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1831 mTimeIsAccurate = true;
1832 return true;
1833 }
1834
1835 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001836 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001837 long long lastChangedTime = 0;
1838 fscanf(file, "%lld", &lastChangedTime);
1839 fclose(file);
1840 if (lastChangedTime > 0) {
1841 struct timespec now;
1842 clock_gettime(CLOCK_REALTIME, &now);
1843 // Match the Java timestamp format
1844 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001845 if (ACCURATE_TIME_EPOCH < rtcNow
1846 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1847 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001848 mTimeIsAccurate = true;
1849 }
1850 }
1851 }
1852
1853 return mTimeIsAccurate;
1854}
1855
1856BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
Josh Yangf95b2002021-12-23 14:32:28 -08001857 mInotifyFd(-1), mBootAnimWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001858
1859BootAnimation::TimeCheckThread::~TimeCheckThread() {
1860 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1861 close(mInotifyFd);
1862}
1863
1864bool BootAnimation::TimeCheckThread::threadLoop() {
1865 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1866 && mBootAnimation->mClockEnabled;
1867 if (!shouldLoop) {
1868 close(mInotifyFd);
1869 mInotifyFd = -1;
1870 }
1871 return shouldLoop;
1872}
1873
1874bool BootAnimation::TimeCheckThread::doThreadLoop() {
1875 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1876
1877 // Poll instead of doing a blocking read so the Thread can exit if requested.
1878 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1879 ssize_t pollResult = poll(&pfd, 1, 1000);
1880
1881 if (pollResult == 0) {
1882 return true;
1883 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001884 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001885 return false;
1886 }
1887
1888 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1889 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1890 if (length == 0) {
1891 return true;
1892 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001893 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001894 return false;
1895 }
1896
1897 const struct inotify_event *event;
1898 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1899 event = (const struct inotify_event *) ptr;
Josh Yangf95b2002021-12-23 14:32:28 -08001900 if (event->wd == mBootAnimWd && strcmp(BOOTANIM_TIME_DIR_NAME, event->name) == 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001901 addTimeDirWatch();
1902 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1903 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1904 return !mBootAnimation->updateIsTimeAccurate();
1905 }
1906 }
1907
1908 return true;
1909}
1910
1911void BootAnimation::TimeCheckThread::addTimeDirWatch() {
Josh Yangf95b2002021-12-23 14:32:28 -08001912 mTimeWd = inotify_add_watch(mInotifyFd, BOOTANIM_TIME_DIR_PATH,
Damien Bargiacchi97480862016-03-29 14:55:55 -07001913 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1914 if (mTimeWd > 0) {
1915 // No need to watch for the time directory to be created if it already exists
Josh Yangf95b2002021-12-23 14:32:28 -08001916 inotify_rm_watch(mInotifyFd, mBootAnimWd);
1917 mBootAnimWd = -1;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001918 }
1919}
1920
1921status_t BootAnimation::TimeCheckThread::readyToRun() {
1922 mInotifyFd = inotify_init();
1923 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001924 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001925 return NO_INIT;
1926 }
1927
Josh Yangf95b2002021-12-23 14:32:28 -08001928 mBootAnimWd = inotify_add_watch(mInotifyFd, BOOTANIM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1929 if (mBootAnimWd < 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001930 close(mInotifyFd);
1931 mInotifyFd = -1;
Josh Yangf95b2002021-12-23 14:32:28 -08001932 SLOGE("Could not add watch for %s: %s", BOOTANIM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001933 return NO_INIT;
1934 }
1935
1936 addTimeDirWatch();
1937
1938 if (mBootAnimation->updateIsTimeAccurate()) {
1939 close(mInotifyFd);
1940 mInotifyFd = -1;
1941 return ALREADY_EXISTS;
1942 }
1943
1944 return NO_ERROR;
1945}
1946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947// ---------------------------------------------------------------------------
1948
Marin Shalamanov9070c052020-05-18 19:05:17 +02001949} // namespace android