blob: fa94e6a4ace66178896a0d7c7dc3ca59708a8e1b [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 Dupindd7ed602021-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
Damien Bargiacchi97480862016-03-29 14:55:55 -070084static const char SYSTEM_DATA_DIR_PATH[] = "/data/system";
85static const char SYSTEM_TIME_DIR_NAME[] = "time";
86static const char SYSTEM_TIME_DIR_PATH[] = "/data/system/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";
92static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/system/time/last_time_change";
93static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
94static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/system/time/time_is_accurate";
Damien Bargiacchi9071db12016-10-28 17:38:22 -070095static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/system/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";
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +0900108static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700109static constexpr size_t TEXT_POS_LEN_MAX = 16;
Shan Huang89965002021-08-16 16:45:39 +0000110static const int DYNAMIC_COLOR_COUNT = 4;
Lucas Dupindd7ed602021-07-29 21:49:07 +0000111static const char U_TEXTURE[] = "uTexture";
112static const char U_FADE[] = "uFade";
113static const char U_CROP_AREA[] = "uCropArea";
Shan Huang89965002021-08-16 16:45:39 +0000114static const char U_START_COLOR_PREFIX[] = "uStartColor";
115static const char U_END_COLOR_PREFIX[] = "uEndColor";
116static const char U_COLOR_PROGRESS[] = "uColorProgress";
Lucas Dupindd7ed602021-07-29 21:49:07 +0000117static const char A_UV[] = "aUv";
118static const char A_POSITION[] = "aPosition";
119static const char VERTEX_SHADER_SOURCE[] = R"(
120 precision mediump float;
121 attribute vec4 aPosition;
122 attribute highp vec2 aUv;
123 varying highp vec2 vUv;
124 void main() {
125 gl_Position = aPosition;
126 vUv = aUv;
127 })";
Shan Huang89965002021-08-16 16:45:39 +0000128static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
129 precision mediump float;
130 uniform sampler2D uTexture;
131 uniform float uFade;
132 uniform float uColorProgress;
133 uniform vec4 uStartColor0;
134 uniform vec4 uStartColor1;
135 uniform vec4 uStartColor2;
136 uniform vec4 uStartColor3;
137 uniform vec4 uEndColor0;
138 uniform vec4 uEndColor1;
139 uniform vec4 uEndColor2;
140 uniform vec4 uEndColor3;
141 varying highp vec2 vUv;
142 void main() {
143 vec4 mask = texture2D(uTexture, vUv);
144 vec4 color = mask.r * mix(uStartColor0, uEndColor0, uColorProgress)
145 + mask.g * mix(uStartColor1, uEndColor1, uColorProgress)
146 + mask.b * mix(uStartColor2, uEndColor2, uColorProgress)
147 + mask.a * mix(uStartColor3, uEndColor3, uColorProgress);
148 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
149 })";
Lucas Dupindd7ed602021-07-29 21:49:07 +0000150static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
151 precision mediump float;
152 uniform sampler2D uTexture;
153 uniform float uFade;
154 varying highp vec2 vUv;
155 void main() {
156 vec4 color = texture2D(uTexture, vUv);
Shan Huang89965002021-08-16 16:45:39 +0000157 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupindd7ed602021-07-29 21:49:07 +0000158 })";
159static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
160 precision mediump float;
161 uniform sampler2D uTexture;
162 uniform vec4 uCropArea;
163 varying highp vec2 vUv;
164 void main() {
165 vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
166 mix(uCropArea.y, uCropArea.w, vUv.y));
167 gl_FragColor = texture2D(uTexture, uv);
168 })";
169
170static GLfloat quadPositions[] = {
171 -0.5f, -0.5f,
172 +0.5f, -0.5f,
173 +0.5f, +0.5f,
174 +0.5f, +0.5f,
175 -0.5f, +0.5f,
176 -0.5f, -0.5f
177};
178static GLfloat quadUVs[] = {
179 0.0f, 1.0f,
180 1.0f, 1.0f,
181 1.0f, 0.0f,
182 1.0f, 0.0f,
183 0.0f, 0.0f,
184 0.0f, 1.0f
185};
Narayan Kamathafd31e02013-12-03 13:16:03 +0000186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187// ---------------------------------------------------------------------------
188
Ed Coyne7464ac92017-06-08 12:26:48 -0700189BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200190 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700191 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700192 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400193
Keun-young Parkb5938422017-03-23 13:46:24 -0700194 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
195 if (powerCtl.empty()) {
196 mShuttingDown = false;
197 } else {
198 mShuttingDown = true;
199 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700200 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
201 elapsedRealtime());
202}
203
204BootAnimation::~BootAnimation() {
205 if (mAnimation != nullptr) {
206 releaseAnimation(mAnimation);
207 mAnimation = nullptr;
208 }
209 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
210 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211}
212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700214 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700215 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700216 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700217 // Load the animation content -- this can be slow (eg 200ms)
218 // called before waitForSurfaceFlinger() in main() to avoid wait
219 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
220 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
221 preloadAnimation();
222 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
223 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
Mathias Agopianbc726112009-09-23 15:44:05 -0700224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225}
226
Mathias Agopianbc726112009-09-23 15:44:05 -0700227sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 return mSession;
229}
230
Marin Shalamanov9070c052020-05-18 19:05:17 +0200231void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700232 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700233 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700234
235 // calling requestExit() is not enough here because the Surface code
236 // might be blocked on a condition variable that will never be updated.
237 kill( getpid(), SIGKILL );
238 requestExit();
239}
240
Shan Huang89965002021-08-16 16:45:39 +0000241static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
242 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400243 AImageDecoder* decoder = nullptr;
244 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
245 if (!decoder) {
246 return nullptr;
247 }
248
249 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
250 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
251 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
252 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
253 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
254 outInfo->flags = 0;
255
Shan Huang89965002021-08-16 16:45:39 +0000256 if (!premultiplyAlpha) {
257 AImageDecoder_setUnpremultipliedRequired(decoder, true);
258 }
259
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400260 const size_t size = outInfo->stride * outInfo->height;
261 void* pixels = malloc(size);
262 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
263 AImageDecoder_delete(decoder);
264
265 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
266 free(pixels);
267 return nullptr;
268 }
269 return pixels;
270}
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
Shan Huang89965002021-08-16 16:45:39 +0000273 const char* name, bool premultiplyAlpha) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700275 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400277
278 AndroidBitmapInfo bitmapInfo;
Shan Huang89965002021-08-16 16:45:39 +0000279 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
280 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400281 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 asset->close();
284 delete asset;
285
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400286 if (!pixels) {
287 return NO_INIT;
288 }
289
290 const int w = bitmapInfo.width;
291 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 texture->w = w;
294 texture->h = h;
295
296 glGenTextures(1, &texture->name);
297 glBindTexture(GL_TEXTURE_2D, texture->name);
298
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400299 switch (bitmapInfo.format) {
300 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400302 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400304 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400306 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400308 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400310 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400312 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400314 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 break;
316 default:
317 break;
318 }
319
Lucas Dupindd7ed602021-07-29 21:49:07 +0000320 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
321 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
322 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
323 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 return NO_ERROR;
326}
327
Shan Huang89965002021-08-16 16:45:39 +0000328status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
329 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400330 AndroidBitmapInfo bitmapInfo;
Shan Huang89965002021-08-16 16:45:39 +0000331 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
332 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400333 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700334
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200335 // FileMap memory is never released until application exit.
336 // Release it now as the texture is already loaded and the memory used for
337 // the packed resource can be released.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700338 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200339
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400340 if (!pixels) {
341 return NO_INIT;
342 }
343
344 const int w = bitmapInfo.width;
345 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700346
Mathias Agopiana8826d62009-10-01 03:10:14 -0700347 int tw = 1 << (31 - __builtin_clz(w));
348 int th = 1 << (31 - __builtin_clz(h));
349 if (tw < w) tw <<= 1;
350 if (th < h) th <<= 1;
351
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400352 switch (bitmapInfo.format) {
353 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530354 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700355 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700356 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700357 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400358 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700359 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530360 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400361 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700362 }
363 break;
364
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400365 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530366 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700367 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700368 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700369 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400370 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700371 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530372 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400373 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700374 }
375 break;
376 default:
377 break;
378 }
379
Lucas Dupindd7ed602021-07-29 21:49:07 +0000380 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
381 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
382 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
383 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700384
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700385 *width = w;
386 *height = h;
387
Mathias Agopiana8826d62009-10-01 03:10:14 -0700388 return NO_ERROR;
389}
390
Marin Shalamanov9070c052020-05-18 19:05:17 +0200391class BootAnimation::DisplayEventCallback : public LooperCallback {
392 BootAnimation* mBootAnimation;
393
394public:
395 DisplayEventCallback(BootAnimation* bootAnimation) {
396 mBootAnimation = bootAnimation;
397 }
398
399 int handleEvent(int /* fd */, int events, void* /* data */) {
400 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
401 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
402 events);
403 return 0; // remove the callback
404 }
405
406 if (!(events & Looper::EVENT_INPUT)) {
407 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
408 return 1; // keep the callback
409 }
410
411 constexpr int kBufferSize = 100;
412 DisplayEventReceiver::Event buffer[kBufferSize];
413 ssize_t numEvents;
414 do {
415 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
416 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
417 const auto& event = buffer[i];
418 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
419 SLOGV("Hotplug received");
420
421 if (!event.hotplug.connected) {
422 // ignore hotplug disconnect
423 continue;
424 }
425 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
426 event.header.displayId);
427
428 if (token != mBootAnimation->mDisplayToken) {
429 // ignore hotplug of a secondary display
430 continue;
431 }
432
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100433 DisplayMode displayMode;
434 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
435 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200436 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100437 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200438 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100439 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
440 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200441 }
442 }
443 } while (numEvents > 0);
444
445 return 1; // keep the callback
446 }
447};
448
449EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
450 const EGLint attribs[] = {
451 EGL_RED_SIZE, 8,
452 EGL_GREEN_SIZE, 8,
453 EGL_BLUE_SIZE, 8,
454 EGL_DEPTH_SIZE, 0,
455 EGL_NONE
456 };
457 EGLint numConfigs;
458 EGLConfig config;
459 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
460 return config;
461}
462
Marin Shalamanov047802d2020-05-19 23:55:12 +0200463ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
464 ui::Size limited(width, height);
465 bool wasLimited = false;
466 const float aspectRatio = float(width) / float(height);
467 if (mMaxWidth != 0 && width > mMaxWidth) {
468 limited.height = mMaxWidth / aspectRatio;
469 limited.width = mMaxWidth;
470 wasLimited = true;
471 }
472 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
473 limited.height = mMaxHeight;
474 limited.width = mMaxHeight * aspectRatio;
475 wasLimited = true;
476 }
477 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
478 limited.width, limited.height, width, height);
479 return limited;
480}
481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482status_t BootAnimation::readyToRun() {
483 mAssets.addDefaultAssets();
484
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800485 mDisplayToken = SurfaceComposerClient::getInternalDisplayToken();
486 if (mDisplayToken == nullptr)
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800487 return NAME_NOT_FOUND;
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800488
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100489 DisplayMode displayMode;
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800490 const status_t error =
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100491 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800492 if (error != NO_ERROR)
493 return error;
494
Marin Shalamanov047802d2020-05-19 23:55:12 +0200495 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
496 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100497 ui::Size resolution = displayMode.resolution;
Marin Shalamanov047802d2020-05-19 23:55:12 +0200498 resolution = limitSurfaceSize(resolution.width, resolution.height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 // create the native surface
Jeff Brown0b722fe2012-08-24 22:40:14 -0700500 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800501 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565);
Mathias Agopian439863f2011-06-28 19:09:31 -0700502
Robert Carre13b58e2017-08-31 14:50:44 -0700503 SurfaceComposerClient::Transaction t;
Huihong Luof97c9e22019-05-29 11:08:01 -0700504
505 // this guest property specifies multi-display IDs to show the boot animation
506 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800507 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200508 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700509 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800510 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700511 bool isValid = displayValue[0] != '\0';
512 if (isValid) {
513 char *p = displayValue;
514 while (*p) {
515 if (!isdigit(*p) && *p != ',') {
516 isValid = false;
517 break;
518 }
519 p ++;
520 }
521 if (!isValid)
Huihong Luod4a217e2020-01-16 15:56:33 -0800522 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700523 }
524 if (isValid) {
525 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200526 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700527 physicalDisplayIds.add(id);
528 if (stream.peek() == ',')
529 stream.ignore();
530 }
531
532 // In the case of multi-display, boot animation shows on the specified displays
533 // in addition to the primary display
534 auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
535 constexpr uint32_t LAYER_STACK = 0;
536 for (auto id : physicalDisplayIds) {
537 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
538 sp<IBinder> token = SurfaceComposerClient::getPhysicalDisplayToken(id);
539 if (token != nullptr)
540 t.setDisplayLayerStack(token, LAYER_STACK);
541 }
542 }
543 t.setLayerStack(control, LAYER_STACK);
544 }
545
Robert Carre13b58e2017-08-31 14:50:44 -0700546 t.setLayer(control, 0x40000000)
547 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548
Mathias Agopian17f638b2009-04-16 20:04:08 -0700549 sp<Surface> s = control->getSurface();
550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700553 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200554 EGLConfig config = getEglConfig(display);
555 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupindd7ed602021-07-29 21:49:07 +0000556 // Initialize egl context with client version number 2.0.
557 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
558 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200559 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 eglQuerySurface(display, surface, EGL_WIDTH, &w);
561 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700562
Mathias Agopianabac0102009-07-31 14:47:00 -0700563 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
564 return NO_INIT;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 mDisplay = display;
567 mContext = context;
568 mSurface = surface;
569 mWidth = w;
570 mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700571 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200573 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200575 projectSceneToWindow();
576
Marin Shalamanov9070c052020-05-18 19:05:17 +0200577 // Register a display event receiver
578 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
579 status_t status = mDisplayEventReceiver->initCheck();
580 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
581 status);
582 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
583 new DisplayEventCallback(this), nullptr);
584
Huihong Luo50a2f362018-08-11 09:27:57 -0700585 return NO_ERROR;
586}
587
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200588void BootAnimation::projectSceneToWindow() {
589 glViewport(0, 0, mWidth, mHeight);
590 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200591}
592
Marin Shalamanov9070c052020-05-18 19:05:17 +0200593void BootAnimation::resizeSurface(int newWidth, int newHeight) {
594 // We assume this function is called on the animation thread.
595 if (newWidth == mWidth && newHeight == mHeight) {
596 return;
597 }
598 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
599
600 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
601 eglDestroySurface(mDisplay, mSurface);
602
Marin Shalamanov047802d2020-05-19 23:55:12 +0200603 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
604 mWidth = limitedSize.width;
605 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200606
607 SurfaceComposerClient::Transaction t;
608 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
609 t.apply();
610
611 EGLConfig config = getEglConfig(mDisplay);
612 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
613 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
614 SLOGE("Can't make the new surface current. Error %d", eglGetError());
615 return;
616 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200617
618 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200619
620 mSurface = surface;
621}
622
Huihong Luo50a2f362018-08-11 09:27:57 -0700623bool BootAnimation::preloadAnimation() {
624 findBootAnimationFile();
625 if (!mZipFileName.isEmpty()) {
626 mAnimation = loadAnimation(mZipFileName);
627 return (mAnimation != nullptr);
628 }
629
630 return false;
631}
632
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000633bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
634 for (const std::string& f : files) {
635 if (access(f.c_str(), R_OK) == 0) {
636 mZipFileName = f.c_str();
637 return true;
638 }
639 }
640 return false;
641}
642
Huihong Luo50a2f362018-08-11 09:27:57 -0700643void BootAnimation::findBootAnimationFile() {
Elliott Hughesc367d482013-10-29 13:12:55 -0700644 // If the device has encryption turned on or is in process
Jason parksbd9a08d2011-01-31 15:04:34 -0600645 // of being encrypted we show the encrypted boot animation.
646 char decrypt[PROPERTY_VALUE_MAX];
647 property_get("vold.decrypt", decrypt, "");
648
Keun-young Parkb5938422017-03-23 13:46:24 -0700649 bool encryptedAnimation = atoi(decrypt) != 0 ||
650 !strcmp("trigger_restart_min_framework", decrypt);
Jason parksbd9a08d2011-01-31 15:04:34 -0600651
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900652 if (!mShuttingDown && encryptedAnimation) {
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000653 static const std::vector<std::string> encryptedBootFiles = {
654 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
655 };
656 if (findBootAnimationFileInternal(encryptedBootFiles)) {
657 return;
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900658 }
Jason parksbd9a08d2011-01-31 15:04:34 -0600659 }
Beverly34ffe252019-05-17 11:03:54 -0400660
661 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000662 static const std::vector<std::string> bootFiles = {
663 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
664 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
665 };
666 static const std::vector<std::string> shutdownFiles = {
667 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
668 };
669 static const std::vector<std::string> userspaceRebootFiles = {
670 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
671 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
672 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700673
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000674 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
675 findBootAnimationFileInternal(userspaceRebootFiles);
676 } else if (mShuttingDown) {
677 findBootAnimationFileInternal(shutdownFiles);
678 } else {
679 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681}
682
Lucas Dupindd7ed602021-07-29 21:49:07 +0000683GLuint compileShader(GLenum shaderType, const GLchar *source) {
684 GLuint shader = glCreateShader(shaderType);
685 glShaderSource(shader, 1, &source, 0);
686 glCompileShader(shader);
687 GLint isCompiled = 0;
688 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
689 if (isCompiled == GL_FALSE) {
690 SLOGE("Compile shader failed. Shader type: %d", shaderType);
691 return 0;
692 }
693 return shader;
694}
695
696GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
697 GLuint program = glCreateProgram();
698 glAttachShader(program, vertexShader);
699 glAttachShader(program, fragmentShader);
700 glLinkProgram(program);
701 GLint isLinked = 0;
702 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
703 if (isLinked == GL_FALSE) {
704 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
705 vertexShader, fragmentShader);
706 return 0;
707 }
708 return program;
709}
710
711void BootAnimation::initShaders() {
Shan Huang89965002021-08-16 16:45:39 +0000712 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupindd7ed602021-07-29 21:49:07 +0000713 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
714 GLuint imageFragmentShader =
Shan Huang89965002021-08-16 16:45:39 +0000715 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
716 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
717 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupindd7ed602021-07-29 21:49:07 +0000718 GLuint textFragmentShader =
719 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
720
721 // Initialize image shader.
722 mImageShader = linkShader(vertexShader, imageFragmentShader);
723 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
724 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
725 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
726 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
727 glEnableVertexAttribArray(positionLocation);
728 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
729 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
730 glEnableVertexAttribArray(uvLocation);
731
Shan Huang89965002021-08-16 16:45:39 +0000732 if (dynamicColoringEnabled) {
733 glUseProgram(mImageShader);
734 SLOGI("[BootAnimation] Dynamically coloring boot animation.");
735 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
736 float *startColor = mAnimation->startColors[i];
737 float *endColor = mAnimation->endColors[i];
738 glUniform4f(glGetUniformLocation(mImageShader,
739 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
740 startColor[0], startColor[1], startColor[2], 1 /* alpha */);
741 glUniform4f(glGetUniformLocation(mImageShader,
742 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
743 endColor[0], endColor[1], endColor[2], 1 /* alpha */);
744 }
745 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
746 }
747
Lucas Dupindd7ed602021-07-29 21:49:07 +0000748 // Initialize text shader.
749 mTextShader = linkShader(vertexShader, textFragmentShader);
750 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
751 uvLocation = glGetAttribLocation(mTextShader, A_UV);
752 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
753 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
754 glEnableVertexAttribArray(positionLocation);
755 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
756 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
757 glEnableVertexAttribArray(uvLocation);
758}
759
Marin Shalamanov9070c052020-05-18 19:05:17 +0200760bool BootAnimation::threadLoop() {
761 bool result;
Lucas Dupindd7ed602021-07-29 21:49:07 +0000762 initShaders();
763
Narayan Kamathafd31e02013-12-03 13:16:03 +0000764 // We have no bootanimation file, so we use the stock android logo
765 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700766 if (mZipFileName.isEmpty()) {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200767 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700768 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200769 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700770 }
771
Philip Junker60600562020-11-25 18:16:16 +0100772 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
774 eglDestroyContext(mDisplay, mContext);
775 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700776 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700777 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700778 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530779 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700780 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200781 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782}
783
Marin Shalamanov9070c052020-05-18 19:05:17 +0200784bool BootAnimation::android() {
Lucas Dupindd7ed602021-07-29 21:49:07 +0000785 glActiveTexture(GL_TEXTURE0);
786
Wei Wang159a4102018-10-23 23:15:58 -0700787 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700788 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700789 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
790 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791
Ed Coyne7464ac92017-06-08 12:26:48 -0700792 mCallbacks->init({});
793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700795 glDisable(GL_DITHER);
796 glDisable(GL_SCISSOR_TEST);
Mathias Agopian59f19e42011-05-06 19:22:12 -0700797 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 glClear(GL_COLOR_BUFFER_BIT);
799 eglSwapBuffers(mDisplay, mSurface);
800
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700801 // Blend state
802 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 const nsecs_t startTime = systemTime();
805 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200806 processDisplayEvents();
807 const GLint xc = (mWidth - mAndroid[0].w) / 2;
808 const GLint yc = (mHeight - mAndroid[0].h) / 2;
809 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
810 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
811 updateRect.height());
812
Mathias Agopian13796652009-03-24 22:49:21 -0700813 nsecs_t now = systemTime();
814 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700815 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
816 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
817 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818
Mathias Agopian81668642009-07-28 11:41:30 -0700819 glDisable(GL_SCISSOR_TEST);
820 glClear(GL_COLOR_BUFFER_BIT);
821
822 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupindd7ed602021-07-29 21:49:07 +0000825 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
826 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700828 glEnable(GL_BLEND);
829 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupindd7ed602021-07-29 21:49:07 +0000830 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831
Mathias Agopian627e7b52009-05-21 19:21:59 -0700832 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
833 if (res == EGL_FALSE)
834 break;
835
Mathias Agopian13796652009-03-24 22:49:21 -0700836 // 12fps: don't animate too fast to preserve CPU
837 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
838 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700839 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700840
841 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 } while (!exitPending());
843
844 glDeleteTextures(1, &mAndroid[0].name);
845 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 return false;
847}
848
Kevin Hesterd3782b22012-04-26 10:38:55 -0700849void BootAnimation::checkExit() {
850 // Allow surface flinger to gracefully request shutdown
851 char value[PROPERTY_VALUE_MAX];
852 property_get(EXIT_PROP_NAME, value, "0");
853 int exitnow = atoi(value);
854 if (exitnow) {
855 requestExit();
856 }
857}
858
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700859bool BootAnimation::validClock(const Animation::Part& part) {
860 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
861}
862
863bool parseTextCoord(const char* str, int* dest) {
864 if (strcmp("c", str) == 0) {
865 *dest = TEXT_CENTER_VALUE;
866 return true;
867 }
868
869 char* end;
870 int val = (int) strtol(str, &end, 0);
871 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
872 return false;
873 }
874 *dest = val;
875 return true;
876}
877
878// Parse two position coordinates. If only string is non-empty, treat it as the y value.
879void parsePosition(const char* str1, const char* str2, int* x, int* y) {
880 bool success = false;
881 if (strlen(str1) == 0) { // No values were specified
882 // success = false
883 } else if (strlen(str2) == 0) { // we have only one value
884 if (parseTextCoord(str1, y)) {
885 *x = TEXT_CENTER_VALUE;
886 success = true;
887 }
888 } else {
889 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
890 success = true;
891 }
892 }
893
894 if (!success) {
895 *x = TEXT_MISSING_VALUE;
896 *y = TEXT_MISSING_VALUE;
897 }
898}
899
Jesse Hall083b84c2014-09-22 10:51:09 -0700900// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
901// characters in str is a hex number in [0, 255], which are converted to
902// floating point values in the range [0.0, 1.0] and placed in the
903// corresponding elements of color.
904//
905// If the input string isn't valid, parseColor returns false and color is
906// left unchanged.
907static bool parseColor(const char str[7], float color[3]) {
908 float tmpColor[3];
909 for (int i = 0; i < 3; i++) {
910 int val = 0;
911 for (int j = 0; j < 2; j++) {
912 val *= 16;
913 char c = str[2*i + j];
914 if (c >= '0' && c <= '9') val += c - '0';
915 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
916 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
917 else return false;
918 }
919 tmpColor[i] = static_cast<float>(val) / 255.0f;
920 }
921 memcpy(color, tmpColor, sizeof(tmpColor));
922 return true;
923}
924
Shan Huang89965002021-08-16 16:45:39 +0000925// Parse a color represented as a signed decimal int string.
926// E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
927// If the input color string is empty, set color with values in defaultColor.
928static void parseColorDecimalString(const std::string& colorString,
929 float color[3], float defaultColor[3]) {
930 if (colorString == "") {
931 memcpy(color, defaultColor, sizeof(float) * 3);
932 return;
933 }
934 int colorInt = atoi(colorString.c_str());
935 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
936 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
937 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
938}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700939
Marin Shalamanov9070c052020-05-18 19:05:17 +0200940static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700941 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -0700942 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700943 if (!entry) {
944 return false;
945 }
946
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700947 FileMap* entryMap = zip->createEntryFileMap(entry);
948 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -0700949 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700950 if (!entryMap) {
951 return false;
952 }
953
954 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +0000955 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700956 return true;
957}
958
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700959// The font image should be a 96x2 array of character images. The
960// columns are the printable ASCII characters 0x20 - 0x7f. The
961// top row is regular text; the bottom row is bold.
962status_t BootAnimation::initFont(Font* font, const char* fallback) {
963 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800964
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700965 if (font->map != nullptr) {
966 glGenTextures(1, &font->texture.name);
967 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800968
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700969 status = initTexture(font->map, &font->texture.w, &font->texture.h);
970
Lucas Dupindd7ed602021-07-29 21:49:07 +0000971 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
972 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
973 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
974 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700975 } else if (fallback != nullptr) {
976 status = initTexture(&font->texture, mAssets, fallback);
977 } else {
978 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800979 }
980
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700981 if (status == NO_ERROR) {
982 font->char_width = font->texture.w / FONT_NUM_COLS;
983 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
984 }
985
986 return status;
987}
988
989void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
990 glEnable(GL_BLEND); // Allow us to draw on top of the animation
991 glBindTexture(GL_TEXTURE_2D, font.texture.name);
Lucas Dupindd7ed602021-07-29 21:49:07 +0000992 glUseProgram(mTextShader);
993 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700994
995 const int len = strlen(str);
996 const int strWidth = font.char_width * len;
997
998 if (*x == TEXT_CENTER_VALUE) {
999 *x = (mWidth - strWidth) / 2;
1000 } else if (*x < 0) {
1001 *x = mWidth + *x - strWidth;
1002 }
1003 if (*y == TEXT_CENTER_VALUE) {
1004 *y = (mHeight - font.char_height) / 2;
1005 } else if (*y < 0) {
1006 *y = mHeight + *y - font.char_height;
1007 }
1008
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001009 for (int i = 0; i < len; i++) {
1010 char c = str[i];
1011
1012 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1013 c = '?';
1014 }
1015
1016 // Crop the texture to only the pixels in the current glyph
1017 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1018 const int row = charPos / FONT_NUM_COLS;
1019 const int col = charPos % FONT_NUM_COLS;
Lucas Dupindd7ed602021-07-29 21:49:07 +00001020 // Bold fonts are expected in the second half of each row.
1021 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1022 float u0 = ((float)col) / FONT_NUM_COLS;
1023 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1024 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1025 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1026 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001027
1028 *x += font.char_width;
1029 }
1030
1031 glDisable(GL_BLEND); // Return to the animation's default behaviour
1032 glBindTexture(GL_TEXTURE_2D, 0);
1033}
1034
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001035// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001036void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001037 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1038 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001039 static constexpr int TIME_LENGTH = 6;
1040
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001041 time_t rawtime;
1042 time(&rawtime);
1043 struct tm* timeInfo = localtime(&rawtime);
1044
1045 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001046 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1047 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001048
1049 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001050 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001051 mClockEnabled = false;
1052 return;
1053 }
1054
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001055 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001056 int x = xPos;
1057 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001058 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001059}
1060
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001061void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1062 static constexpr int PERCENT_LENGTH = 5;
1063
1064 char percentBuff[PERCENT_LENGTH];
1065 // ';' has the ascii code just after ':', and the font resource contains '%'
1066 // for that ascii code.
1067 sprintf(percentBuff, "%d;", percent);
1068 int x = xPos;
1069 int y = yPos;
1070 drawText(percentBuff, font, false, &x, &y);
1071}
1072
Marin Shalamanov9070c052020-05-18 19:05:17 +02001073bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001074 String8 desString;
1075
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001076 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001077 return false;
1078 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001079 char const* s = desString.string();
Shan Huang89965002021-08-16 16:45:39 +00001080 std::string dynamicColoringPartName = "";
1081 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001082
Mathias Agopiana8826d62009-10-01 03:10:14 -07001083 // Parse the description file
1084 for (;;) {
1085 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001086 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001087 String8 line(s, endl - s);
1088 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001089 int fps = 0;
1090 int width = 0;
1091 int height = 0;
1092 int count = 0;
1093 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001094 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001095 int framesToFadeCount = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001096 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001097 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001098 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1099 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang89965002021-08-16 16:45:39 +00001100 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001101 char pathType;
Shan Huang89965002021-08-16 16:45:39 +00001102 // start colors default to black if unspecified
1103 char start_color_0[7] = "000000";
1104 char start_color_1[7] = "000000";
1105 char start_color_2[7] = "000000";
1106 char start_color_3[7] = "000000";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001107
1108 int nextReadPos;
1109
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001110 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1111 if (topLineNumbers == 3 || topLineNumbers == 4) {
1112 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001113 animation.width = width;
1114 animation.height = height;
1115 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001116 if (topLineNumbers == 4) {
1117 animation.progressEnabled = (progress != 0);
1118 } else {
1119 animation.progressEnabled = false;
1120 }
Shan Huang89965002021-08-16 16:45:39 +00001121 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s",
1122 dynamicColoringPartNameBuffer,
1123 start_color_0, start_color_1, start_color_2, start_color_3)) {
1124 animation.dynamicColoringEnabled = true;
1125 parseColor(start_color_0, animation.startColors[0]);
1126 parseColor(start_color_1, animation.startColors[1]);
1127 parseColor(start_color_2, animation.startColors[2]);
1128 parseColor(start_color_3, animation.startColors[3]);
1129 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001130 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1131 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1132 if (pathType == 'f') {
1133 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1134 clockPos2);
1135 } else {
1136 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1137 }
1138 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1139 // "clockPos1=%s, clockPos2=%s",
1140 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001141 Animation::Part part;
Shan Huang89965002021-08-16 16:45:39 +00001142 if (path == dynamicColoringPartName) {
1143 // Part is specified to use dynamic coloring.
1144 part.useDynamicColoring = true;
1145 part.postDynamicColoring = false;
1146 postDynamicColoring = true;
1147 } else {
1148 // Part does not use dynamic coloring.
1149 part.useDynamicColoring = false;
1150 part.postDynamicColoring = postDynamicColoring;
1151 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001152 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001153 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001154 part.count = count;
1155 part.pause = pause;
1156 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001157 part.audioData = nullptr;
1158 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001159 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001160 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001161 part.backgroundColor[0] = 0.0f;
1162 part.backgroundColor[1] = 0.0f;
1163 part.backgroundColor[2] = 0.0f;
1164 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001165 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001166 animation.parts.add(part);
1167 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001168 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001169 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001170 Animation::Part part;
1171 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001172 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001173 part.count = 1;
1174 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001175 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001176 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001177 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001178 animation.parts.add(part);
1179 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001180 s = ++endl;
1181 }
1182
Shan Huang89965002021-08-16 16:45:39 +00001183 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1184 parseColorDecimalString(
1185 android::base::GetProperty("persist.bootanim.color" + std::to_string(i + 1), ""),
1186 animation.endColors[i], animation.startColors[i]);
1187 }
1188
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001189 return true;
1190}
1191
Marin Shalamanov9070c052020-05-18 19:05:17 +02001192bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001193 // read all the data structures
1194 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001195 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001196 ZipFileRO* zip = animation.zip;
1197 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001198 return false;
1199 }
1200
1201 ZipEntryRO entry;
1202 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001203 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001204 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001205 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001206 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001207 continue;
1208 }
1209
1210 const String8 entryName(name);
1211 const String8 path(entryName.getPathDir());
1212 const String8 leaf(entryName.getPathLeaf());
1213 if (leaf.size() > 0) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001214 if (entryName == CLOCK_FONT_ZIP_NAME) {
1215 FileMap* map = zip->createEntryFileMap(entry);
1216 if (map) {
1217 animation.clockFont.map = map;
1218 }
1219 continue;
1220 }
1221
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001222 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1223 FileMap* map = zip->createEntryFileMap(entry);
1224 if (map) {
1225 animation.progressFont.map = map;
1226 }
1227 continue;
1228 }
1229
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001230 for (size_t j = 0; j < pcount; j++) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001231 if (path == animation.parts[j].path) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001232 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001233 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001234 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001235 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001236 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001237 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001238 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001239 if (leaf == "audio.wav") {
1240 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001241 part.audioData = (uint8_t *)map->getDataPtr();
1242 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001243 } else if (leaf == "trim.txt") {
1244 part.trimData.setTo((char const*)map->getDataPtr(),
1245 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001246 } else {
1247 Animation::Frame frame;
1248 frame.name = leaf;
1249 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001250 frame.trimWidth = animation.width;
1251 frame.trimHeight = animation.height;
1252 frame.trimX = 0;
1253 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001254 part.frames.add(frame);
1255 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001256 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001257 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001258 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001259 }
1260 }
1261 }
1262 }
1263 }
1264 }
1265
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001266 // If there is trimData present, override the positioning defaults.
1267 for (Animation::Part& part : animation.parts) {
1268 const char* trimDataStr = part.trimData.string();
1269 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1270 const char* endl = strstr(trimDataStr, "\n");
1271 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001272 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001273 break;
1274 }
1275 String8 line(trimDataStr, endl - trimDataStr);
1276 const char* lineStr = line.string();
1277 trimDataStr = ++endl;
1278 int width = 0, height = 0, x = 0, y = 0;
1279 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1280 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1281 frame.trimWidth = width;
1282 frame.trimHeight = height;
1283 frame.trimX = x;
1284 frame.trimY = y;
1285 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001286 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001287 break;
1288 }
1289 }
1290 }
1291
1292 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001293
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001294 return true;
1295}
1296
Marin Shalamanov9070c052020-05-18 19:05:17 +02001297bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001298 if (mAnimation == nullptr) {
1299 mAnimation = loadAnimation(mZipFileName);
1300 }
1301
1302 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001303 return false;
1304
Huihong Luo50a2f362018-08-11 09:27:57 -07001305 // mCallbacks->init() may get called recursively,
1306 // this loop is needed to get the same results
1307 for (const Animation::Part& part : mAnimation->parts) {
1308 if (part.animation != nullptr) {
1309 mCallbacks->init(part.animation->parts);
1310 }
1311 }
1312 mCallbacks->init(mAnimation->parts);
1313
Damien Bargiacchi97480862016-03-29 14:55:55 -07001314 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001315 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1316 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001317 anyPartHasClock = true;
1318 break;
1319 }
1320 }
1321 if (!anyPartHasClock) {
1322 mClockEnabled = false;
1323 }
1324
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301325 // Check if npot textures are supported
1326 mUseNpotTextures = false;
1327 String8 gl_extensions;
1328 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1329 if (!exts) {
1330 glGetError();
1331 } else {
1332 gl_extensions.setTo(exts);
1333 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1334 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1335 mUseNpotTextures = true;
1336 }
1337 }
1338
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001339 // Blend required to draw time on top of animation frames.
1340 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001341 glDisable(GL_DITHER);
1342 glDisable(GL_SCISSOR_TEST);
1343 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001344
Mathias Agopiana8826d62009-10-01 03:10:14 -07001345 glEnable(GL_TEXTURE_2D);
Lucas Dupindd7ed602021-07-29 21:49:07 +00001346 glBindTexture(GL_TEXTURE_2D, 0);
1347 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1348 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1349 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1350 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001351 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001352 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001353 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001354 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001355 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001356 }
1357
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001358 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1359
Damien Bargiacchi97480862016-03-29 14:55:55 -07001360 if (mClockEnabled && !updateIsTimeAccurate()) {
1361 mTimeCheckThread = new TimeCheckThread(this);
1362 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1363 }
1364
Huihong Luo50a2f362018-08-11 09:27:57 -07001365 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001366
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001367 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001368 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001369 mTimeCheckThread = nullptr;
1370 }
1371
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001372 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001373 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001374 }
1375
Huihong Luo50a2f362018-08-11 09:27:57 -07001376 releaseAnimation(mAnimation);
1377 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001378
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001379 return false;
1380}
1381
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001382bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1383 const int fadedFramesCount,
1384 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001385 // 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 +01001386 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1387 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001388}
1389
Lucas Dupindd7ed602021-07-29 21:49:07 +00001390// Linear mapping from range <a1, a2> to range <b1, b2>
1391float mapLinear(float x, float a1, float a2, float b1, float b2) {
1392 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1393}
1394
1395void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1396 // Map coordinates from screen space to world space.
1397 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1398 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1399 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1400 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1401 // Update quad vertex positions.
1402 quadPositions[0] = x0;
1403 quadPositions[1] = y0;
1404 quadPositions[2] = x1;
1405 quadPositions[3] = y0;
1406 quadPositions[4] = x1;
1407 quadPositions[5] = y1;
1408 quadPositions[6] = x1;
1409 quadPositions[7] = y1;
1410 quadPositions[8] = x0;
1411 quadPositions[9] = y1;
1412 quadPositions[10] = x0;
1413 quadPositions[11] = y0;
1414 glDrawArrays(GL_TRIANGLES, 0,
1415 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1416}
1417
Marin Shalamanov9070c052020-05-18 19:05:17 +02001418bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001419 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001420 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001421
Wei Wang159a4102018-10-23 23:15:58 -07001422 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001423 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001424
1425 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001426 int lastDisplayedProgress = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001427 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001428 const Animation::Part& part(animation.parts[i]);
1429 const size_t fcount = part.frames.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001430
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001431 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001432 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001433 playAnimation(*part.animation);
1434 if (exitPending())
1435 break;
1436 continue; //to next part
1437 }
1438
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001439 // process the part not only while the count allows but also if already fading
1440 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001441 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001442
Ed Coyne7464ac92017-06-08 12:26:48 -07001443 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001444
Jesse Hall083b84c2014-09-22 10:51:09 -07001445 glClearColor(
1446 part.backgroundColor[0],
1447 part.backgroundColor[1],
1448 part.backgroundColor[2],
1449 1.0f);
1450
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001451 // For the last animation, if we have progress indicator from
1452 // the system, display it.
1453 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1454 bool displayProgress = animation.progressEnabled &&
1455 (i == (pcount -1)) && currentProgress != 0;
1456
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001457 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001458 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001459
Shan Huang89965002021-08-16 16:45:39 +00001460 // Color progress is
1461 // - the normalized animation progress between [0, 1] for the dynamic coloring part,
1462 // - 0 for parts that come before,
1463 // - 1 for parts that come after.
1464 float colorProgress = part.useDynamicColoring
1465 ? (float)j / fcount
1466 : (part.postDynamicColoring ? 1 : 0);
1467
Marin Shalamanov9070c052020-05-18 19:05:17 +02001468 processDisplayEvents();
1469
1470 const int animationX = (mWidth - animation.width) / 2;
1471 const int animationY = (mHeight - animation.height) / 2;
1472
Mathias Agopiana8826d62009-10-01 03:10:14 -07001473 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001474 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001475
1476 if (r > 0) {
1477 glBindTexture(GL_TEXTURE_2D, frame.tid);
1478 } else {
Lucas Dupindd7ed602021-07-29 21:49:07 +00001479 glGenTextures(1, &frame.tid);
1480 glBindTexture(GL_TEXTURE_2D, frame.tid);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001481 int w, h;
Shan Huang89965002021-08-16 16:45:39 +00001482 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1483 // of transparent pixels are preserved.
1484 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001485 }
1486
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001487 const int xc = animationX + frame.trimX;
1488 const int yc = animationY + frame.trimY;
Shan Huang89965002021-08-16 16:45:39 +00001489 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001490 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1491 // which is equivalent to mHeight - (yc + frame.trimHeight)
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001492 const int frameDrawY = mHeight - (yc + frame.trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001493
Lucas Dupindd7ed602021-07-29 21:49:07 +00001494 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001495 // if the part hasn't been stopped yet then continue fading if necessary
1496 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupindd7ed602021-07-29 21:49:07 +00001497 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001498 if (fadedFramesCount >= part.framesToFadeCount) {
1499 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1500 }
1501 }
Lucas Dupindd7ed602021-07-29 21:49:07 +00001502 glUseProgram(mImageShader);
1503 glUniform1i(mImageTextureLocation, 0);
1504 glUniform1f(mImageFadeLocation, fade);
Shan Huang89965002021-08-16 16:45:39 +00001505 if (animation.dynamicColoringEnabled) {
1506 glUniform1f(mImageColorProgressLocation, colorProgress);
1507 }
Lucas Dupindd7ed602021-07-29 21:49:07 +00001508 glEnable(GL_BLEND);
1509 drawTexturedQuad(xc, frameDrawY, frame.trimWidth, frame.trimHeight);
1510 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001511
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001512 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1513 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001514 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001515
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001516 if (displayProgress) {
1517 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1518 // In case the new progress jumped suddenly, still show an
1519 // increment of 1.
1520 if (lastDisplayedProgress != 100) {
1521 // Artificially sleep 1/10th a second to slow down the animation.
1522 usleep(100000);
1523 if (lastDisplayedProgress < newProgress) {
1524 lastDisplayedProgress++;
1525 }
1526 }
1527 // Put the progress percentage right below the animation.
1528 int posY = animation.height / 3;
1529 int posX = TEXT_CENTER_VALUE;
1530 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1531 }
1532
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001533 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001534
Mathias Agopiana8826d62009-10-01 03:10:14 -07001535 eglSwapBuffers(mDisplay, mSurface);
1536
1537 nsecs_t now = systemTime();
1538 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001539 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001540 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001541
1542 if (delay > 0) {
1543 struct timespec spec;
1544 spec.tv_sec = (now + delay) / 1000000000;
1545 spec.tv_nsec = (now + delay) % 1000000000;
1546 int err;
1547 do {
Yi Kong911ac232019-03-24 01:49:02 -07001548 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001549 } while (err<0 && errno == EINTR);
1550 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001551
1552 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001553 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001554
Mathias Agopiana8826d62009-10-01 03:10:14 -07001555 usleep(part.pause * ns2us(frameDuration));
Kevin Hesterd3782b22012-04-26 10:38:55 -07001556
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001557 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1558 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001559 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1560 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1561 continue;
1562 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001563 break; // exit the infinite non-fading part when it has been played at least once
1564 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001565 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001566 }
1567
1568 // Free textures created for looping parts now that the animation is done.
1569 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001570 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001571 const size_t fcount = part.frames.size();
1572 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001573 const Animation::Frame& frame(part.frames[j]);
1574 glDeleteTextures(1, &frame.tid);
1575 }
1576 }
1577 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001578
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001579 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001580}
1581
Marin Shalamanov9070c052020-05-18 19:05:17 +02001582void BootAnimation::processDisplayEvents() {
1583 // This will poll mDisplayEventReceiver and if there are new events it'll call
1584 // displayEventCallback synchronously.
1585 mLooper->pollOnce(0);
1586}
1587
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001588void BootAnimation::handleViewport(nsecs_t timestep) {
1589 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1590 return;
1591 }
1592 if (mTargetInset < 0) {
1593 // Poll the amount for the top display inset. This will return -1 until persistent properties
1594 // have been loaded.
1595 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1596 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1597 }
1598 if (mTargetInset <= 0) {
1599 return;
1600 }
1601
1602 if (mCurrentInset < mTargetInset) {
1603 // After the device boots, the inset will effectively be cropped away. We animate this here.
1604 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1605 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1606
1607 SurfaceComposerClient::Transaction()
1608 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1609 .apply();
1610 } else {
1611 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1612 // later. This changes the coordinate system, and means we must move the surface up by
1613 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001614 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1615 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1616
1617 SurfaceComposerClient::Transaction t;
1618 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1619 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001620 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001621 t.apply();
1622
1623 mTargetInset = mCurrentInset = 0;
1624 }
1625
1626 int delta = timestep * mTargetInset / ms2ns(200);
1627 mCurrentInset += delta;
1628}
1629
Marin Shalamanov9070c052020-05-18 19:05:17 +02001630void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001631 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1632 e = animation->parts.end(); it != e; ++it) {
1633 if (it->animation)
1634 releaseAnimation(it->animation);
1635 }
1636 if (animation->zip)
1637 delete animation->zip;
1638 delete animation;
1639}
1640
Marin Shalamanov9070c052020-05-18 19:05:17 +02001641BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001642 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001643 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001644 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001645 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001646 }
1647 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001648 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001649 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001650 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001651 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001652 }
1653
1654 Animation *animation = new Animation;
1655 animation->fileName = fn;
1656 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001657 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001658 mLoadedFiles.add(animation->fileName);
1659
1660 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001661 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001662 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001663 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001664 }
1665
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001666 mLoadedFiles.remove(fn);
1667 return animation;
1668}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001669
1670bool BootAnimation::updateIsTimeAccurate() {
1671 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1672 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1673
1674 if (mTimeIsAccurate) {
1675 return true;
1676 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001677 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001678 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001679
1680 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1681 mTimeFormat12Hour = true;
1682 }
1683
Damien Bargiacchi97480862016-03-29 14:55:55 -07001684 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1685 mTimeIsAccurate = true;
1686 return true;
1687 }
1688
1689 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001690 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001691 long long lastChangedTime = 0;
1692 fscanf(file, "%lld", &lastChangedTime);
1693 fclose(file);
1694 if (lastChangedTime > 0) {
1695 struct timespec now;
1696 clock_gettime(CLOCK_REALTIME, &now);
1697 // Match the Java timestamp format
1698 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001699 if (ACCURATE_TIME_EPOCH < rtcNow
1700 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1701 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001702 mTimeIsAccurate = true;
1703 }
1704 }
1705 }
1706
1707 return mTimeIsAccurate;
1708}
1709
1710BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1711 mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1712
1713BootAnimation::TimeCheckThread::~TimeCheckThread() {
1714 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1715 close(mInotifyFd);
1716}
1717
1718bool BootAnimation::TimeCheckThread::threadLoop() {
1719 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1720 && mBootAnimation->mClockEnabled;
1721 if (!shouldLoop) {
1722 close(mInotifyFd);
1723 mInotifyFd = -1;
1724 }
1725 return shouldLoop;
1726}
1727
1728bool BootAnimation::TimeCheckThread::doThreadLoop() {
1729 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1730
1731 // Poll instead of doing a blocking read so the Thread can exit if requested.
1732 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1733 ssize_t pollResult = poll(&pfd, 1, 1000);
1734
1735 if (pollResult == 0) {
1736 return true;
1737 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001738 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001739 return false;
1740 }
1741
1742 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1743 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1744 if (length == 0) {
1745 return true;
1746 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001747 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001748 return false;
1749 }
1750
1751 const struct inotify_event *event;
1752 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1753 event = (const struct inotify_event *) ptr;
1754 if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
1755 addTimeDirWatch();
1756 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1757 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1758 return !mBootAnimation->updateIsTimeAccurate();
1759 }
1760 }
1761
1762 return true;
1763}
1764
1765void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1766 mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
1767 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1768 if (mTimeWd > 0) {
1769 // No need to watch for the time directory to be created if it already exists
1770 inotify_rm_watch(mInotifyFd, mSystemWd);
1771 mSystemWd = -1;
1772 }
1773}
1774
1775status_t BootAnimation::TimeCheckThread::readyToRun() {
1776 mInotifyFd = inotify_init();
1777 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001778 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001779 return NO_INIT;
1780 }
1781
1782 mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1783 if (mSystemWd < 0) {
1784 close(mInotifyFd);
1785 mInotifyFd = -1;
Dan Sandler562d46d2020-05-11 17:09:22 -04001786 SLOGE("Could not add watch for %s: %s", SYSTEM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001787 return NO_INIT;
1788 }
1789
1790 addTimeDirWatch();
1791
1792 if (mBootAnimation->updateIsTimeAccurate()) {
1793 close(mInotifyFd);
1794 mInotifyFd = -1;
1795 return ALREADY_EXISTS;
1796 }
1797
1798 return NO_ERROR;
1799}
1800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801// ---------------------------------------------------------------------------
1802
Marin Shalamanov9070c052020-05-18 19:05:17 +02001803} // namespace android