blob: 00d9a4bf05f095bc695fe7cc77c938939d178ea0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -070017#define LOG_NDEBUG 0
Mathias Agopianbc726112009-09-23 15:44:05 -070018#define LOG_TAG "BootAnimation"
19
Nikita Ioffe06c986e2020-01-27 17:16:03 +000020#include <vector>
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022#include <stdint.h>
Wei Wanga90c54c2017-02-02 11:35:21 -080023#include <inttypes.h>
Damien Bargiacchi97480862016-03-29 14:55:55 -070024#include <sys/inotify.h>
25#include <sys/poll.h>
26#include <sys/stat.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#include <sys/types.h>
28#include <math.h>
29#include <fcntl.h>
30#include <utils/misc.h>
Mathias Agopianb4d5a722009-09-23 17:05:19 -070031#include <signal.h>
Elliott Hughesbb94f312014-10-21 10:41:33 -070032#include <time.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033
Steven Morelandfb7952f2018-02-23 14:58:50 -080034#include <cutils/atomic.h>
Jason parksbd9a08d2011-01-31 15:04:34 -060035#include <cutils/properties.h>
36
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -040037#include <android/imagedecoder.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080038#include <androidfw/AssetManager.h>
Mathias Agopianac31a3b2009-05-21 19:59:24 -070039#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040#include <utils/Errors.h>
41#include <utils/Log.h>
Wei Wanga90c54c2017-02-02 11:35:21 -080042#include <utils/SystemClock.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
Keun-young Parkb5938422017-03-23 13:46:24 -070044#include <android-base/properties.h>
45
Marin Shalamanovcb783ca2021-01-29 21:26:07 +010046#include <ui/DisplayMode.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047#include <ui/PixelFormat.h>
48#include <ui/Rect.h>
49#include <ui/Region.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050
Jeff Brown0b722fe2012-08-24 22:40:14 -070051#include <gui/ISurfaceComposer.h>
Marin Shalamanov9070c052020-05-18 19:05:17 +020052#include <gui/DisplayEventReceiver.h>
Mathias Agopian8335f1c2012-02-25 18:48:35 -080053#include <gui/Surface.h>
54#include <gui/SurfaceComposerClient.h>
Lucas Dupin8eedc022021-07-29 21:49:07 +000055#include <GLES2/gl2.h>
56#include <GLES2/gl2ext.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057#include <EGL/eglext.h>
58
59#include "BootAnimation.h"
60
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +090061#define ANIM_PATH_MAX 255
62#define STR(x) #x
63#define STRTO(x) STR(x)
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065namespace android {
66
Marin Shalamanovcb783ca2021-01-29 21:26:07 +010067using ui::DisplayMode;
68
Damien Bargiacchi97480862016-03-29 14:55:55 -070069static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
Beverly34ffe252019-05-17 11:03:54 -040070static const char PRODUCT_BOOTANIMATION_DARK_FILE[] = "/product/media/bootanimation-dark.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090071static const char PRODUCT_BOOTANIMATION_FILE[] = "/product/media/bootanimation.zip";
Damien Bargiacchi97480862016-03-29 14:55:55 -070072static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
Anders Fridlunde0b4d232018-11-06 14:23:25 +010073static const char APEX_BOOTANIMATION_FILE[] = "/apex/com.android.bootanimation/etc/bootanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070074static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090075static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070076static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
77
Nikita Ioffe06c986e2020-01-27 17:16:03 +000078static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
79static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
80static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
81
Josh Yangf95b2002021-12-23 14:32:28 -080082static const char BOOTANIM_DATA_DIR_PATH[] = "/data/bootanim";
83static const char BOOTANIM_TIME_DIR_NAME[] = "time";
84static const char BOOTANIM_TIME_DIR_PATH[] = "/data/bootanim/time";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070085static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
86static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +000087static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
88static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
Damien Bargiacchi97480862016-03-29 14:55:55 -070089static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
Josh Yangf95b2002021-12-23 14:32:28 -080090static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/bootanim/time/last_time_change";
Damien Bargiacchi97480862016-03-29 14:55:55 -070091static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
Josh Yangf95b2002021-12-23 14:32:28 -080092static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/bootanim/time/time_is_accurate";
93static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/bootanim/time/time_format_12_hour";
Damien Bargiacchi96762812016-07-12 15:53:40 -070094// Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
95static const long long ACCURATE_TIME_EPOCH = 946684800000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070096static constexpr char FONT_BEGIN_CHAR = ' ';
97static constexpr char FONT_END_CHAR = '~' + 1;
98static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
99static constexpr size_t FONT_NUM_COLS = 16;
100static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
101static const int TEXT_CENTER_VALUE = INT_MAX;
102static const int TEXT_MISSING_VALUE = INT_MIN;
Damien Bargiacchi97480862016-03-29 14:55:55 -0700103static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000104static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
Huihong Luod4a217e2020-01-16 15:56:33 -0800105static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
Thiébaud Weksteen08de4432021-11-18 13:25:59 +1100106static const char CLOCK_ENABLED_PROP_NAME[] = "persist.sys.bootanim.clock.enabled";
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +0900107static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700108static constexpr size_t TEXT_POS_LEN_MAX = 16;
Shan Huang2b31a362021-08-16 16:45:39 +0000109static const int DYNAMIC_COLOR_COUNT = 4;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000110static const char U_TEXTURE[] = "uTexture";
111static const char U_FADE[] = "uFade";
112static const char U_CROP_AREA[] = "uCropArea";
Shan Huang2b31a362021-08-16 16:45:39 +0000113static const char U_START_COLOR_PREFIX[] = "uStartColor";
114static const char U_END_COLOR_PREFIX[] = "uEndColor";
115static const char U_COLOR_PROGRESS[] = "uColorProgress";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000116static const char A_UV[] = "aUv";
117static const char A_POSITION[] = "aPosition";
118static const char VERTEX_SHADER_SOURCE[] = R"(
119 precision mediump float;
120 attribute vec4 aPosition;
121 attribute highp vec2 aUv;
122 varying highp vec2 vUv;
123 void main() {
124 gl_Position = aPosition;
125 vUv = aUv;
126 })";
Shan Huang2b31a362021-08-16 16:45:39 +0000127static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
128 precision mediump float;
Shan Huang81846ba2021-09-07 19:07:47 +0000129 const float cWhiteMaskThreshold = 0.05;
Shan Huang2b31a362021-08-16 16:45:39 +0000130 uniform sampler2D uTexture;
131 uniform float uFade;
132 uniform float uColorProgress;
Andrew Zengf9f58222022-11-08 11:10:48 -0800133 uniform vec3 uStartColor0;
134 uniform vec3 uStartColor1;
135 uniform vec3 uStartColor2;
136 uniform vec3 uStartColor3;
137 uniform vec3 uEndColor0;
138 uniform vec3 uEndColor1;
139 uniform vec3 uEndColor2;
140 uniform vec3 uEndColor3;
Shan Huang2b31a362021-08-16 16:45:39 +0000141 varying highp vec2 vUv;
142 void main() {
143 vec4 mask = texture2D(uTexture, vUv);
Shan Huang488ff742021-08-25 20:10:46 +0000144 float r = mask.r;
145 float g = mask.g;
146 float b = mask.b;
147 float a = mask.a;
148 // If all channels have values, render pixel as a shade of white.
149 float useWhiteMask = step(cWhiteMaskThreshold, r)
150 * step(cWhiteMaskThreshold, g)
151 * step(cWhiteMaskThreshold, b)
152 * step(cWhiteMaskThreshold, a);
Andrew Zengf9f58222022-11-08 11:10:48 -0800153 vec3 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
Shan Huang488ff742021-08-25 20:10:46 +0000154 + g * mix(uStartColor1, uEndColor1, uColorProgress)
155 + b * mix(uStartColor2, uEndColor2, uColorProgress)
156 + a * mix(uStartColor3, uEndColor3, uColorProgress);
Andrew Zengf9f58222022-11-08 11:10:48 -0800157 color = mix(color, vec3((r + g + b + a) * 0.25), useWhiteMask);
158 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade));
Shan Huang2b31a362021-08-16 16:45:39 +0000159 })";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000160static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
161 precision mediump float;
162 uniform sampler2D uTexture;
163 uniform float uFade;
164 varying highp vec2 vUv;
165 void main() {
166 vec4 color = texture2D(uTexture, vUv);
Shan Huang2b31a362021-08-16 16:45:39 +0000167 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000168 })";
169static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
170 precision mediump float;
171 uniform sampler2D uTexture;
172 uniform vec4 uCropArea;
173 varying highp vec2 vUv;
174 void main() {
175 vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
176 mix(uCropArea.y, uCropArea.w, vUv.y));
177 gl_FragColor = texture2D(uTexture, uv);
178 })";
179
180static GLfloat quadPositions[] = {
181 -0.5f, -0.5f,
182 +0.5f, -0.5f,
183 +0.5f, +0.5f,
184 +0.5f, +0.5f,
185 -0.5f, +0.5f,
186 -0.5f, -0.5f
187};
188static GLfloat quadUVs[] = {
189 0.0f, 1.0f,
190 1.0f, 1.0f,
191 1.0f, 0.0f,
192 1.0f, 0.0f,
193 0.0f, 0.0f,
194 0.0f, 1.0f
195};
Narayan Kamathafd31e02013-12-03 13:16:03 +0000196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197// ---------------------------------------------------------------------------
198
Ed Coyne7464ac92017-06-08 12:26:48 -0700199BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200200 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700201 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700202 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400203
Keun-young Parkb5938422017-03-23 13:46:24 -0700204 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
205 if (powerCtl.empty()) {
206 mShuttingDown = false;
207 } else {
208 mShuttingDown = true;
209 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700210 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
211 elapsedRealtime());
212}
213
214BootAnimation::~BootAnimation() {
215 if (mAnimation != nullptr) {
216 releaseAnimation(mAnimation);
217 mAnimation = nullptr;
218 }
219 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
220 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221}
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700224 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700225 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700226 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700227 // Load the animation content -- this can be slow (eg 200ms)
228 // called before waitForSurfaceFlinger() in main() to avoid wait
229 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
230 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
231 preloadAnimation();
232 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
233 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
Mathias Agopianbc726112009-09-23 15:44:05 -0700234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235}
236
Mathias Agopianbc726112009-09-23 15:44:05 -0700237sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 return mSession;
239}
240
Marin Shalamanov9070c052020-05-18 19:05:17 +0200241void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700242 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700243 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700244
245 // calling requestExit() is not enough here because the Surface code
246 // might be blocked on a condition variable that will never be updated.
247 kill( getpid(), SIGKILL );
248 requestExit();
249}
250
Shan Huang2b31a362021-08-16 16:45:39 +0000251static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
252 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400253 AImageDecoder* decoder = nullptr;
254 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
255 if (!decoder) {
256 return nullptr;
257 }
258
259 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
260 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
261 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
262 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
263 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
264 outInfo->flags = 0;
265
Shan Huang2b31a362021-08-16 16:45:39 +0000266 if (!premultiplyAlpha) {
267 AImageDecoder_setUnpremultipliedRequired(decoder, true);
268 }
269
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400270 const size_t size = outInfo->stride * outInfo->height;
271 void* pixels = malloc(size);
272 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
273 AImageDecoder_delete(decoder);
274
275 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
276 free(pixels);
277 return nullptr;
278 }
279 return pixels;
280}
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
Shan Huang2b31a362021-08-16 16:45:39 +0000283 const char* name, bool premultiplyAlpha) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700285 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400287
288 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000289 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
290 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400291 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 asset->close();
294 delete asset;
295
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400296 if (!pixels) {
297 return NO_INIT;
298 }
299
300 const int w = bitmapInfo.width;
301 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 texture->w = w;
304 texture->h = h;
305
306 glGenTextures(1, &texture->name);
307 glBindTexture(GL_TEXTURE_2D, texture->name);
308
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400309 switch (bitmapInfo.format) {
310 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400312 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400314 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400316 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400318 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400320 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400322 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400324 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 break;
326 default:
327 break;
328 }
329
Lucas Dupin8eedc022021-07-29 21:49:07 +0000330 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
331 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
332 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
333 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 return NO_ERROR;
336}
337
Shan Huang2b31a362021-08-16 16:45:39 +0000338status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
339 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400340 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000341 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
342 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400343 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700344
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200345 // FileMap memory is never released until application exit.
346 // Release it now as the texture is already loaded and the memory used for
347 // the packed resource can be released.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700348 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200349
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400350 if (!pixels) {
351 return NO_INIT;
352 }
353
354 const int w = bitmapInfo.width;
355 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700356
Mathias Agopiana8826d62009-10-01 03:10:14 -0700357 int tw = 1 << (31 - __builtin_clz(w));
358 int th = 1 << (31 - __builtin_clz(h));
359 if (tw < w) tw <<= 1;
360 if (th < h) th <<= 1;
361
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400362 switch (bitmapInfo.format) {
363 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530364 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700365 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700366 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700367 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400368 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700369 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530370 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400371 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700372 }
373 break;
374
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400375 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530376 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700377 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700378 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700379 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400380 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700381 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530382 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400383 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700384 }
385 break;
386 default:
387 break;
388 }
389
Lucas Dupin8eedc022021-07-29 21:49:07 +0000390 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
391 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
392 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
393 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700394
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700395 *width = w;
396 *height = h;
397
Mathias Agopiana8826d62009-10-01 03:10:14 -0700398 return NO_ERROR;
399}
400
Marin Shalamanov9070c052020-05-18 19:05:17 +0200401class BootAnimation::DisplayEventCallback : public LooperCallback {
402 BootAnimation* mBootAnimation;
403
404public:
405 DisplayEventCallback(BootAnimation* bootAnimation) {
406 mBootAnimation = bootAnimation;
407 }
408
409 int handleEvent(int /* fd */, int events, void* /* data */) {
410 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
411 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
412 events);
413 return 0; // remove the callback
414 }
415
416 if (!(events & Looper::EVENT_INPUT)) {
417 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
418 return 1; // keep the callback
419 }
420
421 constexpr int kBufferSize = 100;
422 DisplayEventReceiver::Event buffer[kBufferSize];
423 ssize_t numEvents;
424 do {
425 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
426 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
427 const auto& event = buffer[i];
428 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
429 SLOGV("Hotplug received");
430
431 if (!event.hotplug.connected) {
432 // ignore hotplug disconnect
433 continue;
434 }
435 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
436 event.header.displayId);
437
438 if (token != mBootAnimation->mDisplayToken) {
439 // ignore hotplug of a secondary display
440 continue;
441 }
442
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100443 DisplayMode displayMode;
444 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
445 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200446 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100447 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200448 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100449 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
450 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200451 }
452 }
453 } while (numEvents > 0);
454
455 return 1; // keep the callback
456 }
457};
458
459EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
460 const EGLint attribs[] = {
461 EGL_RED_SIZE, 8,
462 EGL_GREEN_SIZE, 8,
463 EGL_BLUE_SIZE, 8,
464 EGL_DEPTH_SIZE, 0,
465 EGL_NONE
466 };
467 EGLint numConfigs;
468 EGLConfig config;
469 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
470 return config;
471}
472
Marin Shalamanov047802d2020-05-19 23:55:12 +0200473ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
474 ui::Size limited(width, height);
475 bool wasLimited = false;
476 const float aspectRatio = float(width) / float(height);
477 if (mMaxWidth != 0 && width > mMaxWidth) {
478 limited.height = mMaxWidth / aspectRatio;
479 limited.width = mMaxWidth;
480 wasLimited = true;
481 }
482 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
483 limited.height = mMaxHeight;
484 limited.width = mMaxHeight * aspectRatio;
485 wasLimited = true;
486 }
487 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
488 limited.width, limited.height, width, height);
489 return limited;
490}
491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492status_t BootAnimation::readyToRun() {
493 mAssets.addDefaultAssets();
494
Huihong Luo44305102022-09-26 11:16:20 -0700495 const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds();
496 if (ids.empty()) {
497 SLOGE("Failed to get ID for any displays\n");
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800498 return NAME_NOT_FOUND;
Huihong Luo44305102022-09-26 11:16:20 -0700499 }
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800500
Huihong Luo44305102022-09-26 11:16:20 -0700501 // this system property specifies multi-display IDs to show the boot animation
Huihong Luof97c9e22019-05-29 11:08:01 -0700502 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800503 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200504 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700505 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800506 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700507 bool isValid = displayValue[0] != '\0';
508 if (isValid) {
509 char *p = displayValue;
510 while (*p) {
511 if (!isdigit(*p) && *p != ',') {
512 isValid = false;
513 break;
514 }
515 p ++;
516 }
517 if (!isValid)
Huihong Luod4a217e2020-01-16 15:56:33 -0800518 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700519 }
520 if (isValid) {
521 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200522 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700523 physicalDisplayIds.add(id);
524 if (stream.peek() == ',')
525 stream.ignore();
526 }
527
Huihong Luo44305102022-09-26 11:16:20 -0700528 // the first specified display id is used to retrieve mDisplayToken
529 for (const auto id : physicalDisplayIds) {
530 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
531 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
532 mDisplayToken = token;
533 break;
534 }
535 }
536 }
537 }
538
539 // If the system property is not present or invalid, display 0 is used
540 if (mDisplayToken == nullptr) {
541 mDisplayToken = SurfaceComposerClient::getPhysicalDisplayToken(ids.front());
542 if (mDisplayToken == nullptr) {
543 return NAME_NOT_FOUND;
544 }
545 }
546
547 DisplayMode displayMode;
548 const status_t error =
549 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
550 if (error != NO_ERROR) {
551 return error;
552 }
553
554 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
555 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
556 ui::Size resolution = displayMode.resolution;
557 resolution = limitSurfaceSize(resolution.width, resolution.height);
558 // create the native surface
559 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
560 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565,
561 ISurfaceComposerClient::eOpaque);
562
563 SurfaceComposerClient::Transaction t;
564 if (isValid) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700565 // In the case of multi-display, boot animation shows on the specified displays
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700566 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700567 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700568 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
569 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
570 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700571 }
572 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700573 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700574 }
575
Robert Carre13b58e2017-08-31 14:50:44 -0700576 t.setLayer(control, 0x40000000)
577 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578
Mathias Agopian17f638b2009-04-16 20:04:08 -0700579 sp<Surface> s = control->getSurface();
580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700583 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200584 EGLConfig config = getEglConfig(display);
585 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000586 // Initialize egl context with client version number 2.0.
587 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
588 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200589 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 eglQuerySurface(display, surface, EGL_WIDTH, &w);
591 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700592
Huihong Luo44305102022-09-26 11:16:20 -0700593 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
Mathias Agopianabac0102009-07-31 14:47:00 -0700594 return NO_INIT;
Huihong Luo44305102022-09-26 11:16:20 -0700595 }
Mathias Agopiana8826d62009-10-01 03:10:14 -0700596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 mDisplay = display;
598 mContext = context;
599 mSurface = surface;
joenchen764ea042022-04-11 23:58:34 +0800600 mInitWidth = mWidth = w;
601 mInitHeight = mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700602 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200604 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000606 // Rotate the boot animation according to the value specified in the sysprop
607 // ro.bootanim.set_orientation_<display_id>. Four values are supported: ORIENTATION_0,
608 // ORIENTATION_90, ORIENTATION_180 and ORIENTATION_270.
609 // If the value isn't specified or is ORIENTATION_0, nothing will be changed.
610 // This is needed to support having boot animation in orientations different from the natural
611 // device orientation. For example, on tablets that may want to keep natural orientation
612 // portrait for applications compatibility and to have the boot animation in landscape.
613 rotateAwayFromNaturalOrientationIfNeeded();
614
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200615 projectSceneToWindow();
616
Marin Shalamanov9070c052020-05-18 19:05:17 +0200617 // Register a display event receiver
618 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
619 status_t status = mDisplayEventReceiver->initCheck();
620 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
621 status);
622 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
623 new DisplayEventCallback(this), nullptr);
624
Huihong Luo50a2f362018-08-11 09:27:57 -0700625 return NO_ERROR;
626}
627
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000628void BootAnimation::rotateAwayFromNaturalOrientationIfNeeded() {
629 const auto orientation = parseOrientationProperty();
630
631 if (orientation == ui::ROTATION_0) {
632 // Do nothing if the sysprop isn't set or is set to ROTATION_0.
633 return;
634 }
635
636 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
637 std::swap(mWidth, mHeight);
638 std::swap(mInitWidth, mInitHeight);
639 mFlingerSurfaceControl->updateDefaultBufferSize(mWidth, mHeight);
640 }
641
642 Rect displayRect(0, 0, mWidth, mHeight);
643 Rect layerStackRect(0, 0, mWidth, mHeight);
644
645 SurfaceComposerClient::Transaction t;
646 t.setDisplayProjection(mDisplayToken, orientation, layerStackRect, displayRect);
647 t.apply();
648}
649
650ui::Rotation BootAnimation::parseOrientationProperty() {
651 const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
652 if (displayIds.size() == 0) {
653 return ui::ROTATION_0;
654 }
655 const auto displayId = displayIds[0];
656 const auto syspropName = [displayId] {
657 std::stringstream ss;
658 ss << "ro.bootanim.set_orientation_" << displayId.value;
659 return ss.str();
660 }();
661 const auto syspropValue = android::base::GetProperty(syspropName, "ORIENTATION_0");
662 if (syspropValue == "ORIENTATION_90") {
663 return ui::ROTATION_90;
664 } else if (syspropValue == "ORIENTATION_180") {
665 return ui::ROTATION_180;
666 } else if (syspropValue == "ORIENTATION_270") {
667 return ui::ROTATION_270;
668 }
669 return ui::ROTATION_0;
670}
671
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200672void BootAnimation::projectSceneToWindow() {
673 glViewport(0, 0, mWidth, mHeight);
674 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200675}
676
Marin Shalamanov9070c052020-05-18 19:05:17 +0200677void BootAnimation::resizeSurface(int newWidth, int newHeight) {
678 // We assume this function is called on the animation thread.
679 if (newWidth == mWidth && newHeight == mHeight) {
680 return;
681 }
682 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
683
684 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
685 eglDestroySurface(mDisplay, mSurface);
686
joenchen764ea042022-04-11 23:58:34 +0800687 mFlingerSurfaceControl->updateDefaultBufferSize(newWidth, newHeight);
Marin Shalamanov047802d2020-05-19 23:55:12 +0200688 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
689 mWidth = limitedSize.width;
690 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200691
Marin Shalamanov9070c052020-05-18 19:05:17 +0200692 EGLConfig config = getEglConfig(mDisplay);
693 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
694 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
695 SLOGE("Can't make the new surface current. Error %d", eglGetError());
696 return;
697 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200698
699 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200700
701 mSurface = surface;
702}
703
Huihong Luo50a2f362018-08-11 09:27:57 -0700704bool BootAnimation::preloadAnimation() {
705 findBootAnimationFile();
706 if (!mZipFileName.isEmpty()) {
707 mAnimation = loadAnimation(mZipFileName);
708 return (mAnimation != nullptr);
709 }
710
711 return false;
712}
713
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000714bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
715 for (const std::string& f : files) {
716 if (access(f.c_str(), R_OK) == 0) {
717 mZipFileName = f.c_str();
718 return true;
719 }
720 }
721 return false;
722}
723
Huihong Luo50a2f362018-08-11 09:27:57 -0700724void BootAnimation::findBootAnimationFile() {
Beverly34ffe252019-05-17 11:03:54 -0400725 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000726 static const std::vector<std::string> bootFiles = {
727 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
728 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
729 };
730 static const std::vector<std::string> shutdownFiles = {
731 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
732 };
733 static const std::vector<std::string> userspaceRebootFiles = {
734 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
735 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
736 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700737
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000738 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
739 findBootAnimationFileInternal(userspaceRebootFiles);
740 } else if (mShuttingDown) {
741 findBootAnimationFileInternal(shutdownFiles);
742 } else {
743 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745}
746
Lucas Dupin8eedc022021-07-29 21:49:07 +0000747GLuint compileShader(GLenum shaderType, const GLchar *source) {
748 GLuint shader = glCreateShader(shaderType);
749 glShaderSource(shader, 1, &source, 0);
750 glCompileShader(shader);
751 GLint isCompiled = 0;
752 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
753 if (isCompiled == GL_FALSE) {
754 SLOGE("Compile shader failed. Shader type: %d", shaderType);
Shan Huang81846ba2021-09-07 19:07:47 +0000755 GLint maxLength = 0;
756 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
757 std::vector<GLchar> errorLog(maxLength);
758 glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
759 SLOGE("Shader compilation error: %s", &errorLog[0]);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000760 return 0;
761 }
762 return shader;
763}
764
765GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
766 GLuint program = glCreateProgram();
767 glAttachShader(program, vertexShader);
768 glAttachShader(program, fragmentShader);
769 glLinkProgram(program);
770 GLint isLinked = 0;
771 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
772 if (isLinked == GL_FALSE) {
773 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
774 vertexShader, fragmentShader);
775 return 0;
776 }
777 return program;
778}
779
780void BootAnimation::initShaders() {
Shan Huang2b31a362021-08-16 16:45:39 +0000781 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000782 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
783 GLuint imageFragmentShader =
Shan Huang2b31a362021-08-16 16:45:39 +0000784 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
785 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
786 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000787 GLuint textFragmentShader =
788 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
789
790 // Initialize image shader.
791 mImageShader = linkShader(vertexShader, imageFragmentShader);
792 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
793 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
794 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
795 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
796 glEnableVertexAttribArray(positionLocation);
797 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
798 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
799 glEnableVertexAttribArray(uvLocation);
800
801 // Initialize text shader.
802 mTextShader = linkShader(vertexShader, textFragmentShader);
803 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
804 uvLocation = glGetAttribLocation(mTextShader, A_UV);
805 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
806 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
807 glEnableVertexAttribArray(positionLocation);
808 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
809 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
810 glEnableVertexAttribArray(uvLocation);
811}
812
Marin Shalamanov9070c052020-05-18 19:05:17 +0200813bool BootAnimation::threadLoop() {
814 bool result;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000815 initShaders();
816
Narayan Kamathafd31e02013-12-03 13:16:03 +0000817 // We have no bootanimation file, so we use the stock android logo
818 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700819 if (mZipFileName.isEmpty()) {
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +0900820 ALOGD("No animation file");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200821 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700822 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200823 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700824 }
825
Philip Junker60600562020-11-25 18:16:16 +0100826 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
828 eglDestroyContext(mDisplay, mContext);
829 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700830 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700831 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700832 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530833 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700834 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200835 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836}
837
Marin Shalamanov9070c052020-05-18 19:05:17 +0200838bool BootAnimation::android() {
Lucas Dupin8eedc022021-07-29 21:49:07 +0000839 glActiveTexture(GL_TEXTURE0);
840
Wei Wang159a4102018-10-23 23:15:58 -0700841 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700842 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700843 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
844 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845
Ed Coyne7464ac92017-06-08 12:26:48 -0700846 mCallbacks->init({});
847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700849 glDisable(GL_DITHER);
850 glDisable(GL_SCISSOR_TEST);
Shan Huangbfd2d3c2021-09-09 23:19:04 +0000851 glUseProgram(mImageShader);
852
Mathias Agopian59f19e42011-05-06 19:22:12 -0700853 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 glClear(GL_COLOR_BUFFER_BIT);
855 eglSwapBuffers(mDisplay, mSurface);
856
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700857 // Blend state
858 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 const nsecs_t startTime = systemTime();
861 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200862 processDisplayEvents();
863 const GLint xc = (mWidth - mAndroid[0].w) / 2;
864 const GLint yc = (mHeight - mAndroid[0].h) / 2;
865 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
866 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
867 updateRect.height());
868
Mathias Agopian13796652009-03-24 22:49:21 -0700869 nsecs_t now = systemTime();
870 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700871 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
872 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
873 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874
Mathias Agopian81668642009-07-28 11:41:30 -0700875 glDisable(GL_SCISSOR_TEST);
876 glClear(GL_COLOR_BUFFER_BIT);
877
878 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000881 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
882 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700884 glEnable(GL_BLEND);
885 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000886 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887
Mathias Agopian627e7b52009-05-21 19:21:59 -0700888 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
889 if (res == EGL_FALSE)
890 break;
891
Mathias Agopian13796652009-03-24 22:49:21 -0700892 // 12fps: don't animate too fast to preserve CPU
893 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
894 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700895 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700896
897 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 } while (!exitPending());
899
900 glDeleteTextures(1, &mAndroid[0].name);
901 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 return false;
903}
904
Kevin Hesterd3782b22012-04-26 10:38:55 -0700905void BootAnimation::checkExit() {
906 // Allow surface flinger to gracefully request shutdown
907 char value[PROPERTY_VALUE_MAX];
908 property_get(EXIT_PROP_NAME, value, "0");
909 int exitnow = atoi(value);
910 if (exitnow) {
911 requestExit();
912 }
913}
914
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700915bool BootAnimation::validClock(const Animation::Part& part) {
916 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
917}
918
919bool parseTextCoord(const char* str, int* dest) {
920 if (strcmp("c", str) == 0) {
921 *dest = TEXT_CENTER_VALUE;
922 return true;
923 }
924
925 char* end;
926 int val = (int) strtol(str, &end, 0);
927 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
928 return false;
929 }
930 *dest = val;
931 return true;
932}
933
934// Parse two position coordinates. If only string is non-empty, treat it as the y value.
935void parsePosition(const char* str1, const char* str2, int* x, int* y) {
936 bool success = false;
937 if (strlen(str1) == 0) { // No values were specified
938 // success = false
939 } else if (strlen(str2) == 0) { // we have only one value
940 if (parseTextCoord(str1, y)) {
941 *x = TEXT_CENTER_VALUE;
942 success = true;
943 }
944 } else {
945 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
946 success = true;
947 }
948 }
949
950 if (!success) {
951 *x = TEXT_MISSING_VALUE;
952 *y = TEXT_MISSING_VALUE;
953 }
954}
955
Jesse Hall083b84c2014-09-22 10:51:09 -0700956// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
957// characters in str is a hex number in [0, 255], which are converted to
958// floating point values in the range [0.0, 1.0] and placed in the
959// corresponding elements of color.
960//
961// If the input string isn't valid, parseColor returns false and color is
962// left unchanged.
963static bool parseColor(const char str[7], float color[3]) {
964 float tmpColor[3];
965 for (int i = 0; i < 3; i++) {
966 int val = 0;
967 for (int j = 0; j < 2; j++) {
968 val *= 16;
969 char c = str[2*i + j];
970 if (c >= '0' && c <= '9') val += c - '0';
971 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
972 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
973 else return false;
974 }
975 tmpColor[i] = static_cast<float>(val) / 255.0f;
976 }
977 memcpy(color, tmpColor, sizeof(tmpColor));
978 return true;
979}
980
Shan Huang2b31a362021-08-16 16:45:39 +0000981// Parse a color represented as a signed decimal int string.
982// E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
983// If the input color string is empty, set color with values in defaultColor.
984static void parseColorDecimalString(const std::string& colorString,
985 float color[3], float defaultColor[3]) {
986 if (colorString == "") {
987 memcpy(color, defaultColor, sizeof(float) * 3);
988 return;
989 }
990 int colorInt = atoi(colorString.c_str());
991 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
992 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
993 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
994}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700995
Marin Shalamanov9070c052020-05-18 19:05:17 +0200996static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700997 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -0700998 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700999 if (!entry) {
1000 return false;
1001 }
1002
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001003 FileMap* entryMap = zip->createEntryFileMap(entry);
1004 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -07001005 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001006 if (!entryMap) {
1007 return false;
1008 }
1009
1010 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +00001011 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001012 return true;
1013}
1014
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001015// The font image should be a 96x2 array of character images. The
1016// columns are the printable ASCII characters 0x20 - 0x7f. The
1017// top row is regular text; the bottom row is bold.
1018status_t BootAnimation::initFont(Font* font, const char* fallback) {
1019 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001020
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001021 if (font->map != nullptr) {
1022 glGenTextures(1, &font->texture.name);
1023 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001024
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001025 status = initTexture(font->map, &font->texture.w, &font->texture.h);
1026
Lucas Dupin8eedc022021-07-29 21:49:07 +00001027 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1028 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1029 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1030 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001031 } else if (fallback != nullptr) {
1032 status = initTexture(&font->texture, mAssets, fallback);
1033 } else {
1034 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001035 }
1036
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001037 if (status == NO_ERROR) {
1038 font->char_width = font->texture.w / FONT_NUM_COLS;
1039 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
1040 }
1041
1042 return status;
1043}
1044
1045void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
1046 glEnable(GL_BLEND); // Allow us to draw on top of the animation
1047 glBindTexture(GL_TEXTURE_2D, font.texture.name);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001048 glUseProgram(mTextShader);
1049 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001050
1051 const int len = strlen(str);
1052 const int strWidth = font.char_width * len;
1053
1054 if (*x == TEXT_CENTER_VALUE) {
1055 *x = (mWidth - strWidth) / 2;
1056 } else if (*x < 0) {
1057 *x = mWidth + *x - strWidth;
1058 }
1059 if (*y == TEXT_CENTER_VALUE) {
1060 *y = (mHeight - font.char_height) / 2;
1061 } else if (*y < 0) {
1062 *y = mHeight + *y - font.char_height;
1063 }
1064
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001065 for (int i = 0; i < len; i++) {
1066 char c = str[i];
1067
1068 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1069 c = '?';
1070 }
1071
1072 // Crop the texture to only the pixels in the current glyph
1073 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1074 const int row = charPos / FONT_NUM_COLS;
1075 const int col = charPos % FONT_NUM_COLS;
Lucas Dupin8eedc022021-07-29 21:49:07 +00001076 // Bold fonts are expected in the second half of each row.
1077 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1078 float u0 = ((float)col) / FONT_NUM_COLS;
1079 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1080 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1081 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1082 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001083
1084 *x += font.char_width;
1085 }
1086
1087 glDisable(GL_BLEND); // Return to the animation's default behaviour
1088 glBindTexture(GL_TEXTURE_2D, 0);
1089}
1090
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001091// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001092void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001093 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1094 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001095 static constexpr int TIME_LENGTH = 6;
1096
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001097 time_t rawtime;
1098 time(&rawtime);
1099 struct tm* timeInfo = localtime(&rawtime);
1100
1101 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001102 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1103 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001104
1105 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001106 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001107 mClockEnabled = false;
1108 return;
1109 }
1110
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001111 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001112 int x = xPos;
1113 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001114 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001115}
1116
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001117void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1118 static constexpr int PERCENT_LENGTH = 5;
1119
1120 char percentBuff[PERCENT_LENGTH];
1121 // ';' has the ascii code just after ':', and the font resource contains '%'
1122 // for that ascii code.
1123 sprintf(percentBuff, "%d;", percent);
1124 int x = xPos;
1125 int y = yPos;
1126 drawText(percentBuff, font, false, &x, &y);
1127}
1128
Marin Shalamanov9070c052020-05-18 19:05:17 +02001129bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001130 String8 desString;
1131
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001132 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001133 return false;
1134 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001135 char const* s = desString.string();
Shan Huang2b31a362021-08-16 16:45:39 +00001136 std::string dynamicColoringPartName = "";
1137 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001138
Mathias Agopiana8826d62009-10-01 03:10:14 -07001139 // Parse the description file
1140 for (;;) {
1141 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001142 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001143 String8 line(s, endl - s);
1144 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001145 int fps = 0;
1146 int width = 0;
1147 int height = 0;
1148 int count = 0;
1149 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001150 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001151 int framesToFadeCount = 0;
Shan Huang488ff742021-08-25 20:10:46 +00001152 int colorTransitionStart = 0;
1153 int colorTransitionEnd = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001154 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001155 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001156 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1157 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang2b31a362021-08-16 16:45:39 +00001158 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001159 char pathType;
Shan Huang2b31a362021-08-16 16:45:39 +00001160 // start colors default to black if unspecified
1161 char start_color_0[7] = "000000";
1162 char start_color_1[7] = "000000";
1163 char start_color_2[7] = "000000";
1164 char start_color_3[7] = "000000";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001165
1166 int nextReadPos;
1167
yidong zhang87bb3462022-12-07 15:55:31 +08001168 if (strlen(l) == 0) {
1169 s = ++endl;
1170 continue;
1171 }
1172
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001173 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1174 if (topLineNumbers == 3 || topLineNumbers == 4) {
1175 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001176 animation.width = width;
1177 animation.height = height;
1178 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001179 if (topLineNumbers == 4) {
1180 animation.progressEnabled = (progress != 0);
1181 } else {
1182 animation.progressEnabled = false;
1183 }
Shan Huang488ff742021-08-25 20:10:46 +00001184 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
Shan Huang2b31a362021-08-16 16:45:39 +00001185 dynamicColoringPartNameBuffer,
Shan Huang488ff742021-08-25 20:10:46 +00001186 start_color_0, start_color_1, start_color_2, start_color_3,
1187 &colorTransitionStart, &colorTransitionEnd)) {
Shan Huang2b31a362021-08-16 16:45:39 +00001188 animation.dynamicColoringEnabled = true;
1189 parseColor(start_color_0, animation.startColors[0]);
1190 parseColor(start_color_1, animation.startColors[1]);
1191 parseColor(start_color_2, animation.startColors[2]);
1192 parseColor(start_color_3, animation.startColors[3]);
Shan Huang488ff742021-08-25 20:10:46 +00001193 animation.colorTransitionStart = colorTransitionStart;
1194 animation.colorTransitionEnd = colorTransitionEnd;
Shan Huang2b31a362021-08-16 16:45:39 +00001195 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001196 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1197 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1198 if (pathType == 'f') {
1199 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1200 clockPos2);
1201 } else {
1202 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1203 }
1204 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1205 // "clockPos1=%s, clockPos2=%s",
1206 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001207 Animation::Part part;
Shan Huang2b31a362021-08-16 16:45:39 +00001208 if (path == dynamicColoringPartName) {
1209 // Part is specified to use dynamic coloring.
1210 part.useDynamicColoring = true;
1211 part.postDynamicColoring = false;
1212 postDynamicColoring = true;
1213 } else {
1214 // Part does not use dynamic coloring.
1215 part.useDynamicColoring = false;
1216 part.postDynamicColoring = postDynamicColoring;
1217 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001218 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001219 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001220 part.count = count;
1221 part.pause = pause;
1222 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001223 part.audioData = nullptr;
1224 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001225 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001226 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001227 part.backgroundColor[0] = 0.0f;
1228 part.backgroundColor[1] = 0.0f;
1229 part.backgroundColor[2] = 0.0f;
1230 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001231 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001232 animation.parts.add(part);
1233 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001234 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001235 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001236 Animation::Part part;
1237 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001238 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001239 part.count = 1;
1240 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001241 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001242 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001243 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001244 animation.parts.add(part);
1245 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001246 s = ++endl;
1247 }
1248
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001249 return true;
1250}
1251
Marin Shalamanov9070c052020-05-18 19:05:17 +02001252bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001253 // read all the data structures
1254 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001255 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001256 ZipFileRO* zip = animation.zip;
1257 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001258 return false;
1259 }
1260
1261 ZipEntryRO entry;
1262 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001263 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001264 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001265 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001266 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001267 continue;
1268 }
1269
1270 const String8 entryName(name);
1271 const String8 path(entryName.getPathDir());
1272 const String8 leaf(entryName.getPathLeaf());
1273 if (leaf.size() > 0) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001274 if (entryName == CLOCK_FONT_ZIP_NAME) {
1275 FileMap* map = zip->createEntryFileMap(entry);
1276 if (map) {
1277 animation.clockFont.map = map;
1278 }
1279 continue;
1280 }
1281
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001282 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1283 FileMap* map = zip->createEntryFileMap(entry);
1284 if (map) {
1285 animation.progressFont.map = map;
1286 }
1287 continue;
1288 }
1289
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001290 for (size_t j = 0; j < pcount; j++) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001291 if (path == animation.parts[j].path) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001292 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001293 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001294 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001295 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001296 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001297 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001298 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001299 if (leaf == "audio.wav") {
1300 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001301 part.audioData = (uint8_t *)map->getDataPtr();
1302 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001303 } else if (leaf == "trim.txt") {
1304 part.trimData.setTo((char const*)map->getDataPtr(),
1305 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001306 } else {
1307 Animation::Frame frame;
1308 frame.name = leaf;
1309 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001310 frame.trimWidth = animation.width;
1311 frame.trimHeight = animation.height;
1312 frame.trimX = 0;
1313 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001314 part.frames.add(frame);
1315 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001316 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001317 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001318 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001319 }
1320 }
1321 }
1322 }
1323 }
1324 }
1325
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001326 // If there is trimData present, override the positioning defaults.
1327 for (Animation::Part& part : animation.parts) {
1328 const char* trimDataStr = part.trimData.string();
1329 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1330 const char* endl = strstr(trimDataStr, "\n");
1331 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001332 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001333 break;
1334 }
1335 String8 line(trimDataStr, endl - trimDataStr);
1336 const char* lineStr = line.string();
1337 trimDataStr = ++endl;
1338 int width = 0, height = 0, x = 0, y = 0;
1339 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1340 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1341 frame.trimWidth = width;
1342 frame.trimHeight = height;
1343 frame.trimX = x;
1344 frame.trimY = y;
1345 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001346 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001347 break;
1348 }
1349 }
1350 }
1351
1352 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001353
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001354 return true;
1355}
1356
Marin Shalamanov9070c052020-05-18 19:05:17 +02001357bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001358 if (mAnimation == nullptr) {
1359 mAnimation = loadAnimation(mZipFileName);
1360 }
1361
1362 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001363 return false;
1364
Huihong Luo50a2f362018-08-11 09:27:57 -07001365 // mCallbacks->init() may get called recursively,
1366 // this loop is needed to get the same results
1367 for (const Animation::Part& part : mAnimation->parts) {
1368 if (part.animation != nullptr) {
1369 mCallbacks->init(part.animation->parts);
1370 }
1371 }
1372 mCallbacks->init(mAnimation->parts);
1373
Damien Bargiacchi97480862016-03-29 14:55:55 -07001374 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001375 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1376 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001377 anyPartHasClock = true;
1378 break;
1379 }
1380 }
1381 if (!anyPartHasClock) {
1382 mClockEnabled = false;
Thiébaud Weksteen08de4432021-11-18 13:25:59 +11001383 } else if (!android::base::GetBoolProperty(CLOCK_ENABLED_PROP_NAME, false)) {
1384 mClockEnabled = false;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001385 }
1386
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301387 // Check if npot textures are supported
1388 mUseNpotTextures = false;
1389 String8 gl_extensions;
1390 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1391 if (!exts) {
1392 glGetError();
1393 } else {
1394 gl_extensions.setTo(exts);
1395 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1396 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1397 mUseNpotTextures = true;
1398 }
1399 }
1400
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001401 // Blend required to draw time on top of animation frames.
1402 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001403 glDisable(GL_DITHER);
1404 glDisable(GL_SCISSOR_TEST);
1405 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001406
Greg Kaiser2ded8002021-07-19 17:03:27 +00001407 glEnable(GL_TEXTURE_2D);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001408 glBindTexture(GL_TEXTURE_2D, 0);
1409 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1410 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1411 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1412 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001413 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001414 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001415 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001416 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001417 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001418 }
1419
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001420 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1421
Damien Bargiacchi97480862016-03-29 14:55:55 -07001422 if (mClockEnabled && !updateIsTimeAccurate()) {
1423 mTimeCheckThread = new TimeCheckThread(this);
1424 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1425 }
1426
George Burgess IV0f8e8112021-08-23 17:32:23 -07001427 if (mAnimation->dynamicColoringEnabled) {
Shan Huang7fee3522021-08-18 00:56:08 +00001428 initDynamicColors();
1429 }
1430
Huihong Luo50a2f362018-08-11 09:27:57 -07001431 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001432
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001433 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001434 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001435 mTimeCheckThread = nullptr;
1436 }
1437
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001438 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001439 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001440 }
1441
Huihong Luo50a2f362018-08-11 09:27:57 -07001442 releaseAnimation(mAnimation);
1443 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001444
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001445 return false;
1446}
1447
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001448bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1449 const int fadedFramesCount,
1450 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001451 // 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 +01001452 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1453 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001454}
1455
Lucas Dupin8eedc022021-07-29 21:49:07 +00001456// Linear mapping from range <a1, a2> to range <b1, b2>
1457float mapLinear(float x, float a1, float a2, float b1, float b2) {
1458 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1459}
1460
1461void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1462 // Map coordinates from screen space to world space.
1463 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1464 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1465 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1466 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1467 // Update quad vertex positions.
1468 quadPositions[0] = x0;
1469 quadPositions[1] = y0;
1470 quadPositions[2] = x1;
1471 quadPositions[3] = y0;
1472 quadPositions[4] = x1;
1473 quadPositions[5] = y1;
1474 quadPositions[6] = x1;
1475 quadPositions[7] = y1;
1476 quadPositions[8] = x0;
1477 quadPositions[9] = y1;
1478 quadPositions[10] = x0;
1479 quadPositions[11] = y0;
1480 glDrawArrays(GL_TRIANGLES, 0,
1481 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1482}
1483
Shan Huang7fee3522021-08-18 00:56:08 +00001484void BootAnimation::initDynamicColors() {
1485 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
Lucas Dupincd256842022-03-29 15:46:36 -07001486 const auto syspropName = "persist.bootanim.color" + std::to_string(i + 1);
1487 const auto syspropValue = android::base::GetProperty(syspropName, "");
1488 if (syspropValue != "") {
1489 SLOGI("Loaded dynamic color: %s -> %s", syspropName.c_str(), syspropValue.c_str());
1490 mDynamicColorsApplied = true;
1491 }
1492 parseColorDecimalString(syspropValue,
Shan Huang7fee3522021-08-18 00:56:08 +00001493 mAnimation->endColors[i], mAnimation->startColors[i]);
1494 }
1495 glUseProgram(mImageShader);
Lucas Dupincd256842022-03-29 15:46:36 -07001496 SLOGI("Dynamically coloring boot animation. Sysprops loaded? %i", mDynamicColorsApplied);
Shan Huang7fee3522021-08-18 00:56:08 +00001497 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1498 float *startColor = mAnimation->startColors[i];
1499 float *endColor = mAnimation->endColors[i];
Andrew Zengf9f58222022-11-08 11:10:48 -08001500 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001501 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001502 startColor[0], startColor[1], startColor[2]);
1503 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001504 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001505 endColor[0], endColor[1], endColor[2]);
Shan Huang7fee3522021-08-18 00:56:08 +00001506 }
1507 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1508}
1509
Marin Shalamanov9070c052020-05-18 19:05:17 +02001510bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001511 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001512 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001513
Wei Wang159a4102018-10-23 23:15:58 -07001514 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001515 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001516
1517 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001518 int lastDisplayedProgress = 0;
Lucas Dupinbfd18122022-04-25 11:26:08 -07001519 int colorTransitionStart = animation.colorTransitionStart;
1520 int colorTransitionEnd = animation.colorTransitionEnd;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001521 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001522 const Animation::Part& part(animation.parts[i]);
1523 const size_t fcount = part.frames.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001524
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001525 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001526 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001527 playAnimation(*part.animation);
1528 if (exitPending())
1529 break;
1530 continue; //to next part
1531 }
1532
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001533 // process the part not only while the count allows but also if already fading
1534 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001535 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001536
Lucas Dupinbfd18122022-04-25 11:26:08 -07001537 // It's possible that the sysprops were not loaded yet at this boot phase.
1538 // If that's the case, then we should keep trying until they are available.
1539 if (animation.dynamicColoringEnabled && !mDynamicColorsApplied
1540 && (part.useDynamicColoring || part.postDynamicColoring)) {
1541 SLOGD("Trying to load dynamic color sysprops.");
1542 initDynamicColors();
1543 if (mDynamicColorsApplied) {
1544 // Sysprops were loaded. Next step is to adjust the animation if we loaded
1545 // the colors after the animation should have started.
1546 const int transitionLength = colorTransitionEnd - colorTransitionStart;
1547 if (part.postDynamicColoring) {
1548 colorTransitionStart = 0;
1549 colorTransitionEnd = fmin(transitionLength, fcount - 1);
1550 }
1551 }
1552 }
1553
Ed Coyne7464ac92017-06-08 12:26:48 -07001554 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001555
Jesse Hall083b84c2014-09-22 10:51:09 -07001556 glClearColor(
1557 part.backgroundColor[0],
1558 part.backgroundColor[1],
1559 part.backgroundColor[2],
1560 1.0f);
1561
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001562 ALOGD("Playing files = %s/%s, Requested repeat = %d, playUntilComplete = %s",
1563 animation.fileName.string(), part.path.string(), part.count,
1564 part.playUntilComplete ? "true" : "false");
1565
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001566 // For the last animation, if we have progress indicator from
1567 // the system, display it.
1568 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1569 bool displayProgress = animation.progressEnabled &&
1570 (i == (pcount -1)) && currentProgress != 0;
1571
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001572 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001573 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001574
Shan Huang2b31a362021-08-16 16:45:39 +00001575 // Color progress is
Shan Huang488ff742021-08-25 20:10:46 +00001576 // - the animation progress, normalized from
1577 // [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1578 // part.
Shan Huang2b31a362021-08-16 16:45:39 +00001579 // - 0 for parts that come before,
1580 // - 1 for parts that come after.
1581 float colorProgress = part.useDynamicColoring
Shan Huang488ff742021-08-25 20:10:46 +00001582 ? fmin(fmax(
Lucas Dupinbfd18122022-04-25 11:26:08 -07001583 ((float)j - colorTransitionStart) /
1584 fmax(colorTransitionEnd - colorTransitionStart, 1.0f), 0.0f), 1.0f)
Shan Huang2b31a362021-08-16 16:45:39 +00001585 : (part.postDynamicColoring ? 1 : 0);
1586
Marin Shalamanov9070c052020-05-18 19:05:17 +02001587 processDisplayEvents();
1588
joenchen764ea042022-04-11 23:58:34 +08001589 const double ratio_w = static_cast<double>(mWidth) / mInitWidth;
1590 const double ratio_h = static_cast<double>(mHeight) / mInitHeight;
1591 const int animationX = (mWidth - animation.width * ratio_w) / 2;
1592 const int animationY = (mHeight - animation.height * ratio_h) / 2;
Marin Shalamanov9070c052020-05-18 19:05:17 +02001593
Mathias Agopiana8826d62009-10-01 03:10:14 -07001594 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001595 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001596
1597 if (r > 0) {
1598 glBindTexture(GL_TEXTURE_2D, frame.tid);
1599 } else {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001600 glGenTextures(1, &frame.tid);
1601 glBindTexture(GL_TEXTURE_2D, frame.tid);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001602 int w, h;
Shan Huang2b31a362021-08-16 16:45:39 +00001603 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1604 // of transparent pixels are preserved.
1605 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001606 }
1607
joenchen764ea042022-04-11 23:58:34 +08001608 const int trimWidth = frame.trimWidth * ratio_w;
1609 const int trimHeight = frame.trimHeight * ratio_h;
1610 const int trimX = frame.trimX * ratio_w;
1611 const int trimY = frame.trimY * ratio_h;
1612 const int xc = animationX + trimX;
1613 const int yc = animationY + trimY;
Shan Huang2b31a362021-08-16 16:45:39 +00001614 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001615 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1616 // which is equivalent to mHeight - (yc + frame.trimHeight)
joenchen764ea042022-04-11 23:58:34 +08001617 const int frameDrawY = mHeight - (yc + trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001618
Lucas Dupin8eedc022021-07-29 21:49:07 +00001619 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001620 // if the part hasn't been stopped yet then continue fading if necessary
1621 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001622 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001623 if (fadedFramesCount >= part.framesToFadeCount) {
1624 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1625 }
1626 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001627 glUseProgram(mImageShader);
1628 glUniform1i(mImageTextureLocation, 0);
1629 glUniform1f(mImageFadeLocation, fade);
Shan Huang2b31a362021-08-16 16:45:39 +00001630 if (animation.dynamicColoringEnabled) {
1631 glUniform1f(mImageColorProgressLocation, colorProgress);
1632 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001633 glEnable(GL_BLEND);
joenchen764ea042022-04-11 23:58:34 +08001634 drawTexturedQuad(xc, frameDrawY, trimWidth, trimHeight);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001635 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001636
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001637 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1638 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001639 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001640
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001641 if (displayProgress) {
1642 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1643 // In case the new progress jumped suddenly, still show an
1644 // increment of 1.
1645 if (lastDisplayedProgress != 100) {
1646 // Artificially sleep 1/10th a second to slow down the animation.
1647 usleep(100000);
1648 if (lastDisplayedProgress < newProgress) {
1649 lastDisplayedProgress++;
1650 }
1651 }
1652 // Put the progress percentage right below the animation.
1653 int posY = animation.height / 3;
1654 int posX = TEXT_CENTER_VALUE;
1655 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1656 }
1657
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001658 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001659
Mathias Agopiana8826d62009-10-01 03:10:14 -07001660 eglSwapBuffers(mDisplay, mSurface);
1661
1662 nsecs_t now = systemTime();
1663 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001664 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001665 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001666
1667 if (delay > 0) {
1668 struct timespec spec;
1669 spec.tv_sec = (now + delay) / 1000000000;
1670 spec.tv_nsec = (now + delay) % 1000000000;
1671 int err;
1672 do {
Yi Kong911ac232019-03-24 01:49:02 -07001673 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Keith Mok0f2e6682021-11-15 05:50:32 +00001674 } while (err == EINTR);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001675 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001676
1677 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001678 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001679
Mathias Agopiana8826d62009-10-01 03:10:14 -07001680 usleep(part.pause * ns2us(frameDuration));
Kevin Hesterd3782b22012-04-26 10:38:55 -07001681
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001682 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1683 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001684 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1685 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1686 continue;
1687 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001688 break; // exit the infinite non-fading part when it has been played at least once
1689 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001690 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001691 }
1692
1693 // Free textures created for looping parts now that the animation is done.
1694 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001695 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001696 const size_t fcount = part.frames.size();
1697 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001698 const Animation::Frame& frame(part.frames[j]);
1699 glDeleteTextures(1, &frame.tid);
1700 }
1701 }
1702 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001703
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001704 ALOGD("%sAnimationShownTiming End time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1705 elapsedRealtime());
1706
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001707 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001708}
1709
Marin Shalamanov9070c052020-05-18 19:05:17 +02001710void BootAnimation::processDisplayEvents() {
1711 // This will poll mDisplayEventReceiver and if there are new events it'll call
1712 // displayEventCallback synchronously.
1713 mLooper->pollOnce(0);
1714}
1715
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001716void BootAnimation::handleViewport(nsecs_t timestep) {
1717 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1718 return;
1719 }
1720 if (mTargetInset < 0) {
1721 // Poll the amount for the top display inset. This will return -1 until persistent properties
1722 // have been loaded.
1723 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1724 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1725 }
1726 if (mTargetInset <= 0) {
1727 return;
1728 }
1729
1730 if (mCurrentInset < mTargetInset) {
1731 // After the device boots, the inset will effectively be cropped away. We animate this here.
1732 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1733 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1734
1735 SurfaceComposerClient::Transaction()
1736 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1737 .apply();
1738 } else {
1739 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1740 // later. This changes the coordinate system, and means we must move the surface up by
1741 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001742 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1743 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1744
1745 SurfaceComposerClient::Transaction t;
1746 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1747 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001748 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001749 t.apply();
1750
1751 mTargetInset = mCurrentInset = 0;
1752 }
1753
1754 int delta = timestep * mTargetInset / ms2ns(200);
1755 mCurrentInset += delta;
1756}
1757
Marin Shalamanov9070c052020-05-18 19:05:17 +02001758void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001759 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1760 e = animation->parts.end(); it != e; ++it) {
1761 if (it->animation)
1762 releaseAnimation(it->animation);
1763 }
1764 if (animation->zip)
1765 delete animation->zip;
1766 delete animation;
1767}
1768
Marin Shalamanov9070c052020-05-18 19:05:17 +02001769BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001770 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001771 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001772 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001773 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001774 }
1775 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001776 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001777 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001778 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001779 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001780 }
1781
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001782 ALOGD("%s is loaded successfully", fn.string());
1783
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001784 Animation *animation = new Animation;
1785 animation->fileName = fn;
1786 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001787 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001788 mLoadedFiles.add(animation->fileName);
1789
1790 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001791 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001792 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001793 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001794 }
1795
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001796 mLoadedFiles.remove(fn);
1797 return animation;
1798}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001799
1800bool BootAnimation::updateIsTimeAccurate() {
1801 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1802 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1803
1804 if (mTimeIsAccurate) {
1805 return true;
1806 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001807 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001808 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001809
1810 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1811 mTimeFormat12Hour = true;
1812 }
1813
Damien Bargiacchi97480862016-03-29 14:55:55 -07001814 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1815 mTimeIsAccurate = true;
1816 return true;
1817 }
1818
1819 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001820 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001821 long long lastChangedTime = 0;
1822 fscanf(file, "%lld", &lastChangedTime);
1823 fclose(file);
1824 if (lastChangedTime > 0) {
1825 struct timespec now;
1826 clock_gettime(CLOCK_REALTIME, &now);
1827 // Match the Java timestamp format
1828 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001829 if (ACCURATE_TIME_EPOCH < rtcNow
1830 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1831 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001832 mTimeIsAccurate = true;
1833 }
1834 }
1835 }
1836
1837 return mTimeIsAccurate;
1838}
1839
1840BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
Josh Yangf95b2002021-12-23 14:32:28 -08001841 mInotifyFd(-1), mBootAnimWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001842
1843BootAnimation::TimeCheckThread::~TimeCheckThread() {
1844 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1845 close(mInotifyFd);
1846}
1847
1848bool BootAnimation::TimeCheckThread::threadLoop() {
1849 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1850 && mBootAnimation->mClockEnabled;
1851 if (!shouldLoop) {
1852 close(mInotifyFd);
1853 mInotifyFd = -1;
1854 }
1855 return shouldLoop;
1856}
1857
1858bool BootAnimation::TimeCheckThread::doThreadLoop() {
1859 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1860
1861 // Poll instead of doing a blocking read so the Thread can exit if requested.
1862 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1863 ssize_t pollResult = poll(&pfd, 1, 1000);
1864
1865 if (pollResult == 0) {
1866 return true;
1867 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001868 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001869 return false;
1870 }
1871
1872 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1873 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1874 if (length == 0) {
1875 return true;
1876 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001877 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001878 return false;
1879 }
1880
1881 const struct inotify_event *event;
1882 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1883 event = (const struct inotify_event *) ptr;
Josh Yangf95b2002021-12-23 14:32:28 -08001884 if (event->wd == mBootAnimWd && strcmp(BOOTANIM_TIME_DIR_NAME, event->name) == 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001885 addTimeDirWatch();
1886 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1887 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1888 return !mBootAnimation->updateIsTimeAccurate();
1889 }
1890 }
1891
1892 return true;
1893}
1894
1895void BootAnimation::TimeCheckThread::addTimeDirWatch() {
Josh Yangf95b2002021-12-23 14:32:28 -08001896 mTimeWd = inotify_add_watch(mInotifyFd, BOOTANIM_TIME_DIR_PATH,
Damien Bargiacchi97480862016-03-29 14:55:55 -07001897 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1898 if (mTimeWd > 0) {
1899 // No need to watch for the time directory to be created if it already exists
Josh Yangf95b2002021-12-23 14:32:28 -08001900 inotify_rm_watch(mInotifyFd, mBootAnimWd);
1901 mBootAnimWd = -1;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001902 }
1903}
1904
1905status_t BootAnimation::TimeCheckThread::readyToRun() {
1906 mInotifyFd = inotify_init();
1907 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001908 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001909 return NO_INIT;
1910 }
1911
Josh Yangf95b2002021-12-23 14:32:28 -08001912 mBootAnimWd = inotify_add_watch(mInotifyFd, BOOTANIM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1913 if (mBootAnimWd < 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001914 close(mInotifyFd);
1915 mInotifyFd = -1;
Josh Yangf95b2002021-12-23 14:32:28 -08001916 SLOGE("Could not add watch for %s: %s", BOOTANIM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001917 return NO_INIT;
1918 }
1919
1920 addTimeDirWatch();
1921
1922 if (mBootAnimation->updateIsTimeAccurate()) {
1923 close(mInotifyFd);
1924 mInotifyFd = -1;
1925 return ALREADY_EXISTS;
1926 }
1927
1928 return NO_ERROR;
1929}
1930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931// ---------------------------------------------------------------------------
1932
Marin Shalamanov9070c052020-05-18 19:05:17 +02001933} // namespace android