blob: 90a5d49bf56b0db27fc6ca062f13ec2e8a3af6d8 [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
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 Huang2b31a362021-08-16 16:45:39 +0000110static const int DYNAMIC_COLOR_COUNT = 4;
Lucas Dupin8eedc022021-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 Huang2b31a362021-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 Dupin8eedc022021-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 Huang2b31a362021-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 Dupin8eedc022021-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 Huang2b31a362021-08-16 16:45:39 +0000157 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupin8eedc022021-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 Huang2b31a362021-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 Huang2b31a362021-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 Huang2b31a362021-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 Huang2b31a362021-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 Dupin8eedc022021-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 Huang2b31a362021-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 Huang2b31a362021-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 Dupin8eedc022021-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
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700534 const auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
535 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700536 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700537 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
538 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
539 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700540 }
541 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700542 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700543 }
544
Robert Carre13b58e2017-08-31 14:50:44 -0700545 t.setLayer(control, 0x40000000)
546 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547
Mathias Agopian17f638b2009-04-16 20:04:08 -0700548 sp<Surface> s = control->getSurface();
549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700552 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200553 EGLConfig config = getEglConfig(display);
554 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000555 // Initialize egl context with client version number 2.0.
556 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
557 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200558 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 eglQuerySurface(display, surface, EGL_WIDTH, &w);
560 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700561
Mathias Agopianabac0102009-07-31 14:47:00 -0700562 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
563 return NO_INIT;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 mDisplay = display;
566 mContext = context;
567 mSurface = surface;
568 mWidth = w;
569 mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700570 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200572 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200574 projectSceneToWindow();
575
Marin Shalamanov9070c052020-05-18 19:05:17 +0200576 // Register a display event receiver
577 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
578 status_t status = mDisplayEventReceiver->initCheck();
579 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
580 status);
581 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
582 new DisplayEventCallback(this), nullptr);
583
Huihong Luo50a2f362018-08-11 09:27:57 -0700584 return NO_ERROR;
585}
586
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200587void BootAnimation::projectSceneToWindow() {
588 glViewport(0, 0, mWidth, mHeight);
589 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200590}
591
Marin Shalamanov9070c052020-05-18 19:05:17 +0200592void BootAnimation::resizeSurface(int newWidth, int newHeight) {
593 // We assume this function is called on the animation thread.
594 if (newWidth == mWidth && newHeight == mHeight) {
595 return;
596 }
597 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
598
599 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
600 eglDestroySurface(mDisplay, mSurface);
601
Marin Shalamanov047802d2020-05-19 23:55:12 +0200602 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
603 mWidth = limitedSize.width;
604 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200605
606 SurfaceComposerClient::Transaction t;
607 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
608 t.apply();
609
610 EGLConfig config = getEglConfig(mDisplay);
611 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
612 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
613 SLOGE("Can't make the new surface current. Error %d", eglGetError());
614 return;
615 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200616
617 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200618
619 mSurface = surface;
620}
621
Huihong Luo50a2f362018-08-11 09:27:57 -0700622bool BootAnimation::preloadAnimation() {
623 findBootAnimationFile();
624 if (!mZipFileName.isEmpty()) {
625 mAnimation = loadAnimation(mZipFileName);
626 return (mAnimation != nullptr);
627 }
628
629 return false;
630}
631
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000632bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
633 for (const std::string& f : files) {
634 if (access(f.c_str(), R_OK) == 0) {
635 mZipFileName = f.c_str();
636 return true;
637 }
638 }
639 return false;
640}
641
Huihong Luo50a2f362018-08-11 09:27:57 -0700642void BootAnimation::findBootAnimationFile() {
Elliott Hughesc367d482013-10-29 13:12:55 -0700643 // If the device has encryption turned on or is in process
Jason parksbd9a08d2011-01-31 15:04:34 -0600644 // of being encrypted we show the encrypted boot animation.
645 char decrypt[PROPERTY_VALUE_MAX];
646 property_get("vold.decrypt", decrypt, "");
647
Keun-young Parkb5938422017-03-23 13:46:24 -0700648 bool encryptedAnimation = atoi(decrypt) != 0 ||
649 !strcmp("trigger_restart_min_framework", decrypt);
Jason parksbd9a08d2011-01-31 15:04:34 -0600650
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900651 if (!mShuttingDown && encryptedAnimation) {
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000652 static const std::vector<std::string> encryptedBootFiles = {
653 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
654 };
655 if (findBootAnimationFileInternal(encryptedBootFiles)) {
656 return;
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900657 }
Jason parksbd9a08d2011-01-31 15:04:34 -0600658 }
Beverly34ffe252019-05-17 11:03:54 -0400659
660 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000661 static const std::vector<std::string> bootFiles = {
662 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
663 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
664 };
665 static const std::vector<std::string> shutdownFiles = {
666 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
667 };
668 static const std::vector<std::string> userspaceRebootFiles = {
669 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
670 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
671 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700672
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000673 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
674 findBootAnimationFileInternal(userspaceRebootFiles);
675 } else if (mShuttingDown) {
676 findBootAnimationFileInternal(shutdownFiles);
677 } else {
678 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680}
681
Lucas Dupin8eedc022021-07-29 21:49:07 +0000682GLuint compileShader(GLenum shaderType, const GLchar *source) {
683 GLuint shader = glCreateShader(shaderType);
684 glShaderSource(shader, 1, &source, 0);
685 glCompileShader(shader);
686 GLint isCompiled = 0;
687 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
688 if (isCompiled == GL_FALSE) {
689 SLOGE("Compile shader failed. Shader type: %d", shaderType);
690 return 0;
691 }
692 return shader;
693}
694
695GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
696 GLuint program = glCreateProgram();
697 glAttachShader(program, vertexShader);
698 glAttachShader(program, fragmentShader);
699 glLinkProgram(program);
700 GLint isLinked = 0;
701 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
702 if (isLinked == GL_FALSE) {
703 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
704 vertexShader, fragmentShader);
705 return 0;
706 }
707 return program;
708}
709
710void BootAnimation::initShaders() {
Shan Huang2b31a362021-08-16 16:45:39 +0000711 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000712 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
713 GLuint imageFragmentShader =
Shan Huang2b31a362021-08-16 16:45:39 +0000714 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
715 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
716 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000717 GLuint textFragmentShader =
718 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
719
720 // Initialize image shader.
721 mImageShader = linkShader(vertexShader, imageFragmentShader);
722 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
723 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
724 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
725 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
726 glEnableVertexAttribArray(positionLocation);
727 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
728 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
729 glEnableVertexAttribArray(uvLocation);
730
731 // Initialize text shader.
732 mTextShader = linkShader(vertexShader, textFragmentShader);
733 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
734 uvLocation = glGetAttribLocation(mTextShader, A_UV);
735 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
736 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
737 glEnableVertexAttribArray(positionLocation);
738 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
739 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
740 glEnableVertexAttribArray(uvLocation);
741}
742
Marin Shalamanov9070c052020-05-18 19:05:17 +0200743bool BootAnimation::threadLoop() {
744 bool result;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000745 initShaders();
746
Narayan Kamathafd31e02013-12-03 13:16:03 +0000747 // We have no bootanimation file, so we use the stock android logo
748 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700749 if (mZipFileName.isEmpty()) {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200750 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700751 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200752 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700753 }
754
Philip Junker60600562020-11-25 18:16:16 +0100755 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
757 eglDestroyContext(mDisplay, mContext);
758 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700759 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700760 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700761 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530762 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700763 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200764 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765}
766
Marin Shalamanov9070c052020-05-18 19:05:17 +0200767bool BootAnimation::android() {
Lucas Dupin8eedc022021-07-29 21:49:07 +0000768 glActiveTexture(GL_TEXTURE0);
769
Wei Wang159a4102018-10-23 23:15:58 -0700770 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700771 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700772 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
773 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774
Ed Coyne7464ac92017-06-08 12:26:48 -0700775 mCallbacks->init({});
776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700778 glDisable(GL_DITHER);
779 glDisable(GL_SCISSOR_TEST);
Mathias Agopian59f19e42011-05-06 19:22:12 -0700780 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 glClear(GL_COLOR_BUFFER_BIT);
782 eglSwapBuffers(mDisplay, mSurface);
783
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700784 // Blend state
785 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 const nsecs_t startTime = systemTime();
788 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200789 processDisplayEvents();
790 const GLint xc = (mWidth - mAndroid[0].w) / 2;
791 const GLint yc = (mHeight - mAndroid[0].h) / 2;
792 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
793 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
794 updateRect.height());
795
Mathias Agopian13796652009-03-24 22:49:21 -0700796 nsecs_t now = systemTime();
797 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700798 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
799 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
800 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801
Mathias Agopian81668642009-07-28 11:41:30 -0700802 glDisable(GL_SCISSOR_TEST);
803 glClear(GL_COLOR_BUFFER_BIT);
804
805 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000808 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
809 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700811 glEnable(GL_BLEND);
812 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000813 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814
Mathias Agopian627e7b52009-05-21 19:21:59 -0700815 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
816 if (res == EGL_FALSE)
817 break;
818
Mathias Agopian13796652009-03-24 22:49:21 -0700819 // 12fps: don't animate too fast to preserve CPU
820 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
821 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700822 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700823
824 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 } while (!exitPending());
826
827 glDeleteTextures(1, &mAndroid[0].name);
828 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 return false;
830}
831
Kevin Hesterd3782b22012-04-26 10:38:55 -0700832void BootAnimation::checkExit() {
833 // Allow surface flinger to gracefully request shutdown
834 char value[PROPERTY_VALUE_MAX];
835 property_get(EXIT_PROP_NAME, value, "0");
836 int exitnow = atoi(value);
837 if (exitnow) {
838 requestExit();
839 }
840}
841
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700842bool BootAnimation::validClock(const Animation::Part& part) {
843 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
844}
845
846bool parseTextCoord(const char* str, int* dest) {
847 if (strcmp("c", str) == 0) {
848 *dest = TEXT_CENTER_VALUE;
849 return true;
850 }
851
852 char* end;
853 int val = (int) strtol(str, &end, 0);
854 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
855 return false;
856 }
857 *dest = val;
858 return true;
859}
860
861// Parse two position coordinates. If only string is non-empty, treat it as the y value.
862void parsePosition(const char* str1, const char* str2, int* x, int* y) {
863 bool success = false;
864 if (strlen(str1) == 0) { // No values were specified
865 // success = false
866 } else if (strlen(str2) == 0) { // we have only one value
867 if (parseTextCoord(str1, y)) {
868 *x = TEXT_CENTER_VALUE;
869 success = true;
870 }
871 } else {
872 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
873 success = true;
874 }
875 }
876
877 if (!success) {
878 *x = TEXT_MISSING_VALUE;
879 *y = TEXT_MISSING_VALUE;
880 }
881}
882
Jesse Hall083b84c2014-09-22 10:51:09 -0700883// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
884// characters in str is a hex number in [0, 255], which are converted to
885// floating point values in the range [0.0, 1.0] and placed in the
886// corresponding elements of color.
887//
888// If the input string isn't valid, parseColor returns false and color is
889// left unchanged.
890static bool parseColor(const char str[7], float color[3]) {
891 float tmpColor[3];
892 for (int i = 0; i < 3; i++) {
893 int val = 0;
894 for (int j = 0; j < 2; j++) {
895 val *= 16;
896 char c = str[2*i + j];
897 if (c >= '0' && c <= '9') val += c - '0';
898 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
899 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
900 else return false;
901 }
902 tmpColor[i] = static_cast<float>(val) / 255.0f;
903 }
904 memcpy(color, tmpColor, sizeof(tmpColor));
905 return true;
906}
907
Shan Huang2b31a362021-08-16 16:45:39 +0000908// Parse a color represented as a signed decimal int string.
909// E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
910// If the input color string is empty, set color with values in defaultColor.
911static void parseColorDecimalString(const std::string& colorString,
912 float color[3], float defaultColor[3]) {
913 if (colorString == "") {
914 memcpy(color, defaultColor, sizeof(float) * 3);
915 return;
916 }
917 int colorInt = atoi(colorString.c_str());
918 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
919 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
920 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
921}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700922
Marin Shalamanov9070c052020-05-18 19:05:17 +0200923static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700924 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -0700925 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700926 if (!entry) {
927 return false;
928 }
929
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700930 FileMap* entryMap = zip->createEntryFileMap(entry);
931 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -0700932 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700933 if (!entryMap) {
934 return false;
935 }
936
937 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +0000938 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700939 return true;
940}
941
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700942// The font image should be a 96x2 array of character images. The
943// columns are the printable ASCII characters 0x20 - 0x7f. The
944// top row is regular text; the bottom row is bold.
945status_t BootAnimation::initFont(Font* font, const char* fallback) {
946 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800947
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700948 if (font->map != nullptr) {
949 glGenTextures(1, &font->texture.name);
950 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800951
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700952 status = initTexture(font->map, &font->texture.w, &font->texture.h);
953
Lucas Dupin8eedc022021-07-29 21:49:07 +0000954 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
955 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
956 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
957 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700958 } else if (fallback != nullptr) {
959 status = initTexture(&font->texture, mAssets, fallback);
960 } else {
961 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800962 }
963
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700964 if (status == NO_ERROR) {
965 font->char_width = font->texture.w / FONT_NUM_COLS;
966 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
967 }
968
969 return status;
970}
971
972void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
973 glEnable(GL_BLEND); // Allow us to draw on top of the animation
974 glBindTexture(GL_TEXTURE_2D, font.texture.name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000975 glUseProgram(mTextShader);
976 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700977
978 const int len = strlen(str);
979 const int strWidth = font.char_width * len;
980
981 if (*x == TEXT_CENTER_VALUE) {
982 *x = (mWidth - strWidth) / 2;
983 } else if (*x < 0) {
984 *x = mWidth + *x - strWidth;
985 }
986 if (*y == TEXT_CENTER_VALUE) {
987 *y = (mHeight - font.char_height) / 2;
988 } else if (*y < 0) {
989 *y = mHeight + *y - font.char_height;
990 }
991
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700992 for (int i = 0; i < len; i++) {
993 char c = str[i];
994
995 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
996 c = '?';
997 }
998
999 // Crop the texture to only the pixels in the current glyph
1000 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1001 const int row = charPos / FONT_NUM_COLS;
1002 const int col = charPos % FONT_NUM_COLS;
Lucas Dupin8eedc022021-07-29 21:49:07 +00001003 // Bold fonts are expected in the second half of each row.
1004 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1005 float u0 = ((float)col) / FONT_NUM_COLS;
1006 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1007 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1008 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1009 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001010
1011 *x += font.char_width;
1012 }
1013
1014 glDisable(GL_BLEND); // Return to the animation's default behaviour
1015 glBindTexture(GL_TEXTURE_2D, 0);
1016}
1017
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001018// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001019void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001020 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1021 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001022 static constexpr int TIME_LENGTH = 6;
1023
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001024 time_t rawtime;
1025 time(&rawtime);
1026 struct tm* timeInfo = localtime(&rawtime);
1027
1028 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001029 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1030 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001031
1032 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001033 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001034 mClockEnabled = false;
1035 return;
1036 }
1037
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001038 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001039 int x = xPos;
1040 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001041 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001042}
1043
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001044void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1045 static constexpr int PERCENT_LENGTH = 5;
1046
1047 char percentBuff[PERCENT_LENGTH];
1048 // ';' has the ascii code just after ':', and the font resource contains '%'
1049 // for that ascii code.
1050 sprintf(percentBuff, "%d;", percent);
1051 int x = xPos;
1052 int y = yPos;
1053 drawText(percentBuff, font, false, &x, &y);
1054}
1055
Marin Shalamanov9070c052020-05-18 19:05:17 +02001056bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001057 String8 desString;
1058
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001059 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001060 return false;
1061 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001062 char const* s = desString.string();
Shan Huang2b31a362021-08-16 16:45:39 +00001063 std::string dynamicColoringPartName = "";
1064 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001065
Mathias Agopiana8826d62009-10-01 03:10:14 -07001066 // Parse the description file
1067 for (;;) {
1068 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001069 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001070 String8 line(s, endl - s);
1071 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001072 int fps = 0;
1073 int width = 0;
1074 int height = 0;
1075 int count = 0;
1076 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001077 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001078 int framesToFadeCount = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001079 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001080 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001081 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1082 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang2b31a362021-08-16 16:45:39 +00001083 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001084 char pathType;
Shan Huang2b31a362021-08-16 16:45:39 +00001085 // start colors default to black if unspecified
1086 char start_color_0[7] = "000000";
1087 char start_color_1[7] = "000000";
1088 char start_color_2[7] = "000000";
1089 char start_color_3[7] = "000000";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001090
1091 int nextReadPos;
1092
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001093 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1094 if (topLineNumbers == 3 || topLineNumbers == 4) {
1095 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001096 animation.width = width;
1097 animation.height = height;
1098 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001099 if (topLineNumbers == 4) {
1100 animation.progressEnabled = (progress != 0);
1101 } else {
1102 animation.progressEnabled = false;
1103 }
Shan Huang2b31a362021-08-16 16:45:39 +00001104 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s",
1105 dynamicColoringPartNameBuffer,
1106 start_color_0, start_color_1, start_color_2, start_color_3)) {
1107 animation.dynamicColoringEnabled = true;
1108 parseColor(start_color_0, animation.startColors[0]);
1109 parseColor(start_color_1, animation.startColors[1]);
1110 parseColor(start_color_2, animation.startColors[2]);
1111 parseColor(start_color_3, animation.startColors[3]);
1112 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001113 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1114 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1115 if (pathType == 'f') {
1116 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1117 clockPos2);
1118 } else {
1119 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1120 }
1121 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1122 // "clockPos1=%s, clockPos2=%s",
1123 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001124 Animation::Part part;
Shan Huang2b31a362021-08-16 16:45:39 +00001125 if (path == dynamicColoringPartName) {
1126 // Part is specified to use dynamic coloring.
1127 part.useDynamicColoring = true;
1128 part.postDynamicColoring = false;
1129 postDynamicColoring = true;
1130 } else {
1131 // Part does not use dynamic coloring.
1132 part.useDynamicColoring = false;
1133 part.postDynamicColoring = postDynamicColoring;
1134 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001135 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001136 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001137 part.count = count;
1138 part.pause = pause;
1139 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001140 part.audioData = nullptr;
1141 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001142 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001143 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001144 part.backgroundColor[0] = 0.0f;
1145 part.backgroundColor[1] = 0.0f;
1146 part.backgroundColor[2] = 0.0f;
1147 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001148 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001149 animation.parts.add(part);
1150 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001151 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001152 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001153 Animation::Part part;
1154 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001155 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001156 part.count = 1;
1157 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001158 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001159 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001160 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001161 animation.parts.add(part);
1162 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001163 s = ++endl;
1164 }
1165
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001166 return true;
1167}
1168
Marin Shalamanov9070c052020-05-18 19:05:17 +02001169bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001170 // read all the data structures
1171 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001172 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001173 ZipFileRO* zip = animation.zip;
1174 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001175 return false;
1176 }
1177
1178 ZipEntryRO entry;
1179 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001180 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001181 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001182 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001183 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001184 continue;
1185 }
1186
1187 const String8 entryName(name);
1188 const String8 path(entryName.getPathDir());
1189 const String8 leaf(entryName.getPathLeaf());
1190 if (leaf.size() > 0) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001191 if (entryName == CLOCK_FONT_ZIP_NAME) {
1192 FileMap* map = zip->createEntryFileMap(entry);
1193 if (map) {
1194 animation.clockFont.map = map;
1195 }
1196 continue;
1197 }
1198
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001199 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1200 FileMap* map = zip->createEntryFileMap(entry);
1201 if (map) {
1202 animation.progressFont.map = map;
1203 }
1204 continue;
1205 }
1206
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001207 for (size_t j = 0; j < pcount; j++) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001208 if (path == animation.parts[j].path) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001209 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001210 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001211 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001212 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001213 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001214 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001215 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001216 if (leaf == "audio.wav") {
1217 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001218 part.audioData = (uint8_t *)map->getDataPtr();
1219 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001220 } else if (leaf == "trim.txt") {
1221 part.trimData.setTo((char const*)map->getDataPtr(),
1222 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001223 } else {
1224 Animation::Frame frame;
1225 frame.name = leaf;
1226 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001227 frame.trimWidth = animation.width;
1228 frame.trimHeight = animation.height;
1229 frame.trimX = 0;
1230 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001231 part.frames.add(frame);
1232 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001233 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001234 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001235 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001236 }
1237 }
1238 }
1239 }
1240 }
1241 }
1242
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001243 // If there is trimData present, override the positioning defaults.
1244 for (Animation::Part& part : animation.parts) {
1245 const char* trimDataStr = part.trimData.string();
1246 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1247 const char* endl = strstr(trimDataStr, "\n");
1248 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001249 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001250 break;
1251 }
1252 String8 line(trimDataStr, endl - trimDataStr);
1253 const char* lineStr = line.string();
1254 trimDataStr = ++endl;
1255 int width = 0, height = 0, x = 0, y = 0;
1256 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1257 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1258 frame.trimWidth = width;
1259 frame.trimHeight = height;
1260 frame.trimX = x;
1261 frame.trimY = y;
1262 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001263 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001264 break;
1265 }
1266 }
1267 }
1268
1269 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001270
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001271 return true;
1272}
1273
Marin Shalamanov9070c052020-05-18 19:05:17 +02001274bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001275 if (mAnimation == nullptr) {
1276 mAnimation = loadAnimation(mZipFileName);
1277 }
1278
1279 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001280 return false;
1281
Huihong Luo50a2f362018-08-11 09:27:57 -07001282 // mCallbacks->init() may get called recursively,
1283 // this loop is needed to get the same results
1284 for (const Animation::Part& part : mAnimation->parts) {
1285 if (part.animation != nullptr) {
1286 mCallbacks->init(part.animation->parts);
1287 }
1288 }
1289 mCallbacks->init(mAnimation->parts);
1290
Damien Bargiacchi97480862016-03-29 14:55:55 -07001291 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001292 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1293 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001294 anyPartHasClock = true;
1295 break;
1296 }
1297 }
1298 if (!anyPartHasClock) {
1299 mClockEnabled = false;
1300 }
1301
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301302 // Check if npot textures are supported
1303 mUseNpotTextures = false;
1304 String8 gl_extensions;
1305 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1306 if (!exts) {
1307 glGetError();
1308 } else {
1309 gl_extensions.setTo(exts);
1310 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1311 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1312 mUseNpotTextures = true;
1313 }
1314 }
1315
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001316 // Blend required to draw time on top of animation frames.
1317 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001318 glDisable(GL_DITHER);
1319 glDisable(GL_SCISSOR_TEST);
1320 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001321
Greg Kaiser2ded8002021-07-19 17:03:27 +00001322 glEnable(GL_TEXTURE_2D);
Lucas Dupin8eedc022021-07-29 21:49:07 +00001323 glBindTexture(GL_TEXTURE_2D, 0);
1324 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1325 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1326 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1327 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001328 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001329 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001330 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001331 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001332 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001333 }
1334
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001335 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1336
Damien Bargiacchi97480862016-03-29 14:55:55 -07001337 if (mClockEnabled && !updateIsTimeAccurate()) {
1338 mTimeCheckThread = new TimeCheckThread(this);
1339 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1340 }
1341
George Burgess IV0f8e8112021-08-23 17:32:23 -07001342 if (mAnimation->dynamicColoringEnabled) {
Shan Huang7fee3522021-08-18 00:56:08 +00001343 initDynamicColors();
1344 }
1345
Huihong Luo50a2f362018-08-11 09:27:57 -07001346 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001347
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001348 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001349 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001350 mTimeCheckThread = nullptr;
1351 }
1352
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001353 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001354 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001355 }
1356
Huihong Luo50a2f362018-08-11 09:27:57 -07001357 releaseAnimation(mAnimation);
1358 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001359
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001360 return false;
1361}
1362
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001363bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1364 const int fadedFramesCount,
1365 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001366 // 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 +01001367 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1368 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001369}
1370
Lucas Dupin8eedc022021-07-29 21:49:07 +00001371// Linear mapping from range <a1, a2> to range <b1, b2>
1372float mapLinear(float x, float a1, float a2, float b1, float b2) {
1373 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1374}
1375
1376void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1377 // Map coordinates from screen space to world space.
1378 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1379 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1380 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1381 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1382 // Update quad vertex positions.
1383 quadPositions[0] = x0;
1384 quadPositions[1] = y0;
1385 quadPositions[2] = x1;
1386 quadPositions[3] = y0;
1387 quadPositions[4] = x1;
1388 quadPositions[5] = y1;
1389 quadPositions[6] = x1;
1390 quadPositions[7] = y1;
1391 quadPositions[8] = x0;
1392 quadPositions[9] = y1;
1393 quadPositions[10] = x0;
1394 quadPositions[11] = y0;
1395 glDrawArrays(GL_TRIANGLES, 0,
1396 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1397}
1398
Shan Huang7fee3522021-08-18 00:56:08 +00001399void BootAnimation::initDynamicColors() {
1400 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1401 parseColorDecimalString(
1402 android::base::GetProperty("persist.bootanim.color" + std::to_string(i + 1), ""),
1403 mAnimation->endColors[i], mAnimation->startColors[i]);
1404 }
1405 glUseProgram(mImageShader);
1406 SLOGI("[BootAnimation] Dynamically coloring boot animation.");
1407 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1408 float *startColor = mAnimation->startColors[i];
1409 float *endColor = mAnimation->endColors[i];
1410 glUniform4f(glGetUniformLocation(mImageShader,
1411 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
1412 startColor[0], startColor[1], startColor[2], 1 /* alpha */);
1413 glUniform4f(glGetUniformLocation(mImageShader,
1414 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
1415 endColor[0], endColor[1], endColor[2], 1 /* alpha */);
1416 }
1417 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1418}
1419
Marin Shalamanov9070c052020-05-18 19:05:17 +02001420bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001421 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001422 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001423
Wei Wang159a4102018-10-23 23:15:58 -07001424 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001425 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001426
1427 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001428 int lastDisplayedProgress = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001429 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001430 const Animation::Part& part(animation.parts[i]);
1431 const size_t fcount = part.frames.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001432
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001433 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001434 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001435 playAnimation(*part.animation);
1436 if (exitPending())
1437 break;
1438 continue; //to next part
1439 }
1440
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001441 // process the part not only while the count allows but also if already fading
1442 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001443 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001444
Ed Coyne7464ac92017-06-08 12:26:48 -07001445 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001446
Jesse Hall083b84c2014-09-22 10:51:09 -07001447 glClearColor(
1448 part.backgroundColor[0],
1449 part.backgroundColor[1],
1450 part.backgroundColor[2],
1451 1.0f);
1452
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001453 // For the last animation, if we have progress indicator from
1454 // the system, display it.
1455 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1456 bool displayProgress = animation.progressEnabled &&
1457 (i == (pcount -1)) && currentProgress != 0;
1458
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001459 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001460 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001461
Shan Huang2b31a362021-08-16 16:45:39 +00001462 // Color progress is
1463 // - the normalized animation progress between [0, 1] for the dynamic coloring part,
1464 // - 0 for parts that come before,
1465 // - 1 for parts that come after.
1466 float colorProgress = part.useDynamicColoring
1467 ? (float)j / fcount
1468 : (part.postDynamicColoring ? 1 : 0);
1469
Marin Shalamanov9070c052020-05-18 19:05:17 +02001470 processDisplayEvents();
1471
1472 const int animationX = (mWidth - animation.width) / 2;
1473 const int animationY = (mHeight - animation.height) / 2;
1474
Mathias Agopiana8826d62009-10-01 03:10:14 -07001475 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001476 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001477
1478 if (r > 0) {
1479 glBindTexture(GL_TEXTURE_2D, frame.tid);
1480 } else {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001481 glGenTextures(1, &frame.tid);
1482 glBindTexture(GL_TEXTURE_2D, frame.tid);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001483 int w, h;
Shan Huang2b31a362021-08-16 16:45:39 +00001484 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1485 // of transparent pixels are preserved.
1486 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001487 }
1488
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001489 const int xc = animationX + frame.trimX;
1490 const int yc = animationY + frame.trimY;
Shan Huang2b31a362021-08-16 16:45:39 +00001491 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001492 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1493 // which is equivalent to mHeight - (yc + frame.trimHeight)
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001494 const int frameDrawY = mHeight - (yc + frame.trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001495
Lucas Dupin8eedc022021-07-29 21:49:07 +00001496 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001497 // if the part hasn't been stopped yet then continue fading if necessary
1498 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001499 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001500 if (fadedFramesCount >= part.framesToFadeCount) {
1501 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1502 }
1503 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001504 glUseProgram(mImageShader);
1505 glUniform1i(mImageTextureLocation, 0);
1506 glUniform1f(mImageFadeLocation, fade);
Shan Huang2b31a362021-08-16 16:45:39 +00001507 if (animation.dynamicColoringEnabled) {
1508 glUniform1f(mImageColorProgressLocation, colorProgress);
1509 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001510 glEnable(GL_BLEND);
1511 drawTexturedQuad(xc, frameDrawY, frame.trimWidth, frame.trimHeight);
1512 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001513
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001514 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1515 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001516 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001517
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001518 if (displayProgress) {
1519 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1520 // In case the new progress jumped suddenly, still show an
1521 // increment of 1.
1522 if (lastDisplayedProgress != 100) {
1523 // Artificially sleep 1/10th a second to slow down the animation.
1524 usleep(100000);
1525 if (lastDisplayedProgress < newProgress) {
1526 lastDisplayedProgress++;
1527 }
1528 }
1529 // Put the progress percentage right below the animation.
1530 int posY = animation.height / 3;
1531 int posX = TEXT_CENTER_VALUE;
1532 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1533 }
1534
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001535 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001536
Mathias Agopiana8826d62009-10-01 03:10:14 -07001537 eglSwapBuffers(mDisplay, mSurface);
1538
1539 nsecs_t now = systemTime();
1540 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001541 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001542 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001543
1544 if (delay > 0) {
1545 struct timespec spec;
1546 spec.tv_sec = (now + delay) / 1000000000;
1547 spec.tv_nsec = (now + delay) % 1000000000;
1548 int err;
1549 do {
Yi Kong911ac232019-03-24 01:49:02 -07001550 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001551 } while (err<0 && errno == EINTR);
1552 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001553
1554 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001555 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001556
Mathias Agopiana8826d62009-10-01 03:10:14 -07001557 usleep(part.pause * ns2us(frameDuration));
Kevin Hesterd3782b22012-04-26 10:38:55 -07001558
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001559 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1560 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001561 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1562 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1563 continue;
1564 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001565 break; // exit the infinite non-fading part when it has been played at least once
1566 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001567 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001568 }
1569
1570 // Free textures created for looping parts now that the animation is done.
1571 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001572 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001573 const size_t fcount = part.frames.size();
1574 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001575 const Animation::Frame& frame(part.frames[j]);
1576 glDeleteTextures(1, &frame.tid);
1577 }
1578 }
1579 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001580
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001581 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001582}
1583
Marin Shalamanov9070c052020-05-18 19:05:17 +02001584void BootAnimation::processDisplayEvents() {
1585 // This will poll mDisplayEventReceiver and if there are new events it'll call
1586 // displayEventCallback synchronously.
1587 mLooper->pollOnce(0);
1588}
1589
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001590void BootAnimation::handleViewport(nsecs_t timestep) {
1591 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1592 return;
1593 }
1594 if (mTargetInset < 0) {
1595 // Poll the amount for the top display inset. This will return -1 until persistent properties
1596 // have been loaded.
1597 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1598 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1599 }
1600 if (mTargetInset <= 0) {
1601 return;
1602 }
1603
1604 if (mCurrentInset < mTargetInset) {
1605 // After the device boots, the inset will effectively be cropped away. We animate this here.
1606 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1607 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1608
1609 SurfaceComposerClient::Transaction()
1610 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1611 .apply();
1612 } else {
1613 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1614 // later. This changes the coordinate system, and means we must move the surface up by
1615 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001616 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1617 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1618
1619 SurfaceComposerClient::Transaction t;
1620 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1621 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001622 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001623 t.apply();
1624
1625 mTargetInset = mCurrentInset = 0;
1626 }
1627
1628 int delta = timestep * mTargetInset / ms2ns(200);
1629 mCurrentInset += delta;
1630}
1631
Marin Shalamanov9070c052020-05-18 19:05:17 +02001632void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001633 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1634 e = animation->parts.end(); it != e; ++it) {
1635 if (it->animation)
1636 releaseAnimation(it->animation);
1637 }
1638 if (animation->zip)
1639 delete animation->zip;
1640 delete animation;
1641}
1642
Marin Shalamanov9070c052020-05-18 19:05:17 +02001643BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001644 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001645 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001646 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001647 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001648 }
1649 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001650 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001651 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001652 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001653 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001654 }
1655
1656 Animation *animation = new Animation;
1657 animation->fileName = fn;
1658 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001659 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001660 mLoadedFiles.add(animation->fileName);
1661
1662 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001663 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001664 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001665 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001666 }
1667
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001668 mLoadedFiles.remove(fn);
1669 return animation;
1670}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001671
1672bool BootAnimation::updateIsTimeAccurate() {
1673 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1674 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1675
1676 if (mTimeIsAccurate) {
1677 return true;
1678 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001679 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001680 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001681
1682 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1683 mTimeFormat12Hour = true;
1684 }
1685
Damien Bargiacchi97480862016-03-29 14:55:55 -07001686 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1687 mTimeIsAccurate = true;
1688 return true;
1689 }
1690
1691 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001692 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001693 long long lastChangedTime = 0;
1694 fscanf(file, "%lld", &lastChangedTime);
1695 fclose(file);
1696 if (lastChangedTime > 0) {
1697 struct timespec now;
1698 clock_gettime(CLOCK_REALTIME, &now);
1699 // Match the Java timestamp format
1700 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001701 if (ACCURATE_TIME_EPOCH < rtcNow
1702 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1703 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001704 mTimeIsAccurate = true;
1705 }
1706 }
1707 }
1708
1709 return mTimeIsAccurate;
1710}
1711
1712BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1713 mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1714
1715BootAnimation::TimeCheckThread::~TimeCheckThread() {
1716 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1717 close(mInotifyFd);
1718}
1719
1720bool BootAnimation::TimeCheckThread::threadLoop() {
1721 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1722 && mBootAnimation->mClockEnabled;
1723 if (!shouldLoop) {
1724 close(mInotifyFd);
1725 mInotifyFd = -1;
1726 }
1727 return shouldLoop;
1728}
1729
1730bool BootAnimation::TimeCheckThread::doThreadLoop() {
1731 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1732
1733 // Poll instead of doing a blocking read so the Thread can exit if requested.
1734 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1735 ssize_t pollResult = poll(&pfd, 1, 1000);
1736
1737 if (pollResult == 0) {
1738 return true;
1739 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001740 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001741 return false;
1742 }
1743
1744 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1745 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1746 if (length == 0) {
1747 return true;
1748 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001749 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001750 return false;
1751 }
1752
1753 const struct inotify_event *event;
1754 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1755 event = (const struct inotify_event *) ptr;
1756 if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
1757 addTimeDirWatch();
1758 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1759 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1760 return !mBootAnimation->updateIsTimeAccurate();
1761 }
1762 }
1763
1764 return true;
1765}
1766
1767void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1768 mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
1769 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1770 if (mTimeWd > 0) {
1771 // No need to watch for the time directory to be created if it already exists
1772 inotify_rm_watch(mInotifyFd, mSystemWd);
1773 mSystemWd = -1;
1774 }
1775}
1776
1777status_t BootAnimation::TimeCheckThread::readyToRun() {
1778 mInotifyFd = inotify_init();
1779 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001780 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001781 return NO_INIT;
1782 }
1783
1784 mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1785 if (mSystemWd < 0) {
1786 close(mInotifyFd);
1787 mInotifyFd = -1;
Dan Sandler562d46d2020-05-11 17:09:22 -04001788 SLOGE("Could not add watch for %s: %s", SYSTEM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001789 return NO_INIT;
1790 }
1791
1792 addTimeDirWatch();
1793
1794 if (mBootAnimation->updateIsTimeAccurate()) {
1795 close(mInotifyFd);
1796 mInotifyFd = -1;
1797 return ALREADY_EXISTS;
1798 }
1799
1800 return NO_ERROR;
1801}
1802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803// ---------------------------------------------------------------------------
1804
Marin Shalamanov9070c052020-05-18 19:05:17 +02001805} // namespace android