blob: 59f602c1124797ed1bd68dfd94ac90b395ca8b8a [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;
Shan Huang81846ba2021-09-07 19:07:47 +0000130 const float cWhiteMaskThreshold = 0.05;
Shan Huang2b31a362021-08-16 16:45:39 +0000131 uniform sampler2D uTexture;
132 uniform float uFade;
133 uniform float uColorProgress;
134 uniform vec4 uStartColor0;
135 uniform vec4 uStartColor1;
136 uniform vec4 uStartColor2;
137 uniform vec4 uStartColor3;
138 uniform vec4 uEndColor0;
139 uniform vec4 uEndColor1;
140 uniform vec4 uEndColor2;
141 uniform vec4 uEndColor3;
142 varying highp vec2 vUv;
143 void main() {
144 vec4 mask = texture2D(uTexture, vUv);
Shan Huang488ff742021-08-25 20:10:46 +0000145 float r = mask.r;
146 float g = mask.g;
147 float b = mask.b;
148 float a = mask.a;
149 // If all channels have values, render pixel as a shade of white.
150 float useWhiteMask = step(cWhiteMaskThreshold, r)
151 * step(cWhiteMaskThreshold, g)
152 * step(cWhiteMaskThreshold, b)
153 * step(cWhiteMaskThreshold, a);
154 vec4 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
155 + g * mix(uStartColor1, uEndColor1, uColorProgress)
156 + b * mix(uStartColor2, uEndColor2, uColorProgress)
157 + a * mix(uStartColor3, uEndColor3, uColorProgress);
Shan Huang81846ba2021-09-07 19:07:47 +0000158 color = mix(color, vec4(vec3((r + g + b + a) * 0.25), 1.0), useWhiteMask);
Shan Huang2b31a362021-08-16 16:45:39 +0000159 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
160 })";
Lucas Dupin8eedc022021-07-29 21:49:07 +0000161static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
162 precision mediump float;
163 uniform sampler2D uTexture;
164 uniform float uFade;
165 varying highp vec2 vUv;
166 void main() {
167 vec4 color = texture2D(uTexture, vUv);
Shan Huang2b31a362021-08-16 16:45:39 +0000168 gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000169 })";
170static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
171 precision mediump float;
172 uniform sampler2D uTexture;
173 uniform vec4 uCropArea;
174 varying highp vec2 vUv;
175 void main() {
176 vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
177 mix(uCropArea.y, uCropArea.w, vUv.y));
178 gl_FragColor = texture2D(uTexture, uv);
179 })";
180
181static GLfloat quadPositions[] = {
182 -0.5f, -0.5f,
183 +0.5f, -0.5f,
184 +0.5f, +0.5f,
185 +0.5f, +0.5f,
186 -0.5f, +0.5f,
187 -0.5f, -0.5f
188};
189static GLfloat quadUVs[] = {
190 0.0f, 1.0f,
191 1.0f, 1.0f,
192 1.0f, 0.0f,
193 1.0f, 0.0f,
194 0.0f, 0.0f,
195 0.0f, 1.0f
196};
Narayan Kamathafd31e02013-12-03 13:16:03 +0000197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198// ---------------------------------------------------------------------------
199
Ed Coyne7464ac92017-06-08 12:26:48 -0700200BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200201 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700202 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700203 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400204
Keun-young Parkb5938422017-03-23 13:46:24 -0700205 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
206 if (powerCtl.empty()) {
207 mShuttingDown = false;
208 } else {
209 mShuttingDown = true;
210 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700211 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
212 elapsedRealtime());
213}
214
215BootAnimation::~BootAnimation() {
216 if (mAnimation != nullptr) {
217 releaseAnimation(mAnimation);
218 mAnimation = nullptr;
219 }
220 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
221 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222}
223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700225 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700226 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700227 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700228 // Load the animation content -- this can be slow (eg 200ms)
229 // called before waitForSurfaceFlinger() in main() to avoid wait
230 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
231 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
232 preloadAnimation();
233 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
234 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
Mathias Agopianbc726112009-09-23 15:44:05 -0700235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236}
237
Mathias Agopianbc726112009-09-23 15:44:05 -0700238sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 return mSession;
240}
241
Marin Shalamanov9070c052020-05-18 19:05:17 +0200242void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700243 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700244 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700245
246 // calling requestExit() is not enough here because the Surface code
247 // might be blocked on a condition variable that will never be updated.
248 kill( getpid(), SIGKILL );
249 requestExit();
250}
251
Shan Huang2b31a362021-08-16 16:45:39 +0000252static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
253 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400254 AImageDecoder* decoder = nullptr;
255 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
256 if (!decoder) {
257 return nullptr;
258 }
259
260 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
261 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
262 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
263 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
264 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
265 outInfo->flags = 0;
266
Shan Huang2b31a362021-08-16 16:45:39 +0000267 if (!premultiplyAlpha) {
268 AImageDecoder_setUnpremultipliedRequired(decoder, true);
269 }
270
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400271 const size_t size = outInfo->stride * outInfo->height;
272 void* pixels = malloc(size);
273 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
274 AImageDecoder_delete(decoder);
275
276 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
277 free(pixels);
278 return nullptr;
279 }
280 return pixels;
281}
282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
Shan Huang2b31a362021-08-16 16:45:39 +0000284 const char* name, bool premultiplyAlpha) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700286 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400288
289 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000290 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
291 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400292 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 asset->close();
295 delete asset;
296
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400297 if (!pixels) {
298 return NO_INIT;
299 }
300
301 const int w = bitmapInfo.width;
302 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 texture->w = w;
305 texture->h = h;
306
307 glGenTextures(1, &texture->name);
308 glBindTexture(GL_TEXTURE_2D, texture->name);
309
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400310 switch (bitmapInfo.format) {
311 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400313 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400315 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400317 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400319 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400321 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400323 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400325 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 break;
327 default:
328 break;
329 }
330
Lucas Dupin8eedc022021-07-29 21:49:07 +0000331 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
332 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
333 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
334 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 return NO_ERROR;
337}
338
Shan Huang2b31a362021-08-16 16:45:39 +0000339status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
340 bool premultiplyAlpha) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400341 AndroidBitmapInfo bitmapInfo;
Shan Huang2b31a362021-08-16 16:45:39 +0000342 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
343 premultiplyAlpha);
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400344 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700345
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200346 // FileMap memory is never released until application exit.
347 // Release it now as the texture is already loaded and the memory used for
348 // the packed resource can be released.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700349 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200350
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400351 if (!pixels) {
352 return NO_INIT;
353 }
354
355 const int w = bitmapInfo.width;
356 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700357
Mathias Agopiana8826d62009-10-01 03:10:14 -0700358 int tw = 1 << (31 - __builtin_clz(w));
359 int th = 1 << (31 - __builtin_clz(h));
360 if (tw < w) tw <<= 1;
361 if (th < h) th <<= 1;
362
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400363 switch (bitmapInfo.format) {
364 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530365 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700366 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700367 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700368 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400369 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700370 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530371 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400372 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700373 }
374 break;
375
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400376 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530377 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700378 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700379 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700380 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400381 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700382 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530383 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400384 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700385 }
386 break;
387 default:
388 break;
389 }
390
Lucas Dupin8eedc022021-07-29 21:49:07 +0000391 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
392 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
393 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
394 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700395
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700396 *width = w;
397 *height = h;
398
Mathias Agopiana8826d62009-10-01 03:10:14 -0700399 return NO_ERROR;
400}
401
Marin Shalamanov9070c052020-05-18 19:05:17 +0200402class BootAnimation::DisplayEventCallback : public LooperCallback {
403 BootAnimation* mBootAnimation;
404
405public:
406 DisplayEventCallback(BootAnimation* bootAnimation) {
407 mBootAnimation = bootAnimation;
408 }
409
410 int handleEvent(int /* fd */, int events, void* /* data */) {
411 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
412 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
413 events);
414 return 0; // remove the callback
415 }
416
417 if (!(events & Looper::EVENT_INPUT)) {
418 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
419 return 1; // keep the callback
420 }
421
422 constexpr int kBufferSize = 100;
423 DisplayEventReceiver::Event buffer[kBufferSize];
424 ssize_t numEvents;
425 do {
426 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
427 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
428 const auto& event = buffer[i];
429 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
430 SLOGV("Hotplug received");
431
432 if (!event.hotplug.connected) {
433 // ignore hotplug disconnect
434 continue;
435 }
436 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
437 event.header.displayId);
438
439 if (token != mBootAnimation->mDisplayToken) {
440 // ignore hotplug of a secondary display
441 continue;
442 }
443
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100444 DisplayMode displayMode;
445 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
446 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200447 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100448 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200449 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100450 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
451 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200452 }
453 }
454 } while (numEvents > 0);
455
456 return 1; // keep the callback
457 }
458};
459
460EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
461 const EGLint attribs[] = {
462 EGL_RED_SIZE, 8,
463 EGL_GREEN_SIZE, 8,
464 EGL_BLUE_SIZE, 8,
465 EGL_DEPTH_SIZE, 0,
466 EGL_NONE
467 };
468 EGLint numConfigs;
469 EGLConfig config;
470 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
471 return config;
472}
473
Marin Shalamanov047802d2020-05-19 23:55:12 +0200474ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
475 ui::Size limited(width, height);
476 bool wasLimited = false;
477 const float aspectRatio = float(width) / float(height);
478 if (mMaxWidth != 0 && width > mMaxWidth) {
479 limited.height = mMaxWidth / aspectRatio;
480 limited.width = mMaxWidth;
481 wasLimited = true;
482 }
483 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
484 limited.height = mMaxHeight;
485 limited.width = mMaxHeight * aspectRatio;
486 wasLimited = true;
487 }
488 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
489 limited.width, limited.height, width, height);
490 return limited;
491}
492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493status_t BootAnimation::readyToRun() {
494 mAssets.addDefaultAssets();
495
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800496 mDisplayToken = SurfaceComposerClient::getInternalDisplayToken();
497 if (mDisplayToken == nullptr)
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800498 return NAME_NOT_FOUND;
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800499
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100500 DisplayMode displayMode;
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800501 const status_t error =
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100502 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800503 if (error != NO_ERROR)
504 return error;
505
Marin Shalamanov047802d2020-05-19 23:55:12 +0200506 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
507 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100508 ui::Size resolution = displayMode.resolution;
Marin Shalamanov047802d2020-05-19 23:55:12 +0200509 resolution = limitSurfaceSize(resolution.width, resolution.height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 // create the native surface
Jeff Brown0b722fe2012-08-24 22:40:14 -0700511 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800512 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565);
Mathias Agopian439863f2011-06-28 19:09:31 -0700513
Robert Carre13b58e2017-08-31 14:50:44 -0700514 SurfaceComposerClient::Transaction t;
Huihong Luof97c9e22019-05-29 11:08:01 -0700515
516 // this guest property specifies multi-display IDs to show the boot animation
517 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800518 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200519 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700520 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800521 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700522 bool isValid = displayValue[0] != '\0';
523 if (isValid) {
524 char *p = displayValue;
525 while (*p) {
526 if (!isdigit(*p) && *p != ',') {
527 isValid = false;
528 break;
529 }
530 p ++;
531 }
532 if (!isValid)
Huihong Luod4a217e2020-01-16 15:56:33 -0800533 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700534 }
535 if (isValid) {
536 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200537 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700538 physicalDisplayIds.add(id);
539 if (stream.peek() == ',')
540 stream.ignore();
541 }
542
543 // In the case of multi-display, boot animation shows on the specified displays
544 // in addition to the primary display
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700545 const auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
546 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700547 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700548 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
549 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
550 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700551 }
552 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700553 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700554 }
555
Robert Carre13b58e2017-08-31 14:50:44 -0700556 t.setLayer(control, 0x40000000)
557 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
Mathias Agopian17f638b2009-04-16 20:04:08 -0700559 sp<Surface> s = control->getSurface();
560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700563 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200564 EGLConfig config = getEglConfig(display);
565 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000566 // Initialize egl context with client version number 2.0.
567 EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
568 EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200569 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 eglQuerySurface(display, surface, EGL_WIDTH, &w);
571 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700572
Mathias Agopianabac0102009-07-31 14:47:00 -0700573 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
574 return NO_INIT;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 mDisplay = display;
577 mContext = context;
578 mSurface = surface;
579 mWidth = w;
580 mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700581 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200583 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200585 projectSceneToWindow();
586
Marin Shalamanov9070c052020-05-18 19:05:17 +0200587 // Register a display event receiver
588 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
589 status_t status = mDisplayEventReceiver->initCheck();
590 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
591 status);
592 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
593 new DisplayEventCallback(this), nullptr);
594
Huihong Luo50a2f362018-08-11 09:27:57 -0700595 return NO_ERROR;
596}
597
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200598void BootAnimation::projectSceneToWindow() {
599 glViewport(0, 0, mWidth, mHeight);
600 glScissor(0, 0, mWidth, mHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200601}
602
Marin Shalamanov9070c052020-05-18 19:05:17 +0200603void BootAnimation::resizeSurface(int newWidth, int newHeight) {
604 // We assume this function is called on the animation thread.
605 if (newWidth == mWidth && newHeight == mHeight) {
606 return;
607 }
608 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
609
610 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
611 eglDestroySurface(mDisplay, mSurface);
612
Marin Shalamanov047802d2020-05-19 23:55:12 +0200613 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
614 mWidth = limitedSize.width;
615 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200616
617 SurfaceComposerClient::Transaction t;
618 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
619 t.apply();
620
621 EGLConfig config = getEglConfig(mDisplay);
622 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
623 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
624 SLOGE("Can't make the new surface current. Error %d", eglGetError());
625 return;
626 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200627
628 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200629
630 mSurface = surface;
631}
632
Huihong Luo50a2f362018-08-11 09:27:57 -0700633bool BootAnimation::preloadAnimation() {
634 findBootAnimationFile();
635 if (!mZipFileName.isEmpty()) {
636 mAnimation = loadAnimation(mZipFileName);
637 return (mAnimation != nullptr);
638 }
639
640 return false;
641}
642
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000643bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
644 for (const std::string& f : files) {
645 if (access(f.c_str(), R_OK) == 0) {
646 mZipFileName = f.c_str();
647 return true;
648 }
649 }
650 return false;
651}
652
Huihong Luo50a2f362018-08-11 09:27:57 -0700653void BootAnimation::findBootAnimationFile() {
Elliott Hughesc367d482013-10-29 13:12:55 -0700654 // If the device has encryption turned on or is in process
Jason parksbd9a08d2011-01-31 15:04:34 -0600655 // of being encrypted we show the encrypted boot animation.
656 char decrypt[PROPERTY_VALUE_MAX];
657 property_get("vold.decrypt", decrypt, "");
658
Keun-young Parkb5938422017-03-23 13:46:24 -0700659 bool encryptedAnimation = atoi(decrypt) != 0 ||
660 !strcmp("trigger_restart_min_framework", decrypt);
Jason parksbd9a08d2011-01-31 15:04:34 -0600661
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900662 if (!mShuttingDown && encryptedAnimation) {
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000663 static const std::vector<std::string> encryptedBootFiles = {
664 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
665 };
666 if (findBootAnimationFileInternal(encryptedBootFiles)) {
667 return;
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900668 }
Jason parksbd9a08d2011-01-31 15:04:34 -0600669 }
Beverly34ffe252019-05-17 11:03:54 -0400670
671 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000672 static const std::vector<std::string> bootFiles = {
673 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
674 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
675 };
676 static const std::vector<std::string> shutdownFiles = {
677 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
678 };
679 static const std::vector<std::string> userspaceRebootFiles = {
680 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
681 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
682 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700683
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000684 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
685 findBootAnimationFileInternal(userspaceRebootFiles);
686 } else if (mShuttingDown) {
687 findBootAnimationFileInternal(shutdownFiles);
688 } else {
689 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691}
692
Lucas Dupin8eedc022021-07-29 21:49:07 +0000693GLuint compileShader(GLenum shaderType, const GLchar *source) {
694 GLuint shader = glCreateShader(shaderType);
695 glShaderSource(shader, 1, &source, 0);
696 glCompileShader(shader);
697 GLint isCompiled = 0;
698 glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
699 if (isCompiled == GL_FALSE) {
700 SLOGE("Compile shader failed. Shader type: %d", shaderType);
Shan Huang81846ba2021-09-07 19:07:47 +0000701 GLint maxLength = 0;
702 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
703 std::vector<GLchar> errorLog(maxLength);
704 glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
705 SLOGE("Shader compilation error: %s", &errorLog[0]);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000706 return 0;
707 }
708 return shader;
709}
710
711GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
712 GLuint program = glCreateProgram();
713 glAttachShader(program, vertexShader);
714 glAttachShader(program, fragmentShader);
715 glLinkProgram(program);
716 GLint isLinked = 0;
717 glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
718 if (isLinked == GL_FALSE) {
719 SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
720 vertexShader, fragmentShader);
721 return 0;
722 }
723 return program;
724}
725
726void BootAnimation::initShaders() {
Shan Huang2b31a362021-08-16 16:45:39 +0000727 bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000728 GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
729 GLuint imageFragmentShader =
Shan Huang2b31a362021-08-16 16:45:39 +0000730 compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
731 ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
732 : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000733 GLuint textFragmentShader =
734 compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
735
736 // Initialize image shader.
737 mImageShader = linkShader(vertexShader, imageFragmentShader);
738 GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
739 GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
740 mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
741 mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
742 glEnableVertexAttribArray(positionLocation);
743 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
744 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
745 glEnableVertexAttribArray(uvLocation);
746
747 // Initialize text shader.
748 mTextShader = linkShader(vertexShader, textFragmentShader);
749 positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
750 uvLocation = glGetAttribLocation(mTextShader, A_UV);
751 mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
752 mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
753 glEnableVertexAttribArray(positionLocation);
754 glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, quadPositions);
755 glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
756 glEnableVertexAttribArray(uvLocation);
757}
758
Marin Shalamanov9070c052020-05-18 19:05:17 +0200759bool BootAnimation::threadLoop() {
760 bool result;
Lucas Dupin8eedc022021-07-29 21:49:07 +0000761 initShaders();
762
Narayan Kamathafd31e02013-12-03 13:16:03 +0000763 // We have no bootanimation file, so we use the stock android logo
764 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700765 if (mZipFileName.isEmpty()) {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200766 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700767 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200768 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700769 }
770
Philip Junker60600562020-11-25 18:16:16 +0100771 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
773 eglDestroyContext(mDisplay, mContext);
774 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700775 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700776 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700777 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530778 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700779 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200780 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781}
782
Marin Shalamanov9070c052020-05-18 19:05:17 +0200783bool BootAnimation::android() {
Lucas Dupin8eedc022021-07-29 21:49:07 +0000784 glActiveTexture(GL_TEXTURE0);
785
Wei Wang159a4102018-10-23 23:15:58 -0700786 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700787 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700788 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
789 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790
Ed Coyne7464ac92017-06-08 12:26:48 -0700791 mCallbacks->init({});
792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 // clear screen
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700794 glDisable(GL_DITHER);
795 glDisable(GL_SCISSOR_TEST);
Shan Huangbfd2d3c2021-09-09 23:19:04 +0000796 glUseProgram(mImageShader);
797
Mathias Agopian59f19e42011-05-06 19:22:12 -0700798 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 glClear(GL_COLOR_BUFFER_BIT);
800 eglSwapBuffers(mDisplay, mSurface);
801
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700802 // Blend state
803 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 const nsecs_t startTime = systemTime();
806 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200807 processDisplayEvents();
808 const GLint xc = (mWidth - mAndroid[0].w) / 2;
809 const GLint yc = (mHeight - mAndroid[0].h) / 2;
810 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
811 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
812 updateRect.height());
813
Mathias Agopian13796652009-03-24 22:49:21 -0700814 nsecs_t now = systemTime();
815 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700816 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
817 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
818 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819
Mathias Agopian81668642009-07-28 11:41:30 -0700820 glDisable(GL_SCISSOR_TEST);
821 glClear(GL_COLOR_BUFFER_BIT);
822
823 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000826 drawTexturedQuad(x, yc, mAndroid[1].w, mAndroid[1].h);
827 drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700829 glEnable(GL_BLEND);
830 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000831 drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832
Mathias Agopian627e7b52009-05-21 19:21:59 -0700833 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
834 if (res == EGL_FALSE)
835 break;
836
Mathias Agopian13796652009-03-24 22:49:21 -0700837 // 12fps: don't animate too fast to preserve CPU
838 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
839 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700840 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700841
842 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 } while (!exitPending());
844
845 glDeleteTextures(1, &mAndroid[0].name);
846 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 return false;
848}
849
Kevin Hesterd3782b22012-04-26 10:38:55 -0700850void BootAnimation::checkExit() {
851 // Allow surface flinger to gracefully request shutdown
852 char value[PROPERTY_VALUE_MAX];
853 property_get(EXIT_PROP_NAME, value, "0");
854 int exitnow = atoi(value);
855 if (exitnow) {
856 requestExit();
857 }
858}
859
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700860bool BootAnimation::validClock(const Animation::Part& part) {
861 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
862}
863
864bool parseTextCoord(const char* str, int* dest) {
865 if (strcmp("c", str) == 0) {
866 *dest = TEXT_CENTER_VALUE;
867 return true;
868 }
869
870 char* end;
871 int val = (int) strtol(str, &end, 0);
872 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
873 return false;
874 }
875 *dest = val;
876 return true;
877}
878
879// Parse two position coordinates. If only string is non-empty, treat it as the y value.
880void parsePosition(const char* str1, const char* str2, int* x, int* y) {
881 bool success = false;
882 if (strlen(str1) == 0) { // No values were specified
883 // success = false
884 } else if (strlen(str2) == 0) { // we have only one value
885 if (parseTextCoord(str1, y)) {
886 *x = TEXT_CENTER_VALUE;
887 success = true;
888 }
889 } else {
890 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
891 success = true;
892 }
893 }
894
895 if (!success) {
896 *x = TEXT_MISSING_VALUE;
897 *y = TEXT_MISSING_VALUE;
898 }
899}
900
Jesse Hall083b84c2014-09-22 10:51:09 -0700901// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
902// characters in str is a hex number in [0, 255], which are converted to
903// floating point values in the range [0.0, 1.0] and placed in the
904// corresponding elements of color.
905//
906// If the input string isn't valid, parseColor returns false and color is
907// left unchanged.
908static bool parseColor(const char str[7], float color[3]) {
909 float tmpColor[3];
910 for (int i = 0; i < 3; i++) {
911 int val = 0;
912 for (int j = 0; j < 2; j++) {
913 val *= 16;
914 char c = str[2*i + j];
915 if (c >= '0' && c <= '9') val += c - '0';
916 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
917 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
918 else return false;
919 }
920 tmpColor[i] = static_cast<float>(val) / 255.0f;
921 }
922 memcpy(color, tmpColor, sizeof(tmpColor));
923 return true;
924}
925
Shan Huang2b31a362021-08-16 16:45:39 +0000926// Parse a color represented as a signed decimal int string.
927// E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
928// If the input color string is empty, set color with values in defaultColor.
929static void parseColorDecimalString(const std::string& colorString,
930 float color[3], float defaultColor[3]) {
931 if (colorString == "") {
932 memcpy(color, defaultColor, sizeof(float) * 3);
933 return;
934 }
935 int colorInt = atoi(colorString.c_str());
936 color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
937 color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
938 color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
939}
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700940
Marin Shalamanov9070c052020-05-18 19:05:17 +0200941static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700942 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -0700943 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700944 if (!entry) {
945 return false;
946 }
947
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700948 FileMap* entryMap = zip->createEntryFileMap(entry);
949 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -0700950 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700951 if (!entryMap) {
952 return false;
953 }
954
955 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +0000956 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700957 return true;
958}
959
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700960// The font image should be a 96x2 array of character images. The
961// columns are the printable ASCII characters 0x20 - 0x7f. The
962// top row is regular text; the bottom row is bold.
963status_t BootAnimation::initFont(Font* font, const char* fallback) {
964 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800965
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700966 if (font->map != nullptr) {
967 glGenTextures(1, &font->texture.name);
968 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800969
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700970 status = initTexture(font->map, &font->texture.w, &font->texture.h);
971
Lucas Dupin8eedc022021-07-29 21:49:07 +0000972 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
973 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
974 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
975 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700976 } else if (fallback != nullptr) {
977 status = initTexture(&font->texture, mAssets, fallback);
978 } else {
979 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800980 }
981
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700982 if (status == NO_ERROR) {
983 font->char_width = font->texture.w / FONT_NUM_COLS;
984 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
985 }
986
987 return status;
988}
989
990void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
991 glEnable(GL_BLEND); // Allow us to draw on top of the animation
992 glBindTexture(GL_TEXTURE_2D, font.texture.name);
Lucas Dupin8eedc022021-07-29 21:49:07 +0000993 glUseProgram(mTextShader);
994 glUniform1i(mTextTextureLocation, 0);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700995
996 const int len = strlen(str);
997 const int strWidth = font.char_width * len;
998
999 if (*x == TEXT_CENTER_VALUE) {
1000 *x = (mWidth - strWidth) / 2;
1001 } else if (*x < 0) {
1002 *x = mWidth + *x - strWidth;
1003 }
1004 if (*y == TEXT_CENTER_VALUE) {
1005 *y = (mHeight - font.char_height) / 2;
1006 } else if (*y < 0) {
1007 *y = mHeight + *y - font.char_height;
1008 }
1009
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001010 for (int i = 0; i < len; i++) {
1011 char c = str[i];
1012
1013 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1014 c = '?';
1015 }
1016
1017 // Crop the texture to only the pixels in the current glyph
1018 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
1019 const int row = charPos / FONT_NUM_COLS;
1020 const int col = charPos % FONT_NUM_COLS;
Lucas Dupin8eedc022021-07-29 21:49:07 +00001021 // Bold fonts are expected in the second half of each row.
1022 float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1023 float u0 = ((float)col) / FONT_NUM_COLS;
1024 float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1025 float u1 = u0 + 1.0f / FONT_NUM_COLS;
1026 glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1027 drawTexturedQuad(*x, *y, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001028
1029 *x += font.char_width;
1030 }
1031
1032 glDisable(GL_BLEND); // Return to the animation's default behaviour
1033 glBindTexture(GL_TEXTURE_2D, 0);
1034}
1035
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001036// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001037void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001038 static constexpr char TIME_FORMAT_12[] = "%l:%M";
1039 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001040 static constexpr int TIME_LENGTH = 6;
1041
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001042 time_t rawtime;
1043 time(&rawtime);
1044 struct tm* timeInfo = localtime(&rawtime);
1045
1046 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001047 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1048 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001049
1050 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -07001051 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001052 mClockEnabled = false;
1053 return;
1054 }
1055
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001056 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001057 int x = xPos;
1058 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -08001059 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001060}
1061
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001062void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1063 static constexpr int PERCENT_LENGTH = 5;
1064
1065 char percentBuff[PERCENT_LENGTH];
1066 // ';' has the ascii code just after ':', and the font resource contains '%'
1067 // for that ascii code.
1068 sprintf(percentBuff, "%d;", percent);
1069 int x = xPos;
1070 int y = yPos;
1071 drawText(percentBuff, font, false, &x, &y);
1072}
1073
Marin Shalamanov9070c052020-05-18 19:05:17 +02001074bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001075 String8 desString;
1076
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001077 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001078 return false;
1079 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001080 char const* s = desString.string();
Shan Huang2b31a362021-08-16 16:45:39 +00001081 std::string dynamicColoringPartName = "";
1082 bool postDynamicColoring = false;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001083
Mathias Agopiana8826d62009-10-01 03:10:14 -07001084 // Parse the description file
1085 for (;;) {
1086 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -07001087 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001088 String8 line(s, endl - s);
1089 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001090 int fps = 0;
1091 int width = 0;
1092 int height = 0;
1093 int count = 0;
1094 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001095 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001096 int framesToFadeCount = 0;
Shan Huang488ff742021-08-25 20:10:46 +00001097 int colorTransitionStart = 0;
1098 int colorTransitionEnd = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001099 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -07001100 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001101 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1102 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Shan Huang2b31a362021-08-16 16:45:39 +00001103 char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
Kevin Hesterd3782b22012-04-26 10:38:55 -07001104 char pathType;
Shan Huang2b31a362021-08-16 16:45:39 +00001105 // start colors default to black if unspecified
1106 char start_color_0[7] = "000000";
1107 char start_color_1[7] = "000000";
1108 char start_color_2[7] = "000000";
1109 char start_color_3[7] = "000000";
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001110
1111 int nextReadPos;
1112
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001113 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1114 if (topLineNumbers == 3 || topLineNumbers == 4) {
1115 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001116 animation.width = width;
1117 animation.height = height;
1118 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001119 if (topLineNumbers == 4) {
1120 animation.progressEnabled = (progress != 0);
1121 } else {
1122 animation.progressEnabled = false;
1123 }
Shan Huang488ff742021-08-25 20:10:46 +00001124 } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
Shan Huang2b31a362021-08-16 16:45:39 +00001125 dynamicColoringPartNameBuffer,
Shan Huang488ff742021-08-25 20:10:46 +00001126 start_color_0, start_color_1, start_color_2, start_color_3,
1127 &colorTransitionStart, &colorTransitionEnd)) {
Shan Huang2b31a362021-08-16 16:45:39 +00001128 animation.dynamicColoringEnabled = true;
1129 parseColor(start_color_0, animation.startColors[0]);
1130 parseColor(start_color_1, animation.startColors[1]);
1131 parseColor(start_color_2, animation.startColors[2]);
1132 parseColor(start_color_3, animation.startColors[3]);
Shan Huang488ff742021-08-25 20:10:46 +00001133 animation.colorTransitionStart = colorTransitionStart;
1134 animation.colorTransitionEnd = colorTransitionEnd;
Shan Huang2b31a362021-08-16 16:45:39 +00001135 dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001136 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1137 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1138 if (pathType == 'f') {
1139 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1140 clockPos2);
1141 } else {
1142 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1143 }
1144 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1145 // "clockPos1=%s, clockPos2=%s",
1146 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001147 Animation::Part part;
Shan Huang2b31a362021-08-16 16:45:39 +00001148 if (path == dynamicColoringPartName) {
1149 // Part is specified to use dynamic coloring.
1150 part.useDynamicColoring = true;
1151 part.postDynamicColoring = false;
1152 postDynamicColoring = true;
1153 } else {
1154 // Part does not use dynamic coloring.
1155 part.useDynamicColoring = false;
1156 part.postDynamicColoring = postDynamicColoring;
1157 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001158 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001159 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001160 part.count = count;
1161 part.pause = pause;
1162 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -07001163 part.audioData = nullptr;
1164 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -07001165 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -07001166 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -07001167 part.backgroundColor[0] = 0.0f;
1168 part.backgroundColor[1] = 0.0f;
1169 part.backgroundColor[2] = 0.0f;
1170 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001171 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001172 animation.parts.add(part);
1173 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001174 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001175 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001176 Animation::Part part;
1177 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001178 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001179 part.count = 1;
1180 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001181 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001182 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001183 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001184 animation.parts.add(part);
1185 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001186 s = ++endl;
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
Greg Kaiser2ded8002021-07-19 17:03:27 +00001345 glEnable(GL_TEXTURE_2D);
Lucas Dupin8eedc022021-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
George Burgess IV0f8e8112021-08-23 17:32:23 -07001365 if (mAnimation->dynamicColoringEnabled) {
Shan Huang7fee3522021-08-18 00:56:08 +00001366 initDynamicColors();
1367 }
1368
Huihong Luo50a2f362018-08-11 09:27:57 -07001369 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001370
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001371 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001372 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001373 mTimeCheckThread = nullptr;
1374 }
1375
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001376 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001377 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001378 }
1379
Huihong Luo50a2f362018-08-11 09:27:57 -07001380 releaseAnimation(mAnimation);
1381 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001382
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001383 return false;
1384}
1385
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001386bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1387 const int fadedFramesCount,
1388 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001389 // 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 +01001390 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1391 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001392}
1393
Lucas Dupin8eedc022021-07-29 21:49:07 +00001394// Linear mapping from range <a1, a2> to range <b1, b2>
1395float mapLinear(float x, float a1, float a2, float b1, float b2) {
1396 return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1397}
1398
1399void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1400 // Map coordinates from screen space to world space.
1401 float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1402 float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1403 float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1404 float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1405 // Update quad vertex positions.
1406 quadPositions[0] = x0;
1407 quadPositions[1] = y0;
1408 quadPositions[2] = x1;
1409 quadPositions[3] = y0;
1410 quadPositions[4] = x1;
1411 quadPositions[5] = y1;
1412 quadPositions[6] = x1;
1413 quadPositions[7] = y1;
1414 quadPositions[8] = x0;
1415 quadPositions[9] = y1;
1416 quadPositions[10] = x0;
1417 quadPositions[11] = y0;
1418 glDrawArrays(GL_TRIANGLES, 0,
1419 sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1420}
1421
Shan Huang7fee3522021-08-18 00:56:08 +00001422void BootAnimation::initDynamicColors() {
1423 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1424 parseColorDecimalString(
1425 android::base::GetProperty("persist.bootanim.color" + std::to_string(i + 1), ""),
1426 mAnimation->endColors[i], mAnimation->startColors[i]);
1427 }
1428 glUseProgram(mImageShader);
1429 SLOGI("[BootAnimation] Dynamically coloring boot animation.");
1430 for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1431 float *startColor = mAnimation->startColors[i];
1432 float *endColor = mAnimation->endColors[i];
1433 glUniform4f(glGetUniformLocation(mImageShader,
1434 (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
1435 startColor[0], startColor[1], startColor[2], 1 /* alpha */);
1436 glUniform4f(glGetUniformLocation(mImageShader,
1437 (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
1438 endColor[0], endColor[1], endColor[2], 1 /* alpha */);
1439 }
1440 mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1441}
1442
Marin Shalamanov9070c052020-05-18 19:05:17 +02001443bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001444 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001445 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001446
Wei Wang159a4102018-10-23 23:15:58 -07001447 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001448 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001449
1450 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001451 int lastDisplayedProgress = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001452 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001453 const Animation::Part& part(animation.parts[i]);
1454 const size_t fcount = part.frames.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001455
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001456 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001457 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001458 playAnimation(*part.animation);
1459 if (exitPending())
1460 break;
1461 continue; //to next part
1462 }
1463
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001464 // process the part not only while the count allows but also if already fading
1465 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001466 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001467
Ed Coyne7464ac92017-06-08 12:26:48 -07001468 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001469
Jesse Hall083b84c2014-09-22 10:51:09 -07001470 glClearColor(
1471 part.backgroundColor[0],
1472 part.backgroundColor[1],
1473 part.backgroundColor[2],
1474 1.0f);
1475
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001476 // For the last animation, if we have progress indicator from
1477 // the system, display it.
1478 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1479 bool displayProgress = animation.progressEnabled &&
1480 (i == (pcount -1)) && currentProgress != 0;
1481
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001482 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001483 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001484
Shan Huang2b31a362021-08-16 16:45:39 +00001485 // Color progress is
Shan Huang488ff742021-08-25 20:10:46 +00001486 // - the animation progress, normalized from
1487 // [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1488 // part.
Shan Huang2b31a362021-08-16 16:45:39 +00001489 // - 0 for parts that come before,
1490 // - 1 for parts that come after.
1491 float colorProgress = part.useDynamicColoring
Shan Huang488ff742021-08-25 20:10:46 +00001492 ? fmin(fmax(
1493 ((float)j - animation.colorTransitionStart) /
1494 fmax(animation.colorTransitionEnd -
1495 animation.colorTransitionStart, 1.0f), 0.0f), 1.0f)
Shan Huang2b31a362021-08-16 16:45:39 +00001496 : (part.postDynamicColoring ? 1 : 0);
1497
Marin Shalamanov9070c052020-05-18 19:05:17 +02001498 processDisplayEvents();
1499
1500 const int animationX = (mWidth - animation.width) / 2;
1501 const int animationY = (mHeight - animation.height) / 2;
1502
Mathias Agopiana8826d62009-10-01 03:10:14 -07001503 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001504 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001505
1506 if (r > 0) {
1507 glBindTexture(GL_TEXTURE_2D, frame.tid);
1508 } else {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001509 glGenTextures(1, &frame.tid);
1510 glBindTexture(GL_TEXTURE_2D, frame.tid);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001511 int w, h;
Shan Huang2b31a362021-08-16 16:45:39 +00001512 // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1513 // of transparent pixels are preserved.
1514 initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001515 }
1516
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001517 const int xc = animationX + frame.trimX;
1518 const int yc = animationY + frame.trimY;
Shan Huang2b31a362021-08-16 16:45:39 +00001519 glClear(GL_COLOR_BUFFER_BIT);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001520 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1521 // which is equivalent to mHeight - (yc + frame.trimHeight)
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001522 const int frameDrawY = mHeight - (yc + frame.trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001523
Lucas Dupin8eedc022021-07-29 21:49:07 +00001524 float fade = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001525 // if the part hasn't been stopped yet then continue fading if necessary
1526 if (exitPending() && part.hasFadingPhase()) {
Lucas Dupin8eedc022021-07-29 21:49:07 +00001527 fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001528 if (fadedFramesCount >= part.framesToFadeCount) {
1529 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1530 }
1531 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001532 glUseProgram(mImageShader);
1533 glUniform1i(mImageTextureLocation, 0);
1534 glUniform1f(mImageFadeLocation, fade);
Shan Huang2b31a362021-08-16 16:45:39 +00001535 if (animation.dynamicColoringEnabled) {
1536 glUniform1f(mImageColorProgressLocation, colorProgress);
1537 }
Lucas Dupin8eedc022021-07-29 21:49:07 +00001538 glEnable(GL_BLEND);
1539 drawTexturedQuad(xc, frameDrawY, frame.trimWidth, frame.trimHeight);
1540 glDisable(GL_BLEND);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001541
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001542 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1543 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001544 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001545
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001546 if (displayProgress) {
1547 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1548 // In case the new progress jumped suddenly, still show an
1549 // increment of 1.
1550 if (lastDisplayedProgress != 100) {
1551 // Artificially sleep 1/10th a second to slow down the animation.
1552 usleep(100000);
1553 if (lastDisplayedProgress < newProgress) {
1554 lastDisplayedProgress++;
1555 }
1556 }
1557 // Put the progress percentage right below the animation.
1558 int posY = animation.height / 3;
1559 int posX = TEXT_CENTER_VALUE;
1560 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1561 }
1562
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001563 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001564
Mathias Agopiana8826d62009-10-01 03:10:14 -07001565 eglSwapBuffers(mDisplay, mSurface);
1566
1567 nsecs_t now = systemTime();
1568 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001569 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001570 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001571
1572 if (delay > 0) {
1573 struct timespec spec;
1574 spec.tv_sec = (now + delay) / 1000000000;
1575 spec.tv_nsec = (now + delay) % 1000000000;
1576 int err;
1577 do {
Yi Kong911ac232019-03-24 01:49:02 -07001578 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001579 } while (err<0 && errno == EINTR);
1580 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001581
1582 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001583 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001584
Mathias Agopiana8826d62009-10-01 03:10:14 -07001585 usleep(part.pause * ns2us(frameDuration));
Kevin Hesterd3782b22012-04-26 10:38:55 -07001586
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001587 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1588 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001589 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1590 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1591 continue;
1592 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001593 break; // exit the infinite non-fading part when it has been played at least once
1594 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001595 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001596 }
1597
1598 // Free textures created for looping parts now that the animation is done.
1599 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001600 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001601 const size_t fcount = part.frames.size();
1602 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001603 const Animation::Frame& frame(part.frames[j]);
1604 glDeleteTextures(1, &frame.tid);
1605 }
1606 }
1607 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001608
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001609 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001610}
1611
Marin Shalamanov9070c052020-05-18 19:05:17 +02001612void BootAnimation::processDisplayEvents() {
1613 // This will poll mDisplayEventReceiver and if there are new events it'll call
1614 // displayEventCallback synchronously.
1615 mLooper->pollOnce(0);
1616}
1617
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001618void BootAnimation::handleViewport(nsecs_t timestep) {
1619 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1620 return;
1621 }
1622 if (mTargetInset < 0) {
1623 // Poll the amount for the top display inset. This will return -1 until persistent properties
1624 // have been loaded.
1625 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1626 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1627 }
1628 if (mTargetInset <= 0) {
1629 return;
1630 }
1631
1632 if (mCurrentInset < mTargetInset) {
1633 // After the device boots, the inset will effectively be cropped away. We animate this here.
1634 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1635 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1636
1637 SurfaceComposerClient::Transaction()
1638 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1639 .apply();
1640 } else {
1641 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1642 // later. This changes the coordinate system, and means we must move the surface up by
1643 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001644 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1645 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1646
1647 SurfaceComposerClient::Transaction t;
1648 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1649 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001650 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001651 t.apply();
1652
1653 mTargetInset = mCurrentInset = 0;
1654 }
1655
1656 int delta = timestep * mTargetInset / ms2ns(200);
1657 mCurrentInset += delta;
1658}
1659
Marin Shalamanov9070c052020-05-18 19:05:17 +02001660void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001661 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1662 e = animation->parts.end(); it != e; ++it) {
1663 if (it->animation)
1664 releaseAnimation(it->animation);
1665 }
1666 if (animation->zip)
1667 delete animation->zip;
1668 delete animation;
1669}
1670
Marin Shalamanov9070c052020-05-18 19:05:17 +02001671BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001672 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001673 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001674 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001675 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001676 }
1677 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001678 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001679 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001680 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001681 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001682 }
1683
1684 Animation *animation = new Animation;
1685 animation->fileName = fn;
1686 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001687 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001688 mLoadedFiles.add(animation->fileName);
1689
1690 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001691 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001692 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001693 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001694 }
1695
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001696 mLoadedFiles.remove(fn);
1697 return animation;
1698}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001699
1700bool BootAnimation::updateIsTimeAccurate() {
1701 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1702 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1703
1704 if (mTimeIsAccurate) {
1705 return true;
1706 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001707 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001708 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001709
1710 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1711 mTimeFormat12Hour = true;
1712 }
1713
Damien Bargiacchi97480862016-03-29 14:55:55 -07001714 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1715 mTimeIsAccurate = true;
1716 return true;
1717 }
1718
1719 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001720 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001721 long long lastChangedTime = 0;
1722 fscanf(file, "%lld", &lastChangedTime);
1723 fclose(file);
1724 if (lastChangedTime > 0) {
1725 struct timespec now;
1726 clock_gettime(CLOCK_REALTIME, &now);
1727 // Match the Java timestamp format
1728 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001729 if (ACCURATE_TIME_EPOCH < rtcNow
1730 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1731 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001732 mTimeIsAccurate = true;
1733 }
1734 }
1735 }
1736
1737 return mTimeIsAccurate;
1738}
1739
1740BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1741 mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1742
1743BootAnimation::TimeCheckThread::~TimeCheckThread() {
1744 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1745 close(mInotifyFd);
1746}
1747
1748bool BootAnimation::TimeCheckThread::threadLoop() {
1749 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1750 && mBootAnimation->mClockEnabled;
1751 if (!shouldLoop) {
1752 close(mInotifyFd);
1753 mInotifyFd = -1;
1754 }
1755 return shouldLoop;
1756}
1757
1758bool BootAnimation::TimeCheckThread::doThreadLoop() {
1759 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1760
1761 // Poll instead of doing a blocking read so the Thread can exit if requested.
1762 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1763 ssize_t pollResult = poll(&pfd, 1, 1000);
1764
1765 if (pollResult == 0) {
1766 return true;
1767 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001768 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001769 return false;
1770 }
1771
1772 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1773 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1774 if (length == 0) {
1775 return true;
1776 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001777 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001778 return false;
1779 }
1780
1781 const struct inotify_event *event;
1782 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1783 event = (const struct inotify_event *) ptr;
1784 if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
1785 addTimeDirWatch();
1786 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1787 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1788 return !mBootAnimation->updateIsTimeAccurate();
1789 }
1790 }
1791
1792 return true;
1793}
1794
1795void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1796 mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
1797 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1798 if (mTimeWd > 0) {
1799 // No need to watch for the time directory to be created if it already exists
1800 inotify_rm_watch(mInotifyFd, mSystemWd);
1801 mSystemWd = -1;
1802 }
1803}
1804
1805status_t BootAnimation::TimeCheckThread::readyToRun() {
1806 mInotifyFd = inotify_init();
1807 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001808 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001809 return NO_INIT;
1810 }
1811
1812 mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1813 if (mSystemWd < 0) {
1814 close(mInotifyFd);
1815 mInotifyFd = -1;
Dan Sandler562d46d2020-05-11 17:09:22 -04001816 SLOGE("Could not add watch for %s: %s", SYSTEM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001817 return NO_INIT;
1818 }
1819
1820 addTimeDirWatch();
1821
1822 if (mBootAnimation->updateIsTimeAccurate()) {
1823 close(mInotifyFd);
1824 mInotifyFd = -1;
1825 return ALREADY_EXISTS;
1826 }
1827
1828 return NO_ERROR;
1829}
1830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831// ---------------------------------------------------------------------------
1832
Marin Shalamanov9070c052020-05-18 19:05:17 +02001833} // namespace android