blob: 27dadda40407843bf175916952c216fb0b330b89 [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";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090074static const char PRODUCT_ENCRYPTED_BOOTANIMATION_FILE[] = "/product/media/bootanimation-encrypted.zip";
Damien Bargiacchi97480862016-03-29 14:55:55 -070075static const char SYSTEM_ENCRYPTED_BOOTANIMATION_FILE[] = "/system/media/bootanimation-encrypted.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070076static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090077static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070078static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
79
Nikita Ioffe06c986e2020-01-27 17:16:03 +000080static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
81static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
82static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
83
Josh Yangf95b2002021-12-23 14:32:28 -080084static const char BOOTANIM_DATA_DIR_PATH[] = "/data/bootanim";
85static const char BOOTANIM_TIME_DIR_NAME[] = "time";
86static const char BOOTANIM_TIME_DIR_PATH[] = "/data/bootanim/time";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070087static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
88static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +000089static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
90static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
Damien Bargiacchi97480862016-03-29 14:55:55 -070091static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
Josh Yangf95b2002021-12-23 14:32:28 -080092static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/bootanim/time/last_time_change";
Damien Bargiacchi97480862016-03-29 14:55:55 -070093static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
Josh Yangf95b2002021-12-23 14:32:28 -080094static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/bootanim/time/time_is_accurate";
95static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/bootanim/time/time_format_12_hour";
Damien Bargiacchi96762812016-07-12 15:53:40 -070096// Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
97static const long long ACCURATE_TIME_EPOCH = 946684800000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070098static constexpr char FONT_BEGIN_CHAR = ' ';
99static constexpr char FONT_END_CHAR = '~' + 1;
100static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
101static constexpr size_t FONT_NUM_COLS = 16;
102static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
103static const int TEXT_CENTER_VALUE = INT_MAX;
104static const int TEXT_MISSING_VALUE = INT_MIN;
Damien Bargiacchi97480862016-03-29 14:55:55 -0700105static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000106static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
Huihong Luod4a217e2020-01-16 15:56:33 -0800107static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
Thiébaud Weksteen08de4432021-11-18 13:25:59 +1100108static const char CLOCK_ENABLED_PROP_NAME[] = "persist.sys.bootanim.clock.enabled";
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +0900109static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
niuwenchao9cd6ac82022-12-23 17:34:22 +0800110static const int MAX_CHECK_EXIT_INTERVAL_US = 50000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700111static constexpr size_t TEXT_POS_LEN_MAX = 16;
Shan Huang2b31a362021-08-16 16:45:39 +0000112static const int DYNAMIC_COLOR_COUNT = 4;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000113static const char U_TEXTURE[] = "uTexture";
114static const char U_FADE[] = "uFade";
115static const char U_CROP_AREA[] = "uCropArea";
Shan Huang2b31a362021-08-16 16:45:39 +0000116static const char U_START_COLOR_PREFIX[] = "uStartColor";
117static const char U_END_COLOR_PREFIX[] = "uEndColor";
118static const char U_COLOR_PROGRESS[] = "uColorProgress";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000119static const char A_UV[] = "aUv";
120static const char A_POSITION[] = "aPosition";
121static const char VERTEX_SHADER_SOURCE[] = R"(
122 precision mediump float;
123 attribute vec4 aPosition;
124 attribute highp vec2 aUv;
125 varying highp vec2 vUv;
126 void main() {
127 gl_Position = aPosition;
128 vUv = aUv;
129 })";
Shan Huang2b31a362021-08-16 16:45:39 +0000130static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
131 precision mediump float;
Shan Huang81846ba2021-09-07 19:07:47 +0000132 const float cWhiteMaskThreshold = 0.05;
Shan Huang2b31a362021-08-16 16:45:39 +0000133 uniform sampler2D uTexture;
134 uniform float uFade;
135 uniform float uColorProgress;
Andrew Zengf9f58222022-11-08 11:10:48 -0800136 uniform vec3 uStartColor0;
137 uniform vec3 uStartColor1;
138 uniform vec3 uStartColor2;
139 uniform vec3 uStartColor3;
140 uniform vec3 uEndColor0;
141 uniform vec3 uEndColor1;
142 uniform vec3 uEndColor2;
143 uniform vec3 uEndColor3;
Shan Huang2b31a362021-08-16 16:45:39 +0000144 varying highp vec2 vUv;
145 void main() {
146 vec4 mask = texture2D(uTexture, vUv);
Shan Huang488ff742021-08-25 20:10:46 +0000147 float r = mask.r;
148 float g = mask.g;
149 float b = mask.b;
150 float a = mask.a;
151 // If all channels have values, render pixel as a shade of white.
152 float useWhiteMask = step(cWhiteMaskThreshold, r)
153 * step(cWhiteMaskThreshold, g)
154 * step(cWhiteMaskThreshold, b)
155 * step(cWhiteMaskThreshold, a);
Andrew Zengf9f58222022-11-08 11:10:48 -0800156 vec3 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
Shan Huang488ff742021-08-25 20:10:46 +0000157 + g * mix(uStartColor1, uEndColor1, uColorProgress)
158 + b * mix(uStartColor2, uEndColor2, uColorProgress)
159 + a * mix(uStartColor3, uEndColor3, uColorProgress);
Andrew Zengf9f58222022-11-08 11:10:48 -0800160 color = mix(color, vec3((r + g + b + a) * 0.25), useWhiteMask);
161 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade));
Shan Huang2b31a362021-08-16 16:45:39 +0000162 })";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000163static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
164 precision mediump float;
165 uniform sampler2D uTexture;
166 uniform float uFade;
167 varying highp vec2 vUv;
168 void main() {
169 vec4 color = texture2D(uTexture, vUv);
Shan Huang2b31a362021-08-16 16:45:39 +0000170 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000171 })";
172static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
173 precision mediump float;
174 uniform sampler2D uTexture;
175 uniform vec4 uCropArea;
176 varying highp vec2 vUv;
177 void main() {
178 vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
179 mix(uCropArea.y, uCropArea.w, vUv.y));
180 gl_FragColor = texture2D(uTexture, uv);
181 })";
182
183static GLfloat quadPositions[] = {
184 -0.5f, -0.5f,
185 +0.5f, -0.5f,
186 +0.5f, +0.5f,
187 +0.5f, +0.5f,
188 -0.5f, +0.5f,
189 -0.5f, -0.5f
190};
191static GLfloat quadUVs[] = {
192 0.0f, 1.0f,
193 1.0f, 1.0f,
194 1.0f, 0.0f,
195 1.0f, 0.0f,
196 0.0f, 0.0f,
197 0.0f, 1.0f
198};
Narayan Kamathafd31e02013-12-03 13:16:03 +0000199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200// ---------------------------------------------------------------------------
201
Ed Coyne7464ac92017-06-08 12:26:48 -0700202BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200203 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700204 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700205 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400206
Keun-young Parkb5938422017-03-23 13:46:24 -0700207 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
208 if (powerCtl.empty()) {
209 mShuttingDown = false;
210 } else {
211 mShuttingDown = true;
212 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700213 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
214 elapsedRealtime());
215}
216
217BootAnimation::~BootAnimation() {
218 if (mAnimation != nullptr) {
219 releaseAnimation(mAnimation);
220 mAnimation = nullptr;
221 }
222 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
223 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224}
225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700227 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700228 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700229 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700230 // Load the animation content -- this can be slow (eg 200ms)
231 // called before waitForSurfaceFlinger() in main() to avoid wait
232 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
233 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
234 preloadAnimation();
235 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
236 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
Mathias Agopianbc726112009-09-23 15:44:05 -0700237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238}
239
Mathias Agopianbc726112009-09-23 15:44:05 -0700240sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 return mSession;
242}
243
Marin Shalamanov9070c052020-05-18 19:05:17 +0200244void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700245 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700246 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700247
248 // calling requestExit() is not enough here because the Surface code
249 // might be blocked on a condition variable that will never be updated.
250 kill( getpid(), SIGKILL );
251 requestExit();
252}
253
Shan Huang2b31a362021-08-16 16:45:39 +0000254static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
255 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400256 AImageDecoder* decoder = nullptr;
257 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
258 if (!decoder) {
259 return nullptr;
260 }
261
262 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
263 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
264 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
265 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
266 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
267 outInfo->flags = 0;
268
Shan Huang2b31a362021-08-16 16:45:39 +0000269 if (!premultiplyAlpha) {
270 AImageDecoder_setUnpremultipliedRequired(decoder, true);
271 }
272
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400273 const size_t size = outInfo->stride * outInfo->height;
274 void* pixels = malloc(size);
275 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
276 AImageDecoder_delete(decoder);
277
278 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
279 free(pixels);
280 return nullptr;
281 }
282 return pixels;
283}
284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
Shan Huang2b31a362021-08-16 16:45:39 +0000286 const char* name, bool premultiplyAlpha) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700288 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400290
291 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000292 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
293 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400294 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 asset->close();
297 delete asset;
298
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400299 if (!pixels) {
300 return NO_INIT;
301 }
302
303 const int w = bitmapInfo.width;
304 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 texture->w = w;
307 texture->h = h;
308
309 glGenTextures(1, &texture->name);
310 glBindTexture(GL_TEXTURE_2D, texture->name);
311
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400312 switch (bitmapInfo.format) {
313 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400315 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400317 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400319 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400321 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400323 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400325 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400327 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 break;
329 default:
330 break;
331 }
332
Lucas Dupin8eedc022021-07-29 21:49:07 +0000333 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
334 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
335 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
336 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 return NO_ERROR;
339}
340
Shan Huang2b31a362021-08-16 16:45:39 +0000341status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
342 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400343 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000344 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
345 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400346 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700347
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200348 // FileMap memory is never released until application exit.
349 // Release it now as the texture is already loaded and the memory used for
350 // the packed resource can be released.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700351 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200352
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400353 if (!pixels) {
354 return NO_INIT;
355 }
356
357 const int w = bitmapInfo.width;
358 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700359
Mathias Agopiana8826d62009-10-01 03:10:14 -0700360 int tw = 1 << (31 - __builtin_clz(w));
361 int th = 1 << (31 - __builtin_clz(h));
362 if (tw < w) tw <<= 1;
363 if (th < h) th <<= 1;
364
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400365 switch (bitmapInfo.format) {
366 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530367 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700368 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700369 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700370 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400371 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700372 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530373 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400374 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700375 }
376 break;
377
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400378 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530379 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700380 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700381 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700382 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400383 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700384 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530385 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400386 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700387 }
388 break;
389 default:
390 break;
391 }
392
Lucas Dupin8eedc022021-07-29 21:49:07 +0000393 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
394 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
395 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
396 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700397
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700398 *width = w;
399 *height = h;
400
Mathias Agopiana8826d62009-10-01 03:10:14 -0700401 return NO_ERROR;
402}
403
Marin Shalamanov9070c052020-05-18 19:05:17 +0200404class BootAnimation::DisplayEventCallback : public LooperCallback {
405 BootAnimation* mBootAnimation;
406
407public:
408 DisplayEventCallback(BootAnimation* bootAnimation) {
409 mBootAnimation = bootAnimation;
410 }
411
412 int handleEvent(int /* fd */, int events, void* /* data */) {
413 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
414 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
415 events);
416 return 0; // remove the callback
417 }
418
419 if (!(events & Looper::EVENT_INPUT)) {
420 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
421 return 1; // keep the callback
422 }
423
424 constexpr int kBufferSize = 100;
425 DisplayEventReceiver::Event buffer[kBufferSize];
426 ssize_t numEvents;
427 do {
428 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
429 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
430 const auto& event = buffer[i];
431 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
432 SLOGV("Hotplug received");
433
434 if (!event.hotplug.connected) {
435 // ignore hotplug disconnect
436 continue;
437 }
438 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
439 event.header.displayId);
440
441 if (token != mBootAnimation->mDisplayToken) {
442 // ignore hotplug of a secondary display
443 continue;
444 }
445
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100446 DisplayMode displayMode;
447 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
448 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200449 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100450 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200451 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100452 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
453 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200454 }
455 }
456 } while (numEvents > 0);
457
458 return 1; // keep the callback
459 }
460};
461
462EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
463 const EGLint attribs[] = {
Andrii Chepurnyid93f7b22023-03-15 11:22:07 +0200464 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
Marin Shalamanov9070c052020-05-18 19:05:17 +0200465 EGL_RED_SIZE, 8,
466 EGL_GREEN_SIZE, 8,
467 EGL_BLUE_SIZE, 8,
468 EGL_DEPTH_SIZE, 0,
469 EGL_NONE
470 };
471 EGLint numConfigs;
472 EGLConfig config;
473 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
474 return config;
475}
476
Marin Shalamanov047802d2020-05-19 23:55:12 +0200477ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
478 ui::Size limited(width, height);
479 bool wasLimited = false;
480 const float aspectRatio = float(width) / float(height);
481 if (mMaxWidth != 0 && width > mMaxWidth) {
482 limited.height = mMaxWidth / aspectRatio;
483 limited.width = mMaxWidth;
484 wasLimited = true;
485 }
486 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
487 limited.height = mMaxHeight;
488 limited.width = mMaxHeight * aspectRatio;
489 wasLimited = true;
490 }
491 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
492 limited.width, limited.height, width, height);
493 return limited;
494}
495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496status_t BootAnimation::readyToRun() {
497 mAssets.addDefaultAssets();
498
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800499 mDisplayToken = SurfaceComposerClient::getInternalDisplayToken();
500 if (mDisplayToken == nullptr)
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800501 return NAME_NOT_FOUND;
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800502
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100503 DisplayMode displayMode;
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800504 const status_t error =
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100505 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800506 if (error != NO_ERROR)
507 return error;
508
Marin Shalamanov047802d2020-05-19 23:55:12 +0200509 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
510 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100511 ui::Size resolution = displayMode.resolution;
Marin Shalamanov047802d2020-05-19 23:55:12 +0200512 resolution = limitSurfaceSize(resolution.width, resolution.height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 // create the native surface
Jeff Brown0b722fe2012-08-24 22:40:14 -0700514 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
xi yuc3415442022-05-09 08:58:02 +0000515 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565,
516 ISurfaceComposerClient::eOpaque);
Mathias Agopian439863f2011-06-28 19:09:31 -0700517
Robert Carre13b58e2017-08-31 14:50:44 -0700518 SurfaceComposerClient::Transaction t;
Huihong Luof97c9e22019-05-29 11:08:01 -0700519
520 // this guest property specifies multi-display IDs to show the boot animation
521 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800522 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200523 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700524 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800525 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700526 bool isValid = displayValue[0] != '\0';
527 if (isValid) {
528 char *p = displayValue;
529 while (*p) {
530 if (!isdigit(*p) && *p != ',') {
531 isValid = false;
532 break;
533 }
534 p ++;
535 }
536 if (!isValid)
Huihong Luod4a217e2020-01-16 15:56:33 -0800537 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700538 }
539 if (isValid) {
540 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200541 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700542 physicalDisplayIds.add(id);
543 if (stream.peek() == ',')
544 stream.ignore();
545 }
546
547 // In the case of multi-display, boot animation shows on the specified displays
548 // in addition to the primary display
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700549 const auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
550 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700551 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700552 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
553 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
554 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700555 }
556 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700557 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700558 }
559
Robert Carre13b58e2017-08-31 14:50:44 -0700560 t.setLayer(control, 0x40000000)
561 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562
Mathias Agopian17f638b2009-04-16 20:04:08 -0700563 sp<Surface> s = control->getSurface();
564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700567 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200568 EGLConfig config = getEglConfig(display);
569 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000570 // Initialize egl context with client version number 2.0.
571 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
572 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200573 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 eglQuerySurface(display, surface, EGL_WIDTH, &w);
575 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700576
Mathias Agopianabac0102009-07-31 14:47:00 -0700577 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
578 return NO_INIT;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 mDisplay = display;
581 mContext = context;
582 mSurface = surface;
joenchen85b339f2022-04-11 23:58:34 +0800583 mInitWidth = mWidth = w;
584 mInitHeight = mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700585 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200587 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000589 // Rotate the boot animation according to the value specified in the sysprop
590 // ro.bootanim.set_orientation_<display_id>. Four values are supported: ORIENTATION_0,
591 // ORIENTATION_90, ORIENTATION_180 and ORIENTATION_270.
592 // If the value isn't specified or is ORIENTATION_0, nothing will be changed.
593 // This is needed to support having boot animation in orientations different from the natural
594 // device orientation. For example, on tablets that may want to keep natural orientation
595 // portrait for applications compatibility and to have the boot animation in landscape.
596 rotateAwayFromNaturalOrientationIfNeeded();
597
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200598 projectSceneToWindow();
599
Marin Shalamanov9070c052020-05-18 19:05:17 +0200600 // Register a display event receiver
601 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
602 status_t status = mDisplayEventReceiver->initCheck();
603 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
604 status);
605 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
606 new DisplayEventCallback(this), nullptr);
607
Huihong Luo50a2f362018-08-11 09:27:57 -0700608 return NO_ERROR;
609}
610
Mariia Sandrikovaa166f012022-12-10 02:32:14 +0000611void BootAnimation::rotateAwayFromNaturalOrientationIfNeeded() {
612 const auto orientation = parseOrientationProperty();
613
614 if (orientation == ui::ROTATION_0) {
615 // Do nothing if the sysprop isn't set or is set to ROTATION_0.
616 return;
617 }
618
619 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
620 std::swap(mWidth, mHeight);
621 std::swap(mInitWidth, mInitHeight);
622 mFlingerSurfaceControl->updateDefaultBufferSize(mWidth, mHeight);
623 }
624
625 Rect displayRect(0, 0, mWidth, mHeight);
626 Rect layerStackRect(0, 0, mWidth, mHeight);
627
628 SurfaceComposerClient::Transaction t;
629 t.setDisplayProjection(mDisplayToken, orientation, layerStackRect, displayRect);
630 t.apply();
631}
632
633ui::Rotation BootAnimation::parseOrientationProperty() {
634 const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
635 if (displayIds.size() == 0) {
636 return ui::ROTATION_0;
637 }
638 const auto displayId = displayIds[0];
639 const auto syspropName = [displayId] {
640 std::stringstream ss;
641 ss << "ro.bootanim.set_orientation_" << displayId.value;
642 return ss.str();
643 }();
644 const auto syspropValue = android::base::GetProperty(syspropName, "ORIENTATION_0");
645 if (syspropValue == "ORIENTATION_90") {
646 return ui::ROTATION_90;
647 } else if (syspropValue == "ORIENTATION_180") {
648 return ui::ROTATION_180;
649 } else if (syspropValue == "ORIENTATION_270") {
650 return ui::ROTATION_270;
651 }
652 return ui::ROTATION_0;
653}
654
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200655void BootAnimation::projectSceneToWindow() {
656 glViewport(0, 0, mWidth, mHeight);
657 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200658}
659
Marin Shalamanov9070c052020-05-18 19:05:17 +0200660void BootAnimation::resizeSurface(int newWidth, int newHeight) {
661 // We assume this function is called on the animation thread.
662 if (newWidth == mWidth && newHeight == mHeight) {
663 return;
664 }
665 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
666
667 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
668 eglDestroySurface(mDisplay, mSurface);
669
joenchen85b339f2022-04-11 23:58:34 +0800670 mFlingerSurfaceControl->updateDefaultBufferSize(newWidth, newHeight);
Marin Shalamanov047802d2020-05-19 23:55:12 +0200671 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
672 mWidth = limitedSize.width;
673 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200674
675 SurfaceComposerClient::Transaction t;
676 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
677 t.apply();
678
679 EGLConfig config = getEglConfig(mDisplay);
680 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
681 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
682 SLOGE("Can't make the new surface current. Error %d", eglGetError());
683 return;
684 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200685
686 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200687
688 mSurface = surface;
689}
690
Huihong Luo50a2f362018-08-11 09:27:57 -0700691bool BootAnimation::preloadAnimation() {
692 findBootAnimationFile();
693 if (!mZipFileName.isEmpty()) {
694 mAnimation = loadAnimation(mZipFileName);
695 return (mAnimation != nullptr);
696 }
697
698 return false;
699}
700
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000701bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
702 for (const std::string& f : files) {
703 if (access(f.c_str(), R_OK) == 0) {
704 mZipFileName = f.c_str();
705 return true;
706 }
707 }
708 return false;
709}
710
Huihong Luo50a2f362018-08-11 09:27:57 -0700711void BootAnimation::findBootAnimationFile() {
Elliott Hughesc367d482013-10-29 13:12:55 -0700712 // If the device has encryption turned on or is in process
Jason parksbd9a08d2011-01-31 15:04:34 -0600713 // of being encrypted we show the encrypted boot animation.
714 char decrypt[PROPERTY_VALUE_MAX];
715 property_get("vold.decrypt", decrypt, "");
716
Keun-young Parkb5938422017-03-23 13:46:24 -0700717 bool encryptedAnimation = atoi(decrypt) != 0 ||
718 !strcmp("trigger_restart_min_framework", decrypt);
Jason parksbd9a08d2011-01-31 15:04:34 -0600719
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900720 if (!mShuttingDown && encryptedAnimation) {
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000721 static const std::vector<std::string> encryptedBootFiles = {
722 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
723 };
724 if (findBootAnimationFileInternal(encryptedBootFiles)) {
725 return;
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900726 }
Jason parksbd9a08d2011-01-31 15:04:34 -0600727 }
Beverly34ffe252019-05-17 11:03:54 -0400728
729 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000730 static const std::vector<std::string> bootFiles = {
731 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
732 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
733 };
734 static const std::vector<std::string> shutdownFiles = {
735 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
736 };
737 static const std::vector<std::string> userspaceRebootFiles = {
738 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
739 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
740 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700741
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000742 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
743 findBootAnimationFileInternal(userspaceRebootFiles);
744 } else if (mShuttingDown) {
745 findBootAnimationFileInternal(shutdownFiles);
746 } else {
747 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749}
750
Lucas Dupin8eedc022021-07-29 21:49:07 +0000751GLuint compileShader(GLenum shaderType, const GLchar *source) {
752 GLuint shader = glCreateShader(shaderType);
753 glShaderSource(shader, 1, &source, 0);
754 glCompileShader(shader);
755 GLint isCompiled = 0;
756 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
757 if (isCompiled == GL_FALSE) {
758 SLOGE("Compile shader failed. Shader type: %d", shaderType);
Shan Huang81846ba2021-09-07 19:07:47 +0000759 GLint maxLength = 0;
760 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
761 std::vector<GLchar> errorLog(maxLength);
762 glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
763 SLOGE("Shader compilation error: %s", &errorLog[0]);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000764 return 0;
765 }
766 return shader;
767}
768
769GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
770 GLuint program = glCreateProgram();
771 glAttachShader(program, vertexShader);
772 glAttachShader(program, fragmentShader);
773 glLinkProgram(program);
774 GLint isLinked = 0;
775 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
776 if (isLinked == GL_FALSE) {
777 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
778 vertexShader, fragmentShader);
779 return 0;
780 }
781 return program;
782}
783
784void BootAnimation::initShaders() {
Shan Huang2b31a362021-08-16 16:45:39 +0000785 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000786 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
787 GLuint imageFragmentShader =
Shan Huang2b31a362021-08-16 16:45:39 +0000788 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
789 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
790 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000791 GLuint textFragmentShader =
792 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
793
794 // Initialize image shader.
795 mImageShader = linkShader(vertexShader, imageFragmentShader);
796 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
797 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
798 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
799 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
800 glEnableVertexAttribArray(positionLocation);
801 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
802 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
803 glEnableVertexAttribArray(uvLocation);
804
805 // Initialize text shader.
806 mTextShader = linkShader(vertexShader, textFragmentShader);
807 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
808 uvLocation = glGetAttribLocation(mTextShader, A_UV);
809 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
810 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
811 glEnableVertexAttribArray(positionLocation);
812 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
813 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
814 glEnableVertexAttribArray(uvLocation);
815}
816
Marin Shalamanov9070c052020-05-18 19:05:17 +0200817bool BootAnimation::threadLoop() {
818 bool result;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000819 initShaders();
820
Narayan Kamathafd31e02013-12-03 13:16:03 +0000821 // We have no bootanimation file, so we use the stock android logo
822 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700823 if (mZipFileName.isEmpty()) {
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +0900824 ALOGD("No animation file");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200825 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700826 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200827 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700828 }
829
Philip Junker60600562020-11-25 18:16:16 +0100830 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
832 eglDestroyContext(mDisplay, mContext);
833 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700834 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700835 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700836 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530837 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700838 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200839 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840}
841
Marin Shalamanov9070c052020-05-18 19:05:17 +0200842bool BootAnimation::android() {
Lucas Dupin8eedc022021-07-29 21:49:07 +0000843 glActiveTexture(GL_TEXTURE0);
844
Wei Wang159a4102018-10-23 23:15:58 -0700845 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700846 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700847 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
848 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849
Ed Coyne7464ac92017-06-08 12:26:48 -0700850 mCallbacks->init({});
851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700853 glDisable(GL_DITHER);
854 glDisable(GL_SCISSOR_TEST);
Shan Huangbfd2d3c2021-09-09 23:19:04 +0000855 glUseProgram(mImageShader);
856
Mathias Agopian59f19e42011-05-06 19:22:12 -0700857 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 glClear(GL_COLOR_BUFFER_BIT);
859 eglSwapBuffers(mDisplay, mSurface);
860
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700861 // Blend state
862 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 const nsecs_t startTime = systemTime();
865 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200866 processDisplayEvents();
867 const GLint xc = (mWidth - mAndroid[0].w) / 2;
868 const GLint yc = (mHeight - mAndroid[0].h) / 2;
869 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
870 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
871 updateRect.height());
872
Mathias Agopian13796652009-03-24 22:49:21 -0700873 nsecs_t now = systemTime();
874 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700875 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
876 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
877 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878
Mathias Agopian81668642009-07-28 11:41:30 -0700879 glDisable(GL_SCISSOR_TEST);
880 glClear(GL_COLOR_BUFFER_BIT);
881
882 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000885 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
886 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700888 glEnable(GL_BLEND);
889 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000890 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891
Mathias Agopian627e7b52009-05-21 19:21:59 -0700892 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
893 if (res == EGL_FALSE)
894 break;
895
Mathias Agopian13796652009-03-24 22:49:21 -0700896 // 12fps: don't animate too fast to preserve CPU
897 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
898 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700899 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700900
901 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 } while (!exitPending());
903
904 glDeleteTextures(1, &mAndroid[0].name);
905 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 return false;
907}
908
Kevin Hesterd3782b22012-04-26 10:38:55 -0700909void BootAnimation::checkExit() {
910 // Allow surface flinger to gracefully request shutdown
911 char value[PROPERTY_VALUE_MAX];
912 property_get(EXIT_PROP_NAME, value, "0");
913 int exitnow = atoi(value);
914 if (exitnow) {
915 requestExit();
916 }
917}
918
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700919bool BootAnimation::validClock(const Animation::Part& part) {
920 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
921}
922
923bool parseTextCoord(const char* str, int* dest) {
924 if (strcmp("c", str) == 0) {
925 *dest = TEXT_CENTER_VALUE;
926 return true;
927 }
928
929 char* end;
930 int val = (int) strtol(str, &end, 0);
931 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
932 return false;
933 }
934 *dest = val;
935 return true;
936}
937
938// Parse two position coordinates. If only string is non-empty, treat it as the y value.
939void parsePosition(const char* str1, const char* str2, int* x, int* y) {
940 bool success = false;
941 if (strlen(str1) == 0) { // No values were specified
942 // success = false
943 } else if (strlen(str2) == 0) { // we have only one value
944 if (parseTextCoord(str1, y)) {
945 *x = TEXT_CENTER_VALUE;
946 success = true;
947 }
948 } else {
949 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
950 success = true;
951 }
952 }
953
954 if (!success) {
955 *x = TEXT_MISSING_VALUE;
956 *y = TEXT_MISSING_VALUE;
957 }
958}
959
Jesse Hall083b84c2014-09-22 10:51:09 -0700960// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
961// characters in str is a hex number in [0, 255], which are converted to
962// floating point values in the range [0.0, 1.0] and placed in the
963// corresponding elements of color.
964//
965// If the input string isn't valid, parseColor returns false and color is
966// left unchanged.
967static bool parseColor(const char str[7], float color[3]) {
968 float tmpColor[3];
969 for (int i = 0; i < 3; i++) {
970 int val = 0;
971 for (int j = 0; j < 2; j++) {
972 val *= 16;
973 char c = str[2*i + j];
974 if (c >= '0' && c <= '9') val += c - '0';
975 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
976 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
977 else return false;
978 }
979 tmpColor[i] = static_cast<float>(val) / 255.0f;
980 }
981 memcpy(color, tmpColor, sizeof(tmpColor));
982 return true;
983}
984
Shan Huang2b31a362021-08-16 16:45:39 +0000985// Parse a color represented as a signed decimal int string.
986// E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
987// If the input color string is empty, set color with values in defaultColor.
988static void parseColorDecimalString(const std::string& colorString,
989 float color[3], float defaultColor[3]) {
990 if (colorString == "") {
991 memcpy(color, defaultColor, sizeof(float) * 3);
992 return;
993 }
994 int colorInt = atoi(colorString.c_str());
995 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
996 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
997 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
998}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700999
Marin Shalamanov9070c052020-05-18 19:05:17 +02001000static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001001 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -07001002 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001003 if (!entry) {
1004 return false;
1005 }
1006
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001007 FileMap* entryMap = zip->createEntryFileMap(entry);
1008 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -07001009 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001010 if (!entryMap) {
1011 return false;
1012 }
1013
1014 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +00001015 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001016 return true;
1017}
1018
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001019// The font image should be a 96x2 array of character images. The
1020// columns are the printable ASCII characters 0x20 - 0x7f. The
1021// top row is regular text; the bottom row is bold.
1022status_t BootAnimation::initFont(Font* font, const char* fallback) {
1023 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001024
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001025 if (font->map != nullptr) {
1026 glGenTextures(1, &font->texture.name);
1027 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001028
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001029 status = initTexture(font->map, &font->texture.w, &font->texture.h);
1030
Lucas Dupin8eedc022021-07-29 21:49:07 +00001031 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1032 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1033 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1034 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001035 } else if (fallback != nullptr) {
1036 status = initTexture(&font->texture, mAssets, fallback);
1037 } else {
1038 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001039 }
1040
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001041 if (status == NO_ERROR) {
1042 font->char_width = font->texture.w / FONT_NUM_COLS;
1043 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
1044 }
1045
1046 return status;
1047}
1048
1049void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
1050 glEnable(GL_BLEND); // Allow us to draw on top of the animation
1051 glBindTexture(GL_TEXTURE_2D, font.texture.name);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001052 glUseProgram(mTextShader);
1053 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001054
1055 const int len = strlen(str);
1056 const int strWidth = font.char_width * len;
1057
1058 if (*x == TEXT_CENTER_VALUE) {
1059 *x = (mWidth - strWidth) / 2;
1060 } else if (*x < 0) {
1061 *x = mWidth + *x - strWidth;
1062 }
1063 if (*y == TEXT_CENTER_VALUE) {
1064 *y = (mHeight - font.char_height) / 2;
1065 } else if (*y < 0) {
1066 *y = mHeight + *y - font.char_height;
1067 }
1068
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001069 for (int i = 0; i < len; i++) {
1070 char c = str[i];
1071
1072 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1073 c = '?';
1074 }
1075
1076 // Crop the texture to only the pixels in the current glyph
1077 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1078 const int row = charPos / FONT_NUM_COLS;
1079 const int col = charPos % FONT_NUM_COLS;
Lucas Dupin8eedc022021-07-29 21:49:07 +00001080 // Bold fonts are expected in the second half of each row.
1081 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1082 float u0 = ((float)col) / FONT_NUM_COLS;
1083 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1084 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1085 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1086 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001087
1088 *x += font.char_width;
1089 }
1090
1091 glDisable(GL_BLEND); // Return to the animation's default behaviour
1092 glBindTexture(GL_TEXTURE_2D, 0);
1093}
1094
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001095// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001096void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001097 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1098 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001099 static constexpr int TIME_LENGTH = 6;
1100
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001101 time_t rawtime;
1102 time(&rawtime);
1103 struct tm* timeInfo = localtime(&rawtime);
1104
1105 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001106 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1107 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001108
1109 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001110 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001111 mClockEnabled = false;
1112 return;
1113 }
1114
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001115 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001116 int x = xPos;
1117 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001118 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001119}
1120
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001121void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1122 static constexpr int PERCENT_LENGTH = 5;
1123
1124 char percentBuff[PERCENT_LENGTH];
1125 // ';' has the ascii code just after ':', and the font resource contains '%'
1126 // for that ascii code.
1127 sprintf(percentBuff, "%d;", percent);
1128 int x = xPos;
1129 int y = yPos;
1130 drawText(percentBuff, font, false, &x, &y);
1131}
1132
Marin Shalamanov9070c052020-05-18 19:05:17 +02001133bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001134 String8 desString;
1135
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001136 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001137 return false;
1138 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001139 char const* s = desString.string();
Shan Huang2b31a362021-08-16 16:45:39 +00001140 std::string dynamicColoringPartName = "";
1141 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001142
Mathias Agopiana8826d62009-10-01 03:10:14 -07001143 // Parse the description file
1144 for (;;) {
1145 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001146 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001147 String8 line(s, endl - s);
1148 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001149 int fps = 0;
1150 int width = 0;
1151 int height = 0;
1152 int count = 0;
1153 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001154 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001155 int framesToFadeCount = 0;
Shan Huang488ff742021-08-25 20:10:46 +00001156 int colorTransitionStart = 0;
1157 int colorTransitionEnd = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001158 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001159 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001160 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1161 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang2b31a362021-08-16 16:45:39 +00001162 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001163 char pathType;
Shan Huang2b31a362021-08-16 16:45:39 +00001164 // start colors default to black if unspecified
1165 char start_color_0[7] = "000000";
1166 char start_color_1[7] = "000000";
1167 char start_color_2[7] = "000000";
1168 char start_color_3[7] = "000000";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001169
1170 int nextReadPos;
1171
yidong zhang87bb3462022-12-07 15:55:31 +08001172 if (strlen(l) == 0) {
1173 s = ++endl;
1174 continue;
1175 }
1176
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001177 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1178 if (topLineNumbers == 3 || topLineNumbers == 4) {
1179 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001180 animation.width = width;
1181 animation.height = height;
1182 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001183 if (topLineNumbers == 4) {
1184 animation.progressEnabled = (progress != 0);
1185 } else {
1186 animation.progressEnabled = false;
1187 }
Shan Huang488ff742021-08-25 20:10:46 +00001188 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
Shan Huang2b31a362021-08-16 16:45:39 +00001189 dynamicColoringPartNameBuffer,
Shan Huang488ff742021-08-25 20:10:46 +00001190 start_color_0, start_color_1, start_color_2, start_color_3,
1191 &colorTransitionStart, &colorTransitionEnd)) {
Shan Huang2b31a362021-08-16 16:45:39 +00001192 animation.dynamicColoringEnabled = true;
1193 parseColor(start_color_0, animation.startColors[0]);
1194 parseColor(start_color_1, animation.startColors[1]);
1195 parseColor(start_color_2, animation.startColors[2]);
1196 parseColor(start_color_3, animation.startColors[3]);
Shan Huang488ff742021-08-25 20:10:46 +00001197 animation.colorTransitionStart = colorTransitionStart;
1198 animation.colorTransitionEnd = colorTransitionEnd;
Shan Huang2b31a362021-08-16 16:45:39 +00001199 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001200 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1201 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1202 if (pathType == 'f') {
1203 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1204 clockPos2);
1205 } else {
1206 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1207 }
1208 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1209 // "clockPos1=%s, clockPos2=%s",
1210 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001211 Animation::Part part;
Shan Huang2b31a362021-08-16 16:45:39 +00001212 if (path == dynamicColoringPartName) {
1213 // Part is specified to use dynamic coloring.
1214 part.useDynamicColoring = true;
1215 part.postDynamicColoring = false;
1216 postDynamicColoring = true;
1217 } else {
1218 // Part does not use dynamic coloring.
1219 part.useDynamicColoring = false;
1220 part.postDynamicColoring = postDynamicColoring;
1221 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001222 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001223 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001224 part.count = count;
1225 part.pause = pause;
1226 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001227 part.audioData = nullptr;
1228 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001229 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001230 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001231 part.backgroundColor[0] = 0.0f;
1232 part.backgroundColor[1] = 0.0f;
1233 part.backgroundColor[2] = 0.0f;
1234 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001235 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001236 animation.parts.add(part);
1237 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001238 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001239 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001240 Animation::Part part;
1241 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001242 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001243 part.count = 1;
1244 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001245 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001246 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001247 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001248 animation.parts.add(part);
1249 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001250 s = ++endl;
1251 }
1252
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001253 return true;
1254}
1255
Marin Shalamanov9070c052020-05-18 19:05:17 +02001256bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001257 // read all the data structures
1258 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001259 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001260 ZipFileRO* zip = animation.zip;
1261 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001262 return false;
1263 }
1264
1265 ZipEntryRO entry;
1266 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001267 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001268 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001269 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001270 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001271 continue;
1272 }
1273
1274 const String8 entryName(name);
1275 const String8 path(entryName.getPathDir());
1276 const String8 leaf(entryName.getPathLeaf());
1277 if (leaf.size() > 0) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001278 if (entryName == CLOCK_FONT_ZIP_NAME) {
1279 FileMap* map = zip->createEntryFileMap(entry);
1280 if (map) {
1281 animation.clockFont.map = map;
1282 }
1283 continue;
1284 }
1285
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001286 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1287 FileMap* map = zip->createEntryFileMap(entry);
1288 if (map) {
1289 animation.progressFont.map = map;
1290 }
1291 continue;
1292 }
1293
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001294 for (size_t j = 0; j < pcount; j++) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001295 if (path == animation.parts[j].path) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001296 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001297 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001298 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001299 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001300 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001301 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001302 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001303 if (leaf == "audio.wav") {
1304 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001305 part.audioData = (uint8_t *)map->getDataPtr();
1306 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001307 } else if (leaf == "trim.txt") {
1308 part.trimData.setTo((char const*)map->getDataPtr(),
1309 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001310 } else {
1311 Animation::Frame frame;
1312 frame.name = leaf;
1313 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001314 frame.trimWidth = animation.width;
1315 frame.trimHeight = animation.height;
1316 frame.trimX = 0;
1317 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001318 part.frames.add(frame);
1319 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001320 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001321 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001322 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001323 }
1324 }
1325 }
1326 }
1327 }
1328 }
1329
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001330 // If there is trimData present, override the positioning defaults.
1331 for (Animation::Part& part : animation.parts) {
1332 const char* trimDataStr = part.trimData.string();
1333 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1334 const char* endl = strstr(trimDataStr, "\n");
1335 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001336 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001337 break;
1338 }
1339 String8 line(trimDataStr, endl - trimDataStr);
1340 const char* lineStr = line.string();
1341 trimDataStr = ++endl;
1342 int width = 0, height = 0, x = 0, y = 0;
1343 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1344 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1345 frame.trimWidth = width;
1346 frame.trimHeight = height;
1347 frame.trimX = x;
1348 frame.trimY = y;
1349 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001350 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001351 break;
1352 }
1353 }
1354 }
1355
1356 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001357
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001358 return true;
1359}
1360
Marin Shalamanov9070c052020-05-18 19:05:17 +02001361bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001362 if (mAnimation == nullptr) {
1363 mAnimation = loadAnimation(mZipFileName);
1364 }
1365
1366 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001367 return false;
1368
Huihong Luo50a2f362018-08-11 09:27:57 -07001369 // mCallbacks->init() may get called recursively,
1370 // this loop is needed to get the same results
1371 for (const Animation::Part& part : mAnimation->parts) {
1372 if (part.animation != nullptr) {
1373 mCallbacks->init(part.animation->parts);
1374 }
1375 }
1376 mCallbacks->init(mAnimation->parts);
1377
Damien Bargiacchi97480862016-03-29 14:55:55 -07001378 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001379 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1380 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001381 anyPartHasClock = true;
1382 break;
1383 }
1384 }
1385 if (!anyPartHasClock) {
1386 mClockEnabled = false;
Thiébaud Weksteen08de4432021-11-18 13:25:59 +11001387 } else if (!android::base::GetBoolProperty(CLOCK_ENABLED_PROP_NAME, false)) {
1388 mClockEnabled = false;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001389 }
1390
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301391 // Check if npot textures are supported
1392 mUseNpotTextures = false;
1393 String8 gl_extensions;
1394 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1395 if (!exts) {
1396 glGetError();
1397 } else {
1398 gl_extensions.setTo(exts);
1399 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1400 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1401 mUseNpotTextures = true;
1402 }
1403 }
1404
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001405 // Blend required to draw time on top of animation frames.
1406 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001407 glDisable(GL_DITHER);
1408 glDisable(GL_SCISSOR_TEST);
1409 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001410
Greg Kaiser2ded8002021-07-19 17:03:27 +00001411 glEnable(GL_TEXTURE_2D);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001412 glBindTexture(GL_TEXTURE_2D, 0);
1413 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1414 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1415 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1416 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001417 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001418 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001419 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001420 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001421 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001422 }
1423
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001424 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1425
Damien Bargiacchi97480862016-03-29 14:55:55 -07001426 if (mClockEnabled && !updateIsTimeAccurate()) {
1427 mTimeCheckThread = new TimeCheckThread(this);
1428 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1429 }
1430
George Burgess IV0f8e8112021-08-23 17:32:23 -07001431 if (mAnimation->dynamicColoringEnabled) {
Shan Huang7fee3522021-08-18 00:56:08 +00001432 initDynamicColors();
1433 }
1434
Huihong Luo50a2f362018-08-11 09:27:57 -07001435 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001436
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001437 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001438 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001439 mTimeCheckThread = nullptr;
1440 }
1441
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001442 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001443 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001444 }
1445
Huihong Luo50a2f362018-08-11 09:27:57 -07001446 releaseAnimation(mAnimation);
1447 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001448
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001449 return false;
1450}
1451
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001452bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1453 const int fadedFramesCount,
1454 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001455 // 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 +01001456 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1457 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001458}
1459
Lucas Dupin8eedc022021-07-29 21:49:07 +00001460// Linear mapping from range <a1, a2> to range <b1, b2>
1461float mapLinear(float x, float a1, float a2, float b1, float b2) {
1462 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1463}
1464
1465void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1466 // Map coordinates from screen space to world space.
1467 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1468 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1469 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1470 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1471 // Update quad vertex positions.
1472 quadPositions[0] = x0;
1473 quadPositions[1] = y0;
1474 quadPositions[2] = x1;
1475 quadPositions[3] = y0;
1476 quadPositions[4] = x1;
1477 quadPositions[5] = y1;
1478 quadPositions[6] = x1;
1479 quadPositions[7] = y1;
1480 quadPositions[8] = x0;
1481 quadPositions[9] = y1;
1482 quadPositions[10] = x0;
1483 quadPositions[11] = y0;
1484 glDrawArrays(GL_TRIANGLES, 0,
1485 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1486}
1487
Shan Huang7fee3522021-08-18 00:56:08 +00001488void BootAnimation::initDynamicColors() {
1489 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
Lucas Dupincd256842022-03-29 15:46:36 -07001490 const auto syspropName = "persist.bootanim.color" + std::to_string(i + 1);
1491 const auto syspropValue = android::base::GetProperty(syspropName, "");
1492 if (syspropValue != "") {
1493 SLOGI("Loaded dynamic color: %s -> %s", syspropName.c_str(), syspropValue.c_str());
1494 mDynamicColorsApplied = true;
1495 }
1496 parseColorDecimalString(syspropValue,
Shan Huang7fee3522021-08-18 00:56:08 +00001497 mAnimation->endColors[i], mAnimation->startColors[i]);
1498 }
1499 glUseProgram(mImageShader);
Lucas Dupincd256842022-03-29 15:46:36 -07001500 SLOGI("Dynamically coloring boot animation. Sysprops loaded? %i", mDynamicColorsApplied);
Shan Huang7fee3522021-08-18 00:56:08 +00001501 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1502 float *startColor = mAnimation->startColors[i];
1503 float *endColor = mAnimation->endColors[i];
Andrew Zengf9f58222022-11-08 11:10:48 -08001504 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001505 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001506 startColor[0], startColor[1], startColor[2]);
1507 glUniform3f(glGetUniformLocation(mImageShader,
Shan Huang7fee3522021-08-18 00:56:08 +00001508 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
Andrew Zengf9f58222022-11-08 11:10:48 -08001509 endColor[0], endColor[1], endColor[2]);
Shan Huang7fee3522021-08-18 00:56:08 +00001510 }
1511 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1512}
1513
Marin Shalamanov9070c052020-05-18 19:05:17 +02001514bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001515 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001516 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001517
Wei Wang159a4102018-10-23 23:15:58 -07001518 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001519 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001520
1521 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001522 int lastDisplayedProgress = 0;
Lucas Dupinbfd18122022-04-25 11:26:08 -07001523 int colorTransitionStart = animation.colorTransitionStart;
1524 int colorTransitionEnd = animation.colorTransitionEnd;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001525 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001526 const Animation::Part& part(animation.parts[i]);
1527 const size_t fcount = part.frames.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001528
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001529 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001530 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001531 playAnimation(*part.animation);
1532 if (exitPending())
1533 break;
1534 continue; //to next part
1535 }
1536
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001537 // process the part not only while the count allows but also if already fading
1538 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001539 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001540
Lucas Dupinbfd18122022-04-25 11:26:08 -07001541 // It's possible that the sysprops were not loaded yet at this boot phase.
1542 // If that's the case, then we should keep trying until they are available.
1543 if (animation.dynamicColoringEnabled && !mDynamicColorsApplied
1544 && (part.useDynamicColoring || part.postDynamicColoring)) {
1545 SLOGD("Trying to load dynamic color sysprops.");
1546 initDynamicColors();
1547 if (mDynamicColorsApplied) {
1548 // Sysprops were loaded. Next step is to adjust the animation if we loaded
1549 // the colors after the animation should have started.
1550 const int transitionLength = colorTransitionEnd - colorTransitionStart;
1551 if (part.postDynamicColoring) {
1552 colorTransitionStart = 0;
1553 colorTransitionEnd = fmin(transitionLength, fcount - 1);
1554 }
1555 }
1556 }
1557
Ed Coyne7464ac92017-06-08 12:26:48 -07001558 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001559
Jesse Hall083b84c2014-09-22 10:51:09 -07001560 glClearColor(
1561 part.backgroundColor[0],
1562 part.backgroundColor[1],
1563 part.backgroundColor[2],
1564 1.0f);
1565
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001566 ALOGD("Playing files = %s/%s, Requested repeat = %d, playUntilComplete = %s",
1567 animation.fileName.string(), part.path.string(), part.count,
1568 part.playUntilComplete ? "true" : "false");
1569
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001570 // For the last animation, if we have progress indicator from
1571 // the system, display it.
1572 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1573 bool displayProgress = animation.progressEnabled &&
1574 (i == (pcount -1)) && currentProgress != 0;
1575
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001576 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001577 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001578
Shan Huang2b31a362021-08-16 16:45:39 +00001579 // Color progress is
Shan Huang488ff742021-08-25 20:10:46 +00001580 // - the animation progress, normalized from
1581 // [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1582 // part.
Shan Huang2b31a362021-08-16 16:45:39 +00001583 // - 0 for parts that come before,
1584 // - 1 for parts that come after.
1585 float colorProgress = part.useDynamicColoring
Shan Huang488ff742021-08-25 20:10:46 +00001586 ? fmin(fmax(
Lucas Dupinbfd18122022-04-25 11:26:08 -07001587 ((float)j - colorTransitionStart) /
1588 fmax(colorTransitionEnd - colorTransitionStart, 1.0f), 0.0f), 1.0f)
Shan Huang2b31a362021-08-16 16:45:39 +00001589 : (part.postDynamicColoring ? 1 : 0);
1590
Marin Shalamanov9070c052020-05-18 19:05:17 +02001591 processDisplayEvents();
1592
joenchen85b339f2022-04-11 23:58:34 +08001593 const double ratio_w = static_cast<double>(mWidth) / mInitWidth;
1594 const double ratio_h = static_cast<double>(mHeight) / mInitHeight;
1595 const int animationX = (mWidth - animation.width * ratio_w) / 2;
1596 const int animationY = (mHeight - animation.height * ratio_h) / 2;
Marin Shalamanov9070c052020-05-18 19:05:17 +02001597
Mathias Agopiana8826d62009-10-01 03:10:14 -07001598 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001599 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001600
1601 if (r > 0) {
1602 glBindTexture(GL_TEXTURE_2D, frame.tid);
1603 } else {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001604 glGenTextures(1, &frame.tid);
1605 glBindTexture(GL_TEXTURE_2D, frame.tid);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001606 int w, h;
Shan Huang2b31a362021-08-16 16:45:39 +00001607 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1608 // of transparent pixels are preserved.
1609 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001610 }
1611
joenchen85b339f2022-04-11 23:58:34 +08001612 const int trimWidth = frame.trimWidth * ratio_w;
1613 const int trimHeight = frame.trimHeight * ratio_h;
1614 const int trimX = frame.trimX * ratio_w;
1615 const int trimY = frame.trimY * ratio_h;
1616 const int xc = animationX + trimX;
1617 const int yc = animationY + trimY;
Shan Huang2b31a362021-08-16 16:45:39 +00001618 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001619 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1620 // which is equivalent to mHeight - (yc + frame.trimHeight)
joenchen85b339f2022-04-11 23:58:34 +08001621 const int frameDrawY = mHeight - (yc + trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001622
Lucas Dupin8eedc022021-07-29 21:49:07 +00001623 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001624 // if the part hasn't been stopped yet then continue fading if necessary
1625 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001626 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001627 if (fadedFramesCount >= part.framesToFadeCount) {
1628 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1629 }
1630 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001631 glUseProgram(mImageShader);
1632 glUniform1i(mImageTextureLocation, 0);
1633 glUniform1f(mImageFadeLocation, fade);
Shan Huang2b31a362021-08-16 16:45:39 +00001634 if (animation.dynamicColoringEnabled) {
1635 glUniform1f(mImageColorProgressLocation, colorProgress);
1636 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001637 glEnable(GL_BLEND);
joenchen85b339f2022-04-11 23:58:34 +08001638 drawTexturedQuad(xc, frameDrawY, trimWidth, trimHeight);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001639 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001640
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001641 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1642 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001643 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001644
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001645 if (displayProgress) {
1646 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1647 // In case the new progress jumped suddenly, still show an
1648 // increment of 1.
1649 if (lastDisplayedProgress != 100) {
1650 // Artificially sleep 1/10th a second to slow down the animation.
1651 usleep(100000);
1652 if (lastDisplayedProgress < newProgress) {
1653 lastDisplayedProgress++;
1654 }
1655 }
1656 // Put the progress percentage right below the animation.
1657 int posY = animation.height / 3;
1658 int posX = TEXT_CENTER_VALUE;
1659 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1660 }
1661
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001662 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001663
Mathias Agopiana8826d62009-10-01 03:10:14 -07001664 eglSwapBuffers(mDisplay, mSurface);
1665
1666 nsecs_t now = systemTime();
1667 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001668 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001669 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001670
1671 if (delay > 0) {
1672 struct timespec spec;
1673 spec.tv_sec = (now + delay) / 1000000000;
1674 spec.tv_nsec = (now + delay) % 1000000000;
1675 int err;
1676 do {
Yi Kong911ac232019-03-24 01:49:02 -07001677 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Keith Mok0f2e6682021-11-15 05:50:32 +00001678 } while (err == EINTR);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001679 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001680
1681 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001682 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001683
niuwenchao9cd6ac82022-12-23 17:34:22 +08001684 int pauseDuration = part.pause * ns2us(frameDuration);
1685 while(pauseDuration > 0 && !exitPending()){
1686 if (pauseDuration > MAX_CHECK_EXIT_INTERVAL_US) {
1687 usleep(MAX_CHECK_EXIT_INTERVAL_US);
1688 pauseDuration -= MAX_CHECK_EXIT_INTERVAL_US;
1689 } else {
1690 usleep(pauseDuration);
1691 break;
1692 }
1693 checkExit();
1694 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001695
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001696 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1697 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001698 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1699 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1700 continue;
1701 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001702 break; // exit the infinite non-fading part when it has been played at least once
1703 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001704 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001705 }
1706
1707 // Free textures created for looping parts now that the animation is done.
1708 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001709 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001710 const size_t fcount = part.frames.size();
1711 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001712 const Animation::Frame& frame(part.frames[j]);
1713 glDeleteTextures(1, &frame.tid);
1714 }
1715 }
1716 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001717
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001718 ALOGD("%sAnimationShownTiming End time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1719 elapsedRealtime());
1720
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001721 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001722}
1723
Marin Shalamanov9070c052020-05-18 19:05:17 +02001724void BootAnimation::processDisplayEvents() {
1725 // This will poll mDisplayEventReceiver and if there are new events it'll call
1726 // displayEventCallback synchronously.
1727 mLooper->pollOnce(0);
1728}
1729
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001730void BootAnimation::handleViewport(nsecs_t timestep) {
1731 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1732 return;
1733 }
1734 if (mTargetInset < 0) {
1735 // Poll the amount for the top display inset. This will return -1 until persistent properties
1736 // have been loaded.
1737 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1738 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1739 }
1740 if (mTargetInset <= 0) {
1741 return;
1742 }
1743
1744 if (mCurrentInset < mTargetInset) {
1745 // After the device boots, the inset will effectively be cropped away. We animate this here.
1746 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1747 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1748
1749 SurfaceComposerClient::Transaction()
1750 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1751 .apply();
1752 } else {
1753 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1754 // later. This changes the coordinate system, and means we must move the surface up by
1755 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001756 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1757 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1758
1759 SurfaceComposerClient::Transaction t;
1760 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1761 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001762 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001763 t.apply();
1764
1765 mTargetInset = mCurrentInset = 0;
1766 }
1767
1768 int delta = timestep * mTargetInset / ms2ns(200);
1769 mCurrentInset += delta;
1770}
1771
Marin Shalamanov9070c052020-05-18 19:05:17 +02001772void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001773 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1774 e = animation->parts.end(); it != e; ++it) {
1775 if (it->animation)
1776 releaseAnimation(it->animation);
1777 }
1778 if (animation->zip)
1779 delete animation->zip;
1780 delete animation;
1781}
1782
Marin Shalamanov9070c052020-05-18 19:05:17 +02001783BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001784 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001785 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001786 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001787 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001788 }
1789 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001790 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001791 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001792 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001793 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001794 }
1795
Yoshiaki Maruoka9ef19b82017-10-25 13:55:49 +09001796 ALOGD("%s is loaded successfully", fn.string());
1797
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001798 Animation *animation = new Animation;
1799 animation->fileName = fn;
1800 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001801 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001802 mLoadedFiles.add(animation->fileName);
1803
1804 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001805 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001806 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001807 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001808 }
1809
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001810 mLoadedFiles.remove(fn);
1811 return animation;
1812}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001813
1814bool BootAnimation::updateIsTimeAccurate() {
1815 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1816 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1817
1818 if (mTimeIsAccurate) {
1819 return true;
1820 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001821 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001822 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001823
1824 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1825 mTimeFormat12Hour = true;
1826 }
1827
Damien Bargiacchi97480862016-03-29 14:55:55 -07001828 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1829 mTimeIsAccurate = true;
1830 return true;
1831 }
1832
1833 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001834 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001835 long long lastChangedTime = 0;
1836 fscanf(file, "%lld", &lastChangedTime);
1837 fclose(file);
1838 if (lastChangedTime > 0) {
1839 struct timespec now;
1840 clock_gettime(CLOCK_REALTIME, &now);
1841 // Match the Java timestamp format
1842 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001843 if (ACCURATE_TIME_EPOCH < rtcNow
1844 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1845 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001846 mTimeIsAccurate = true;
1847 }
1848 }
1849 }
1850
1851 return mTimeIsAccurate;
1852}
1853
1854BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
Josh Yangf95b2002021-12-23 14:32:28 -08001855 mInotifyFd(-1), mBootAnimWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001856
1857BootAnimation::TimeCheckThread::~TimeCheckThread() {
1858 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1859 close(mInotifyFd);
1860}
1861
1862bool BootAnimation::TimeCheckThread::threadLoop() {
1863 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1864 && mBootAnimation->mClockEnabled;
1865 if (!shouldLoop) {
1866 close(mInotifyFd);
1867 mInotifyFd = -1;
1868 }
1869 return shouldLoop;
1870}
1871
1872bool BootAnimation::TimeCheckThread::doThreadLoop() {
1873 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1874
1875 // Poll instead of doing a blocking read so the Thread can exit if requested.
1876 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1877 ssize_t pollResult = poll(&pfd, 1, 1000);
1878
1879 if (pollResult == 0) {
1880 return true;
1881 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001882 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001883 return false;
1884 }
1885
1886 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1887 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1888 if (length == 0) {
1889 return true;
1890 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001891 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001892 return false;
1893 }
1894
1895 const struct inotify_event *event;
1896 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1897 event = (const struct inotify_event *) ptr;
Josh Yangf95b2002021-12-23 14:32:28 -08001898 if (event->wd == mBootAnimWd && strcmp(BOOTANIM_TIME_DIR_NAME, event->name) == 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001899 addTimeDirWatch();
1900 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1901 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1902 return !mBootAnimation->updateIsTimeAccurate();
1903 }
1904 }
1905
1906 return true;
1907}
1908
1909void BootAnimation::TimeCheckThread::addTimeDirWatch() {
Josh Yangf95b2002021-12-23 14:32:28 -08001910 mTimeWd = inotify_add_watch(mInotifyFd, BOOTANIM_TIME_DIR_PATH,
Damien Bargiacchi97480862016-03-29 14:55:55 -07001911 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1912 if (mTimeWd > 0) {
1913 // No need to watch for the time directory to be created if it already exists
Josh Yangf95b2002021-12-23 14:32:28 -08001914 inotify_rm_watch(mInotifyFd, mBootAnimWd);
1915 mBootAnimWd = -1;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001916 }
1917}
1918
1919status_t BootAnimation::TimeCheckThread::readyToRun() {
1920 mInotifyFd = inotify_init();
1921 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001922 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001923 return NO_INIT;
1924 }
1925
Josh Yangf95b2002021-12-23 14:32:28 -08001926 mBootAnimWd = inotify_add_watch(mInotifyFd, BOOTANIM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1927 if (mBootAnimWd < 0) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001928 close(mInotifyFd);
1929 mInotifyFd = -1;
Josh Yangf95b2002021-12-23 14:32:28 -08001930 SLOGE("Could not add watch for %s: %s", BOOTANIM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001931 return NO_INIT;
1932 }
1933
1934 addTimeDirWatch();
1935
1936 if (mBootAnimation->updateIsTimeAccurate()) {
1937 close(mInotifyFd);
1938 mInotifyFd = -1;
1939 return ALREADY_EXISTS;
1940 }
1941
1942 return NO_ERROR;
1943}
1944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945// ---------------------------------------------------------------------------
1946
Marin Shalamanov9070c052020-05-18 19:05:17 +02001947} // namespace android