blob: 5c75d14dc92042520c98bd8528a789362674c7f5 [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>
Greg Kaiser2ded8002021-07-19 17:03:27 +000055
56#include <GLES/gl.h>
57#include <GLES/glext.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058#include <EGL/eglext.h>
59
60#include "BootAnimation.h"
61
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +090062#define ANIM_PATH_MAX 255
63#define STR(x) #x
64#define STRTO(x) STR(x)
65
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066namespace android {
67
Marin Shalamanovcb783ca2021-01-29 21:26:07 +010068using ui::DisplayMode;
69
Damien Bargiacchi97480862016-03-29 14:55:55 -070070static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
Beverly34ffe252019-05-17 11:03:54 -040071static const char PRODUCT_BOOTANIMATION_DARK_FILE[] = "/product/media/bootanimation-dark.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090072static const char PRODUCT_BOOTANIMATION_FILE[] = "/product/media/bootanimation.zip";
Damien Bargiacchi97480862016-03-29 14:55:55 -070073static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
Anders Fridlunde0b4d232018-11-06 14:23:25 +010074static const char APEX_BOOTANIMATION_FILE[] = "/apex/com.android.bootanimation/etc/bootanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090075static const char PRODUCT_ENCRYPTED_BOOTANIMATION_FILE[] = "/product/media/bootanimation-encrypted.zip";
Damien Bargiacchi97480862016-03-29 14:55:55 -070076static const char SYSTEM_ENCRYPTED_BOOTANIMATION_FILE[] = "/system/media/bootanimation-encrypted.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070077static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
Jaekyun Seokc521bb32018-01-30 11:52:47 +090078static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
Keun-young Parkb5938422017-03-23 13:46:24 -070079static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
80
Nikita Ioffe06c986e2020-01-27 17:16:03 +000081static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
82static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
83static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
84
Damien Bargiacchi97480862016-03-29 14:55:55 -070085static const char SYSTEM_DATA_DIR_PATH[] = "/data/system";
86static const char SYSTEM_TIME_DIR_NAME[] = "time";
87static const char SYSTEM_TIME_DIR_PATH[] = "/data/system/time";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070088static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
89static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +000090static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
91static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
Damien Bargiacchi97480862016-03-29 14:55:55 -070092static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
93static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/system/time/last_time_change";
94static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
95static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/system/time/time_is_accurate";
Damien Bargiacchi9071db12016-10-28 17:38:22 -070096static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/system/time/time_format_12_hour";
Damien Bargiacchi96762812016-07-12 15:53:40 -070097// Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
98static const long long ACCURATE_TIME_EPOCH = 946684800000;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -070099static constexpr char FONT_BEGIN_CHAR = ' ';
100static constexpr char FONT_END_CHAR = '~' + 1;
101static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
102static constexpr size_t FONT_NUM_COLS = 16;
103static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
104static const int TEXT_CENTER_VALUE = INT_MAX;
105static const int TEXT_MISSING_VALUE = INT_MIN;
Damien Bargiacchi97480862016-03-29 14:55:55 -0700106static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000107static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
Huihong Luod4a217e2020-01-16 15:56:33 -0800108static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
Kyeongkab.Nam35a8a112019-07-17 16:41:48 +0900109static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700110static constexpr size_t TEXT_POS_LEN_MAX = 16;
Narayan Kamathafd31e02013-12-03 13:16:03 +0000111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112// ---------------------------------------------------------------------------
113
Ed Coyne7464ac92017-06-08 12:26:48 -0700114BootAnimation::BootAnimation(sp<Callbacks> callbacks)
Marin Shalamanov9070c052020-05-18 19:05:17 +0200115 : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
Yi Kong911ac232019-03-24 01:49:02 -0700116 mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
Mathias Agopian627e7b52009-05-21 19:21:59 -0700117 mSession = new SurfaceComposerClient();
Geoffrey Pitsch290c4352016-08-09 14:35:10 -0400118
Keun-young Parkb5938422017-03-23 13:46:24 -0700119 std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
120 if (powerCtl.empty()) {
121 mShuttingDown = false;
122 } else {
123 mShuttingDown = true;
124 }
Huihong Luo50a2f362018-08-11 09:27:57 -0700125 ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
126 elapsedRealtime());
127}
128
129BootAnimation::~BootAnimation() {
130 if (mAnimation != nullptr) {
131 releaseAnimation(mAnimation);
132 mAnimation = nullptr;
133 }
134 ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
135 elapsedRealtime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136}
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138void BootAnimation::onFirstRef() {
Mathias Agopianbc726112009-09-23 15:44:05 -0700139 status_t err = mSession->linkToComposerDeath(this);
Wei Wang159a4102018-10-23 23:15:58 -0700140 SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
Mathias Agopian8434c532009-09-23 18:52:49 -0700141 if (err == NO_ERROR) {
Huihong Luo50a2f362018-08-11 09:27:57 -0700142 // Load the animation content -- this can be slow (eg 200ms)
143 // called before waitForSurfaceFlinger() in main() to avoid wait
144 ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
145 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
146 preloadAnimation();
147 ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
148 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
Mathias Agopianbc726112009-09-23 15:44:05 -0700149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150}
151
Mathias Agopianbc726112009-09-23 15:44:05 -0700152sp<SurfaceComposerClient> BootAnimation::session() const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 return mSession;
154}
155
Marin Shalamanov9070c052020-05-18 19:05:17 +0200156void BootAnimation::binderDied(const wp<IBinder>&) {
Mathias Agopianbc726112009-09-23 15:44:05 -0700157 // woah, surfaceflinger died!
Wei Wang159a4102018-10-23 23:15:58 -0700158 SLOGD("SurfaceFlinger died, exiting...");
Mathias Agopianbc726112009-09-23 15:44:05 -0700159
160 // calling requestExit() is not enough here because the Surface code
161 // might be blocked on a condition variable that will never be updated.
162 kill( getpid(), SIGKILL );
163 requestExit();
164}
165
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400166static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo) {
167 AImageDecoder* decoder = nullptr;
168 AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
169 if (!decoder) {
170 return nullptr;
171 }
172
173 const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
174 outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
175 outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
176 outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
177 outInfo->stride = AImageDecoder_getMinimumStride(decoder);
178 outInfo->flags = 0;
179
180 const size_t size = outInfo->stride * outInfo->height;
181 void* pixels = malloc(size);
182 int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
183 AImageDecoder_delete(decoder);
184
185 if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
186 free(pixels);
187 return nullptr;
188 }
189 return pixels;
190}
191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
193 const char* name) {
194 Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
Yi Kong911ac232019-03-24 01:49:02 -0700195 if (asset == nullptr)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 return NO_INIT;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400197
198 AndroidBitmapInfo bitmapInfo;
199 void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo);
200 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 asset->close();
203 delete asset;
204
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400205 if (!pixels) {
206 return NO_INIT;
207 }
208
209 const int w = bitmapInfo.width;
210 const int h = bitmapInfo.height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
Greg Kaiser2ded8002021-07-19 17:03:27 +0000212 GLint crop[4] = { 0, h, w, -h };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 texture->w = w;
214 texture->h = h;
215
216 glGenTextures(1, &texture->name);
217 glBindTexture(GL_TEXTURE_2D, texture->name);
218
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400219 switch (bitmapInfo.format) {
220 case ANDROID_BITMAP_FORMAT_A_8:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400222 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400224 case ANDROID_BITMAP_FORMAT_RGBA_4444:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400226 GL_UNSIGNED_SHORT_4_4_4_4, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400228 case ANDROID_BITMAP_FORMAT_RGBA_8888:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400230 GL_UNSIGNED_BYTE, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 break;
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400232 case ANDROID_BITMAP_FORMAT_RGB_565:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400234 GL_UNSIGNED_SHORT_5_6_5, pixels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 break;
236 default:
237 break;
238 }
239
Greg Kaiser2ded8002021-07-19 17:03:27 +0000240 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
241 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
242 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
243 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
244 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 return NO_ERROR;
247}
248
Marin Shalamanov9070c052020-05-18 19:05:17 +0200249status_t BootAnimation::initTexture(FileMap* map, int* width, int* height) {
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400250 AndroidBitmapInfo bitmapInfo;
251 void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo);
252 auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700253
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200254 // FileMap memory is never released until application exit.
255 // Release it now as the texture is already loaded and the memory used for
256 // the packed resource can be released.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700257 delete map;
Mykola Kondratenko0c1eeb32014-04-15 09:35:44 +0200258
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400259 if (!pixels) {
260 return NO_INIT;
261 }
262
263 const int w = bitmapInfo.width;
264 const int h = bitmapInfo.height;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700265
Greg Kaiser2ded8002021-07-19 17:03:27 +0000266 GLint crop[4] = { 0, h, w, -h };
Mathias Agopiana8826d62009-10-01 03:10:14 -0700267 int tw = 1 << (31 - __builtin_clz(w));
268 int th = 1 << (31 - __builtin_clz(h));
269 if (tw < w) tw <<= 1;
270 if (th < h) th <<= 1;
271
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400272 switch (bitmapInfo.format) {
273 case ANDROID_BITMAP_FORMAT_RGBA_8888:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530274 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700275 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
Yi Kong911ac232019-03-24 01:49:02 -0700276 GL_UNSIGNED_BYTE, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700277 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400278 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700279 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530280 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400281 GL_UNSIGNED_BYTE, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700282 }
283 break;
284
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400285 case ANDROID_BITMAP_FORMAT_RGB_565:
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530286 if (!mUseNpotTextures && (tw != w || th != h)) {
Mathias Agopiana8826d62009-10-01 03:10:14 -0700287 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
Yi Kong911ac232019-03-24 01:49:02 -0700288 GL_UNSIGNED_SHORT_5_6_5, nullptr);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700289 glTexSubImage2D(GL_TEXTURE_2D, 0,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400290 0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700291 } else {
Sai Kiran Korwar27167492015-07-07 20:00:06 +0530292 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
Derek Sollenberger22d0d4c72020-04-08 10:53:46 -0400293 GL_UNSIGNED_SHORT_5_6_5, pixels);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700294 }
295 break;
296 default:
297 break;
298 }
299
Greg Kaiser2ded8002021-07-19 17:03:27 +0000300 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700301
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700302 *width = w;
303 *height = h;
304
Mathias Agopiana8826d62009-10-01 03:10:14 -0700305 return NO_ERROR;
306}
307
Marin Shalamanov9070c052020-05-18 19:05:17 +0200308class BootAnimation::DisplayEventCallback : public LooperCallback {
309 BootAnimation* mBootAnimation;
310
311public:
312 DisplayEventCallback(BootAnimation* bootAnimation) {
313 mBootAnimation = bootAnimation;
314 }
315
316 int handleEvent(int /* fd */, int events, void* /* data */) {
317 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
318 ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
319 events);
320 return 0; // remove the callback
321 }
322
323 if (!(events & Looper::EVENT_INPUT)) {
324 ALOGW("Received spurious callback for unhandled poll event. events=0x%x", events);
325 return 1; // keep the callback
326 }
327
328 constexpr int kBufferSize = 100;
329 DisplayEventReceiver::Event buffer[kBufferSize];
330 ssize_t numEvents;
331 do {
332 numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
333 for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
334 const auto& event = buffer[i];
335 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
336 SLOGV("Hotplug received");
337
338 if (!event.hotplug.connected) {
339 // ignore hotplug disconnect
340 continue;
341 }
342 auto token = SurfaceComposerClient::getPhysicalDisplayToken(
343 event.header.displayId);
344
345 if (token != mBootAnimation->mDisplayToken) {
346 // ignore hotplug of a secondary display
347 continue;
348 }
349
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100350 DisplayMode displayMode;
351 const status_t error = SurfaceComposerClient::getActiveDisplayMode(
352 mBootAnimation->mDisplayToken, &displayMode);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200353 if (error != NO_ERROR) {
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100354 SLOGE("Can't get active display mode.");
Marin Shalamanov9070c052020-05-18 19:05:17 +0200355 }
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100356 mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
357 displayMode.resolution.getHeight());
Marin Shalamanov9070c052020-05-18 19:05:17 +0200358 }
359 }
360 } while (numEvents > 0);
361
362 return 1; // keep the callback
363 }
364};
365
366EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
367 const EGLint attribs[] = {
368 EGL_RED_SIZE, 8,
369 EGL_GREEN_SIZE, 8,
370 EGL_BLUE_SIZE, 8,
371 EGL_DEPTH_SIZE, 0,
372 EGL_NONE
373 };
374 EGLint numConfigs;
375 EGLConfig config;
376 eglChooseConfig(display, attribs, &config, 1, &numConfigs);
377 return config;
378}
379
Marin Shalamanov047802d2020-05-19 23:55:12 +0200380ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
381 ui::Size limited(width, height);
382 bool wasLimited = false;
383 const float aspectRatio = float(width) / float(height);
384 if (mMaxWidth != 0 && width > mMaxWidth) {
385 limited.height = mMaxWidth / aspectRatio;
386 limited.width = mMaxWidth;
387 wasLimited = true;
388 }
389 if (mMaxHeight != 0 && limited.height > mMaxHeight) {
390 limited.height = mMaxHeight;
391 limited.width = mMaxHeight * aspectRatio;
392 wasLimited = true;
393 }
394 SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
395 limited.width, limited.height, width, height);
396 return limited;
397}
398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399status_t BootAnimation::readyToRun() {
400 mAssets.addDefaultAssets();
401
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800402 mDisplayToken = SurfaceComposerClient::getInternalDisplayToken();
403 if (mDisplayToken == nullptr)
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800404 return NAME_NOT_FOUND;
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800405
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100406 DisplayMode displayMode;
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800407 const status_t error =
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100408 SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800409 if (error != NO_ERROR)
410 return error;
411
Marin Shalamanov047802d2020-05-19 23:55:12 +0200412 mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
413 mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
Marin Shalamanovcb783ca2021-01-29 21:26:07 +0100414 ui::Size resolution = displayMode.resolution;
Marin Shalamanov047802d2020-05-19 23:55:12 +0200415 resolution = limitSurfaceSize(resolution.width, resolution.height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 // create the native surface
Jeff Brown0b722fe2012-08-24 22:40:14 -0700417 sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
Dominik Laskowski69b281d2019-11-22 14:13:12 -0800418 resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565);
Mathias Agopian439863f2011-06-28 19:09:31 -0700419
Robert Carre13b58e2017-08-31 14:50:44 -0700420 SurfaceComposerClient::Transaction t;
Huihong Luof97c9e22019-05-29 11:08:01 -0700421
422 // this guest property specifies multi-display IDs to show the boot animation
423 // multiple ids can be set with comma (,) as separator, for example:
Huihong Luod4a217e2020-01-16 15:56:33 -0800424 // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200425 Vector<PhysicalDisplayId> physicalDisplayIds;
Huihong Luof97c9e22019-05-29 11:08:01 -0700426 char displayValue[PROPERTY_VALUE_MAX] = "";
Huihong Luod4a217e2020-01-16 15:56:33 -0800427 property_get(DISPLAYS_PROP_NAME, displayValue, "");
Huihong Luof97c9e22019-05-29 11:08:01 -0700428 bool isValid = displayValue[0] != '\0';
429 if (isValid) {
430 char *p = displayValue;
431 while (*p) {
432 if (!isdigit(*p) && *p != ',') {
433 isValid = false;
434 break;
435 }
436 p ++;
437 }
438 if (!isValid)
Huihong Luod4a217e2020-01-16 15:56:33 -0800439 SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
Huihong Luof97c9e22019-05-29 11:08:01 -0700440 }
441 if (isValid) {
442 std::istringstream stream(displayValue);
Marin Shalamanov11599ee2020-07-27 21:31:48 +0200443 for (PhysicalDisplayId id; stream >> id.value; ) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700444 physicalDisplayIds.add(id);
445 if (stream.peek() == ',')
446 stream.ignore();
447 }
448
449 // In the case of multi-display, boot animation shows on the specified displays
450 // in addition to the primary display
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700451 const auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
452 for (const auto id : physicalDisplayIds) {
Huihong Luof97c9e22019-05-29 11:08:01 -0700453 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700454 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
455 t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
456 }
Huihong Luof97c9e22019-05-29 11:08:01 -0700457 }
458 }
Dominik Laskowski989de3d2021-07-27 21:09:34 -0700459 t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
Huihong Luof97c9e22019-05-29 11:08:01 -0700460 }
461
Robert Carre13b58e2017-08-31 14:50:44 -0700462 t.setLayer(control, 0x40000000)
463 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464
Mathias Agopian17f638b2009-04-16 20:04:08 -0700465 sp<Surface> s = control->getSurface();
466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700469 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200470 EGLConfig config = getEglConfig(display);
471 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
Greg Kaiser2ded8002021-07-19 17:03:27 +0000472 EGLContext context = eglCreateContext(display, config, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200473 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 eglQuerySurface(display, surface, EGL_WIDTH, &w);
475 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700476
Mathias Agopianabac0102009-07-31 14:47:00 -0700477 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
478 return NO_INIT;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mDisplay = display;
481 mContext = context;
482 mSurface = surface;
483 mWidth = w;
484 mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700485 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200487 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200489 projectSceneToWindow();
490
Marin Shalamanov9070c052020-05-18 19:05:17 +0200491 // Register a display event receiver
492 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
493 status_t status = mDisplayEventReceiver->initCheck();
494 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
495 status);
496 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
497 new DisplayEventCallback(this), nullptr);
498
Huihong Luo50a2f362018-08-11 09:27:57 -0700499 return NO_ERROR;
500}
501
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200502void BootAnimation::projectSceneToWindow() {
503 glViewport(0, 0, mWidth, mHeight);
504 glScissor(0, 0, mWidth, mHeight);
Greg Kaiser2ded8002021-07-19 17:03:27 +0000505 glMatrixMode(GL_PROJECTION);
506 glLoadIdentity();
507 glOrthof(0, static_cast<float>(mWidth), 0, static_cast<float>(mHeight), -1, 1);
508 glMatrixMode(GL_MODELVIEW);
509 glLoadIdentity();
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200510}
511
Marin Shalamanov9070c052020-05-18 19:05:17 +0200512void BootAnimation::resizeSurface(int newWidth, int newHeight) {
513 // We assume this function is called on the animation thread.
514 if (newWidth == mWidth && newHeight == mHeight) {
515 return;
516 }
517 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
518
519 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
520 eglDestroySurface(mDisplay, mSurface);
521
Marin Shalamanov047802d2020-05-19 23:55:12 +0200522 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
523 mWidth = limitedSize.width;
524 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200525
526 SurfaceComposerClient::Transaction t;
527 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
528 t.apply();
529
530 EGLConfig config = getEglConfig(mDisplay);
531 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
532 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
533 SLOGE("Can't make the new surface current. Error %d", eglGetError());
534 return;
535 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200536
537 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200538
539 mSurface = surface;
540}
541
Huihong Luo50a2f362018-08-11 09:27:57 -0700542bool BootAnimation::preloadAnimation() {
543 findBootAnimationFile();
544 if (!mZipFileName.isEmpty()) {
545 mAnimation = loadAnimation(mZipFileName);
546 return (mAnimation != nullptr);
547 }
548
549 return false;
550}
551
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000552bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
553 for (const std::string& f : files) {
554 if (access(f.c_str(), R_OK) == 0) {
555 mZipFileName = f.c_str();
556 return true;
557 }
558 }
559 return false;
560}
561
Huihong Luo50a2f362018-08-11 09:27:57 -0700562void BootAnimation::findBootAnimationFile() {
Elliott Hughesc367d482013-10-29 13:12:55 -0700563 // If the device has encryption turned on or is in process
Jason parksbd9a08d2011-01-31 15:04:34 -0600564 // of being encrypted we show the encrypted boot animation.
565 char decrypt[PROPERTY_VALUE_MAX];
566 property_get("vold.decrypt", decrypt, "");
567
Keun-young Parkb5938422017-03-23 13:46:24 -0700568 bool encryptedAnimation = atoi(decrypt) != 0 ||
569 !strcmp("trigger_restart_min_framework", decrypt);
Jason parksbd9a08d2011-01-31 15:04:34 -0600570
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900571 if (!mShuttingDown && encryptedAnimation) {
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000572 static const std::vector<std::string> encryptedBootFiles = {
573 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
574 };
575 if (findBootAnimationFileInternal(encryptedBootFiles)) {
576 return;
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900577 }
Jason parksbd9a08d2011-01-31 15:04:34 -0600578 }
Beverly34ffe252019-05-17 11:03:54 -0400579
580 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000581 static const std::vector<std::string> bootFiles = {
582 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
583 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
584 };
585 static const std::vector<std::string> shutdownFiles = {
586 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
587 };
588 static const std::vector<std::string> userspaceRebootFiles = {
589 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
590 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
591 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700592
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000593 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
594 findBootAnimationFileInternal(userspaceRebootFiles);
595 } else if (mShuttingDown) {
596 findBootAnimationFileInternal(shutdownFiles);
597 } else {
598 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600}
601
Marin Shalamanov9070c052020-05-18 19:05:17 +0200602bool BootAnimation::threadLoop() {
603 bool result;
Narayan Kamathafd31e02013-12-03 13:16:03 +0000604 // We have no bootanimation file, so we use the stock android logo
605 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700606 if (mZipFileName.isEmpty()) {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200607 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700608 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200609 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700610 }
611
Philip Junker60600562020-11-25 18:16:16 +0100612 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
614 eglDestroyContext(mDisplay, mContext);
615 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700616 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700617 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700618 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530619 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700620 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200621 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622}
623
Marin Shalamanov9070c052020-05-18 19:05:17 +0200624bool BootAnimation::android() {
Wei Wang159a4102018-10-23 23:15:58 -0700625 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700626 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700627 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
628 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629
Ed Coyne7464ac92017-06-08 12:26:48 -0700630 mCallbacks->init({});
631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 // clear screen
Greg Kaiser2ded8002021-07-19 17:03:27 +0000633 glShadeModel(GL_FLAT);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700634 glDisable(GL_DITHER);
635 glDisable(GL_SCISSOR_TEST);
Mathias Agopian59f19e42011-05-06 19:22:12 -0700636 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 glClear(GL_COLOR_BUFFER_BIT);
638 eglSwapBuffers(mDisplay, mSurface);
639
Greg Kaiser2ded8002021-07-19 17:03:27 +0000640 glEnable(GL_TEXTURE_2D);
641 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
642
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700643 // Blend state
644 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Greg Kaiser2ded8002021-07-19 17:03:27 +0000645 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 const nsecs_t startTime = systemTime();
648 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200649 processDisplayEvents();
650 const GLint xc = (mWidth - mAndroid[0].w) / 2;
651 const GLint yc = (mHeight - mAndroid[0].h) / 2;
652 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
653 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
654 updateRect.height());
655
Mathias Agopian13796652009-03-24 22:49:21 -0700656 nsecs_t now = systemTime();
657 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700658 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
659 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
660 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661
Mathias Agopian81668642009-07-28 11:41:30 -0700662 glDisable(GL_SCISSOR_TEST);
663 glClear(GL_COLOR_BUFFER_BIT);
664
665 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Greg Kaiser2ded8002021-07-19 17:03:27 +0000668 glDrawTexiOES(x, yc, 0, mAndroid[1].w, mAndroid[1].h);
669 glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700671 glEnable(GL_BLEND);
672 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
Greg Kaiser2ded8002021-07-19 17:03:27 +0000673 glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674
Mathias Agopian627e7b52009-05-21 19:21:59 -0700675 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
676 if (res == EGL_FALSE)
677 break;
678
Mathias Agopian13796652009-03-24 22:49:21 -0700679 // 12fps: don't animate too fast to preserve CPU
680 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
681 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700682 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700683
684 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 } while (!exitPending());
686
687 glDeleteTextures(1, &mAndroid[0].name);
688 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 return false;
690}
691
Kevin Hesterd3782b22012-04-26 10:38:55 -0700692void BootAnimation::checkExit() {
693 // Allow surface flinger to gracefully request shutdown
694 char value[PROPERTY_VALUE_MAX];
695 property_get(EXIT_PROP_NAME, value, "0");
696 int exitnow = atoi(value);
697 if (exitnow) {
698 requestExit();
699 }
700}
701
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700702bool BootAnimation::validClock(const Animation::Part& part) {
703 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
704}
705
706bool parseTextCoord(const char* str, int* dest) {
707 if (strcmp("c", str) == 0) {
708 *dest = TEXT_CENTER_VALUE;
709 return true;
710 }
711
712 char* end;
713 int val = (int) strtol(str, &end, 0);
714 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
715 return false;
716 }
717 *dest = val;
718 return true;
719}
720
721// Parse two position coordinates. If only string is non-empty, treat it as the y value.
722void parsePosition(const char* str1, const char* str2, int* x, int* y) {
723 bool success = false;
724 if (strlen(str1) == 0) { // No values were specified
725 // success = false
726 } else if (strlen(str2) == 0) { // we have only one value
727 if (parseTextCoord(str1, y)) {
728 *x = TEXT_CENTER_VALUE;
729 success = true;
730 }
731 } else {
732 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
733 success = true;
734 }
735 }
736
737 if (!success) {
738 *x = TEXT_MISSING_VALUE;
739 *y = TEXT_MISSING_VALUE;
740 }
741}
742
Jesse Hall083b84c2014-09-22 10:51:09 -0700743// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
744// characters in str is a hex number in [0, 255], which are converted to
745// floating point values in the range [0.0, 1.0] and placed in the
746// corresponding elements of color.
747//
748// If the input string isn't valid, parseColor returns false and color is
749// left unchanged.
750static bool parseColor(const char str[7], float color[3]) {
751 float tmpColor[3];
752 for (int i = 0; i < 3; i++) {
753 int val = 0;
754 for (int j = 0; j < 2; j++) {
755 val *= 16;
756 char c = str[2*i + j];
757 if (c >= '0' && c <= '9') val += c - '0';
758 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
759 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
760 else return false;
761 }
762 tmpColor[i] = static_cast<float>(val) / 255.0f;
763 }
764 memcpy(color, tmpColor, sizeof(tmpColor));
765 return true;
766}
767
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700768
Marin Shalamanov9070c052020-05-18 19:05:17 +0200769static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700770 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -0700771 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700772 if (!entry) {
773 return false;
774 }
775
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700776 FileMap* entryMap = zip->createEntryFileMap(entry);
777 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -0700778 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700779 if (!entryMap) {
780 return false;
781 }
782
783 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +0000784 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700785 return true;
786}
787
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700788// The font image should be a 96x2 array of character images. The
789// columns are the printable ASCII characters 0x20 - 0x7f. The
790// top row is regular text; the bottom row is bold.
791status_t BootAnimation::initFont(Font* font, const char* fallback) {
792 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800793
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700794 if (font->map != nullptr) {
795 glGenTextures(1, &font->texture.name);
796 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800797
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700798 status = initTexture(font->map, &font->texture.w, &font->texture.h);
799
Greg Kaiser2ded8002021-07-19 17:03:27 +0000800 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
801 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
802 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
803 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700804 } else if (fallback != nullptr) {
805 status = initTexture(&font->texture, mAssets, fallback);
806 } else {
807 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800808 }
809
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700810 if (status == NO_ERROR) {
811 font->char_width = font->texture.w / FONT_NUM_COLS;
812 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
813 }
814
815 return status;
816}
817
Greg Kaiser2ded8002021-07-19 17:03:27 +0000818void BootAnimation::fadeFrame(const int frameLeft, const int frameBottom, const int frameWidth,
819 const int frameHeight, const Animation::Part& part,
820 const int fadedFramesCount) {
821 glEnable(GL_BLEND);
822 glEnableClientState(GL_VERTEX_ARRAY);
823 glDisable(GL_TEXTURE_2D);
824 // avoid creating a hole due to mixing result alpha with GL_REPLACE texture
825 glBlendFuncSeparateOES(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
826
827 const float alpha = static_cast<float>(fadedFramesCount) / part.framesToFadeCount;
828 glColor4f(part.backgroundColor[0], part.backgroundColor[1], part.backgroundColor[2], alpha);
829
830 const float frameStartX = static_cast<float>(frameLeft);
831 const float frameStartY = static_cast<float>(frameBottom);
832 const float frameEndX = frameStartX + frameWidth;
833 const float frameEndY = frameStartY + frameHeight;
834 const GLfloat frameRect[] = {
835 frameStartX, frameStartY,
836 frameEndX, frameStartY,
837 frameEndX, frameEndY,
838 frameStartX, frameEndY
839 };
840 glVertexPointer(2, GL_FLOAT, 0, frameRect);
841 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
842
843 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
844 glEnable(GL_TEXTURE_2D);
845 glDisableClientState(GL_VERTEX_ARRAY);
846 glDisable(GL_BLEND);
847}
848
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700849void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
850 glEnable(GL_BLEND); // Allow us to draw on top of the animation
851 glBindTexture(GL_TEXTURE_2D, font.texture.name);
852
853 const int len = strlen(str);
854 const int strWidth = font.char_width * len;
855
856 if (*x == TEXT_CENTER_VALUE) {
857 *x = (mWidth - strWidth) / 2;
858 } else if (*x < 0) {
859 *x = mWidth + *x - strWidth;
860 }
861 if (*y == TEXT_CENTER_VALUE) {
862 *y = (mHeight - font.char_height) / 2;
863 } else if (*y < 0) {
864 *y = mHeight + *y - font.char_height;
865 }
866
Greg Kaiser2ded8002021-07-19 17:03:27 +0000867 int cropRect[4] = { 0, 0, font.char_width, -font.char_height };
868
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700869 for (int i = 0; i < len; i++) {
870 char c = str[i];
871
872 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
873 c = '?';
874 }
875
876 // Crop the texture to only the pixels in the current glyph
877 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
878 const int row = charPos / FONT_NUM_COLS;
879 const int col = charPos % FONT_NUM_COLS;
Greg Kaiser2ded8002021-07-19 17:03:27 +0000880 cropRect[0] = col * font.char_width; // Left of column
881 cropRect[1] = row * font.char_height * 2; // Top of row
882 // Move down to bottom of regular (one char_heigh) or bold (two char_heigh) line
883 cropRect[1] += bold ? 2 * font.char_height : font.char_height;
884 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
885
886 glDrawTexiOES(*x, *y, 0, font.char_width, font.char_height);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700887
888 *x += font.char_width;
889 }
890
891 glDisable(GL_BLEND); // Return to the animation's default behaviour
892 glBindTexture(GL_TEXTURE_2D, 0);
893}
894
Damien Bargiacchi9071db12016-10-28 17:38:22 -0700895// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700896void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -0700897 static constexpr char TIME_FORMAT_12[] = "%l:%M";
898 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700899 static constexpr int TIME_LENGTH = 6;
900
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800901 time_t rawtime;
902 time(&rawtime);
903 struct tm* timeInfo = localtime(&rawtime);
904
905 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -0700906 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
907 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800908
909 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -0700910 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800911 mClockEnabled = false;
912 return;
913 }
914
Damien Bargiacchi45a76442016-12-05 18:02:18 -0800915 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700916 int x = xPos;
917 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -0800918 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800919}
920
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000921void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
922 static constexpr int PERCENT_LENGTH = 5;
923
924 char percentBuff[PERCENT_LENGTH];
925 // ';' has the ascii code just after ':', and the font resource contains '%'
926 // for that ascii code.
927 sprintf(percentBuff, "%d;", percent);
928 int x = xPos;
929 int y = yPos;
930 drawText(percentBuff, font, false, &x, &y);
931}
932
Marin Shalamanov9070c052020-05-18 19:05:17 +0200933bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700934 String8 desString;
935
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700936 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +0000937 return false;
938 }
Mathias Agopiana8826d62009-10-01 03:10:14 -0700939 char const* s = desString.string();
940
Mathias Agopiana8826d62009-10-01 03:10:14 -0700941 // Parse the description file
942 for (;;) {
943 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -0700944 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700945 String8 line(s, endl - s);
946 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800947 int fps = 0;
948 int width = 0;
949 int height = 0;
950 int count = 0;
951 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000952 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200953 int framesToFadeCount = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +0000954 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -0700955 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700956 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
957 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Kevin Hesterd3782b22012-04-26 10:38:55 -0700958 char pathType;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200959
960 int nextReadPos;
961
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000962 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
963 if (topLineNumbers == 3 || topLineNumbers == 4) {
964 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700965 animation.width = width;
966 animation.height = height;
967 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000968 if (topLineNumbers == 4) {
969 animation.progressEnabled = (progress != 0);
970 } else {
971 animation.progressEnabled = false;
972 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200973 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
974 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
975 if (pathType == 'f') {
976 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
977 clockPos2);
978 } else {
979 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
980 }
981 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
982 // "clockPos1=%s, clockPos2=%s",
983 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700984 Animation::Part part;
Kevin Hesterd3782b22012-04-26 10:38:55 -0700985 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200986 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700987 part.count = count;
988 part.pause = pause;
989 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -0700990 part.audioData = nullptr;
991 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -0700992 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -0700993 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -0700994 part.backgroundColor[0] = 0.0f;
995 part.backgroundColor[1] = 0.0f;
996 part.backgroundColor[2] = 0.0f;
997 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700998 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700999 animation.parts.add(part);
1000 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001001 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001002 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001003 Animation::Part part;
1004 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001005 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001006 part.count = 1;
1007 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001008 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001009 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001010 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001011 animation.parts.add(part);
1012 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001013 s = ++endl;
1014 }
1015
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001016 return true;
1017}
1018
Marin Shalamanov9070c052020-05-18 19:05:17 +02001019bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001020 // read all the data structures
1021 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001022 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001023 ZipFileRO* zip = animation.zip;
1024 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001025 return false;
1026 }
1027
1028 ZipEntryRO entry;
1029 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001030 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001031 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001032 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001033 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001034 continue;
1035 }
1036
1037 const String8 entryName(name);
1038 const String8 path(entryName.getPathDir());
1039 const String8 leaf(entryName.getPathLeaf());
1040 if (leaf.size() > 0) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001041 if (entryName == CLOCK_FONT_ZIP_NAME) {
1042 FileMap* map = zip->createEntryFileMap(entry);
1043 if (map) {
1044 animation.clockFont.map = map;
1045 }
1046 continue;
1047 }
1048
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001049 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1050 FileMap* map = zip->createEntryFileMap(entry);
1051 if (map) {
1052 animation.progressFont.map = map;
1053 }
1054 continue;
1055 }
1056
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001057 for (size_t j = 0; j < pcount; j++) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001058 if (path == animation.parts[j].path) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001059 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001060 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001061 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001062 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001063 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001064 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001065 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001066 if (leaf == "audio.wav") {
1067 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001068 part.audioData = (uint8_t *)map->getDataPtr();
1069 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001070 } else if (leaf == "trim.txt") {
1071 part.trimData.setTo((char const*)map->getDataPtr(),
1072 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001073 } else {
1074 Animation::Frame frame;
1075 frame.name = leaf;
1076 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001077 frame.trimWidth = animation.width;
1078 frame.trimHeight = animation.height;
1079 frame.trimX = 0;
1080 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001081 part.frames.add(frame);
1082 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001083 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001084 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001085 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001086 }
1087 }
1088 }
1089 }
1090 }
1091 }
1092
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001093 // If there is trimData present, override the positioning defaults.
1094 for (Animation::Part& part : animation.parts) {
1095 const char* trimDataStr = part.trimData.string();
1096 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1097 const char* endl = strstr(trimDataStr, "\n");
1098 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001099 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001100 break;
1101 }
1102 String8 line(trimDataStr, endl - trimDataStr);
1103 const char* lineStr = line.string();
1104 trimDataStr = ++endl;
1105 int width = 0, height = 0, x = 0, y = 0;
1106 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1107 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1108 frame.trimWidth = width;
1109 frame.trimHeight = height;
1110 frame.trimX = x;
1111 frame.trimY = y;
1112 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001113 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001114 break;
1115 }
1116 }
1117 }
1118
1119 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001120
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001121 return true;
1122}
1123
Marin Shalamanov9070c052020-05-18 19:05:17 +02001124bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001125 if (mAnimation == nullptr) {
1126 mAnimation = loadAnimation(mZipFileName);
1127 }
1128
1129 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001130 return false;
1131
Huihong Luo50a2f362018-08-11 09:27:57 -07001132 // mCallbacks->init() may get called recursively,
1133 // this loop is needed to get the same results
1134 for (const Animation::Part& part : mAnimation->parts) {
1135 if (part.animation != nullptr) {
1136 mCallbacks->init(part.animation->parts);
1137 }
1138 }
1139 mCallbacks->init(mAnimation->parts);
1140
Damien Bargiacchi97480862016-03-29 14:55:55 -07001141 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001142 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1143 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001144 anyPartHasClock = true;
1145 break;
1146 }
1147 }
1148 if (!anyPartHasClock) {
1149 mClockEnabled = false;
1150 }
1151
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301152 // Check if npot textures are supported
1153 mUseNpotTextures = false;
1154 String8 gl_extensions;
1155 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1156 if (!exts) {
1157 glGetError();
1158 } else {
1159 gl_extensions.setTo(exts);
1160 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1161 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1162 mUseNpotTextures = true;
1163 }
1164 }
1165
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001166 // Blend required to draw time on top of animation frames.
1167 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Greg Kaiser2ded8002021-07-19 17:03:27 +00001168 glShadeModel(GL_FLAT);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001169 glDisable(GL_DITHER);
1170 glDisable(GL_SCISSOR_TEST);
1171 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001172
Shan Huangd711ac42021-07-13 18:36:57 +08001173 glBindTexture(GL_TEXTURE_2D, 0);
Greg Kaiser2ded8002021-07-19 17:03:27 +00001174 glEnable(GL_TEXTURE_2D);
1175 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1176 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1177 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
1178 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1179 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1180
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001181 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001182 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001183 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001184 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001185 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001186 }
1187
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001188 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1189
Damien Bargiacchi97480862016-03-29 14:55:55 -07001190 if (mClockEnabled && !updateIsTimeAccurate()) {
1191 mTimeCheckThread = new TimeCheckThread(this);
1192 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1193 }
1194
Huihong Luo50a2f362018-08-11 09:27:57 -07001195 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001196
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001197 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001198 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001199 mTimeCheckThread = nullptr;
1200 }
1201
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001202 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001203 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001204 }
1205
Huihong Luo50a2f362018-08-11 09:27:57 -07001206 releaseAnimation(mAnimation);
1207 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001208
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001209 return false;
1210}
1211
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001212bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1213 const int fadedFramesCount,
1214 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001215 // 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 +01001216 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1217 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001218}
1219
Marin Shalamanov9070c052020-05-18 19:05:17 +02001220bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001221 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001222 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001223
Wei Wang159a4102018-10-23 23:15:58 -07001224 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001225 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001226
1227 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001228 int lastDisplayedProgress = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001229 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001230 const Animation::Part& part(animation.parts[i]);
1231 const size_t fcount = part.frames.size();
Greg Kaiser2ded8002021-07-19 17:03:27 +00001232 glBindTexture(GL_TEXTURE_2D, 0);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001233
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001234 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001235 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001236 playAnimation(*part.animation);
1237 if (exitPending())
1238 break;
1239 continue; //to next part
1240 }
1241
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001242 // process the part not only while the count allows but also if already fading
1243 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001244 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001245
Ed Coyne7464ac92017-06-08 12:26:48 -07001246 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001247
Jesse Hall083b84c2014-09-22 10:51:09 -07001248 glClearColor(
1249 part.backgroundColor[0],
1250 part.backgroundColor[1],
1251 part.backgroundColor[2],
1252 1.0f);
1253
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001254 // For the last animation, if we have progress indicator from
1255 // the system, display it.
1256 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1257 bool displayProgress = animation.progressEnabled &&
1258 (i == (pcount -1)) && currentProgress != 0;
1259
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001260 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001261 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001262
Marin Shalamanov9070c052020-05-18 19:05:17 +02001263 processDisplayEvents();
1264
1265 const int animationX = (mWidth - animation.width) / 2;
1266 const int animationY = (mHeight - animation.height) / 2;
1267
Mathias Agopiana8826d62009-10-01 03:10:14 -07001268 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001269 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001270
1271 if (r > 0) {
1272 glBindTexture(GL_TEXTURE_2D, frame.tid);
1273 } else {
Greg Kaiser2ded8002021-07-19 17:03:27 +00001274 if (part.count != 1) {
1275 glGenTextures(1, &frame.tid);
1276 glBindTexture(GL_TEXTURE_2D, frame.tid);
1277 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1278 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1279 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001280 int w, h;
1281 initTexture(frame.map, &w, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001282 }
1283
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001284 const int xc = animationX + frame.trimX;
1285 const int yc = animationY + frame.trimY;
1286 Region clearReg(Rect(mWidth, mHeight));
1287 clearReg.subtractSelf(Rect(xc, yc, xc+frame.trimWidth, yc+frame.trimHeight));
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001288 if (!clearReg.isEmpty()) {
1289 Region::const_iterator head(clearReg.begin());
1290 Region::const_iterator tail(clearReg.end());
1291 glEnable(GL_SCISSOR_TEST);
1292 while (head != tail) {
Andreas Gampecfedceb2014-09-30 21:48:18 -07001293 const Rect& r2(*head++);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001294 glScissor(r2.left, mHeight - r2.bottom, r2.width(), r2.height());
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001295 glClear(GL_COLOR_BUFFER_BIT);
1296 }
1297 glDisable(GL_SCISSOR_TEST);
1298 }
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001299 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1300 // which is equivalent to mHeight - (yc + frame.trimHeight)
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001301 const int frameDrawY = mHeight - (yc + frame.trimHeight);
Greg Kaiser2ded8002021-07-19 17:03:27 +00001302 glDrawTexiOES(xc, frameDrawY, 0, frame.trimWidth, frame.trimHeight);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001303
1304 // if the part hasn't been stopped yet then continue fading if necessary
1305 if (exitPending() && part.hasFadingPhase()) {
Greg Kaiser2ded8002021-07-19 17:03:27 +00001306 fadeFrame(xc, frameDrawY, frame.trimWidth, frame.trimHeight, part,
1307 ++fadedFramesCount);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001308 if (fadedFramesCount >= part.framesToFadeCount) {
1309 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1310 }
1311 }
1312
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001313 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1314 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001315 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001316
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001317 if (displayProgress) {
1318 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1319 // In case the new progress jumped suddenly, still show an
1320 // increment of 1.
1321 if (lastDisplayedProgress != 100) {
1322 // Artificially sleep 1/10th a second to slow down the animation.
1323 usleep(100000);
1324 if (lastDisplayedProgress < newProgress) {
1325 lastDisplayedProgress++;
1326 }
1327 }
1328 // Put the progress percentage right below the animation.
1329 int posY = animation.height / 3;
1330 int posX = TEXT_CENTER_VALUE;
1331 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1332 }
1333
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001334 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001335
Mathias Agopiana8826d62009-10-01 03:10:14 -07001336 eglSwapBuffers(mDisplay, mSurface);
1337
1338 nsecs_t now = systemTime();
1339 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001340 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001341 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001342
1343 if (delay > 0) {
1344 struct timespec spec;
1345 spec.tv_sec = (now + delay) / 1000000000;
1346 spec.tv_nsec = (now + delay) % 1000000000;
1347 int err;
1348 do {
Yi Kong911ac232019-03-24 01:49:02 -07001349 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001350 } while (err<0 && errno == EINTR);
1351 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001352
1353 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001354 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001355
Mathias Agopiana8826d62009-10-01 03:10:14 -07001356 usleep(part.pause * ns2us(frameDuration));
Kevin Hesterd3782b22012-04-26 10:38:55 -07001357
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001358 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1359 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001360 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1361 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1362 continue;
1363 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001364 break; // exit the infinite non-fading part when it has been played at least once
1365 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001366 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001367 }
1368
1369 // Free textures created for looping parts now that the animation is done.
1370 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001371 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001372 const size_t fcount = part.frames.size();
1373 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001374 const Animation::Frame& frame(part.frames[j]);
1375 glDeleteTextures(1, &frame.tid);
1376 }
1377 }
1378 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001379
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001380 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001381}
1382
Marin Shalamanov9070c052020-05-18 19:05:17 +02001383void BootAnimation::processDisplayEvents() {
1384 // This will poll mDisplayEventReceiver and if there are new events it'll call
1385 // displayEventCallback synchronously.
1386 mLooper->pollOnce(0);
1387}
1388
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001389void BootAnimation::handleViewport(nsecs_t timestep) {
1390 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1391 return;
1392 }
1393 if (mTargetInset < 0) {
1394 // Poll the amount for the top display inset. This will return -1 until persistent properties
1395 // have been loaded.
1396 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1397 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1398 }
1399 if (mTargetInset <= 0) {
1400 return;
1401 }
1402
1403 if (mCurrentInset < mTargetInset) {
1404 // After the device boots, the inset will effectively be cropped away. We animate this here.
1405 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1406 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1407
1408 SurfaceComposerClient::Transaction()
1409 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1410 .apply();
1411 } else {
1412 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1413 // later. This changes the coordinate system, and means we must move the surface up by
1414 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001415 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1416 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1417
1418 SurfaceComposerClient::Transaction t;
1419 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1420 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001421 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001422 t.apply();
1423
1424 mTargetInset = mCurrentInset = 0;
1425 }
1426
1427 int delta = timestep * mTargetInset / ms2ns(200);
1428 mCurrentInset += delta;
1429}
1430
Marin Shalamanov9070c052020-05-18 19:05:17 +02001431void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001432 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1433 e = animation->parts.end(); it != e; ++it) {
1434 if (it->animation)
1435 releaseAnimation(it->animation);
1436 }
1437 if (animation->zip)
1438 delete animation->zip;
1439 delete animation;
1440}
1441
Marin Shalamanov9070c052020-05-18 19:05:17 +02001442BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001443 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001444 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001445 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001446 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001447 }
1448 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001449 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001450 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001451 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001452 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001453 }
1454
1455 Animation *animation = new Animation;
1456 animation->fileName = fn;
1457 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001458 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001459 mLoadedFiles.add(animation->fileName);
1460
1461 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001462 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001463 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001464 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001465 }
1466
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001467 mLoadedFiles.remove(fn);
1468 return animation;
1469}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001470
1471bool BootAnimation::updateIsTimeAccurate() {
1472 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1473 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1474
1475 if (mTimeIsAccurate) {
1476 return true;
1477 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001478 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001479 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001480
1481 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1482 mTimeFormat12Hour = true;
1483 }
1484
Damien Bargiacchi97480862016-03-29 14:55:55 -07001485 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1486 mTimeIsAccurate = true;
1487 return true;
1488 }
1489
1490 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001491 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001492 long long lastChangedTime = 0;
1493 fscanf(file, "%lld", &lastChangedTime);
1494 fclose(file);
1495 if (lastChangedTime > 0) {
1496 struct timespec now;
1497 clock_gettime(CLOCK_REALTIME, &now);
1498 // Match the Java timestamp format
1499 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001500 if (ACCURATE_TIME_EPOCH < rtcNow
1501 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1502 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001503 mTimeIsAccurate = true;
1504 }
1505 }
1506 }
1507
1508 return mTimeIsAccurate;
1509}
1510
1511BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1512 mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1513
1514BootAnimation::TimeCheckThread::~TimeCheckThread() {
1515 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1516 close(mInotifyFd);
1517}
1518
1519bool BootAnimation::TimeCheckThread::threadLoop() {
1520 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1521 && mBootAnimation->mClockEnabled;
1522 if (!shouldLoop) {
1523 close(mInotifyFd);
1524 mInotifyFd = -1;
1525 }
1526 return shouldLoop;
1527}
1528
1529bool BootAnimation::TimeCheckThread::doThreadLoop() {
1530 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1531
1532 // Poll instead of doing a blocking read so the Thread can exit if requested.
1533 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1534 ssize_t pollResult = poll(&pfd, 1, 1000);
1535
1536 if (pollResult == 0) {
1537 return true;
1538 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001539 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001540 return false;
1541 }
1542
1543 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1544 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1545 if (length == 0) {
1546 return true;
1547 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001548 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001549 return false;
1550 }
1551
1552 const struct inotify_event *event;
1553 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1554 event = (const struct inotify_event *) ptr;
1555 if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
1556 addTimeDirWatch();
1557 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1558 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1559 return !mBootAnimation->updateIsTimeAccurate();
1560 }
1561 }
1562
1563 return true;
1564}
1565
1566void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1567 mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
1568 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1569 if (mTimeWd > 0) {
1570 // No need to watch for the time directory to be created if it already exists
1571 inotify_rm_watch(mInotifyFd, mSystemWd);
1572 mSystemWd = -1;
1573 }
1574}
1575
1576status_t BootAnimation::TimeCheckThread::readyToRun() {
1577 mInotifyFd = inotify_init();
1578 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001579 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001580 return NO_INIT;
1581 }
1582
1583 mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1584 if (mSystemWd < 0) {
1585 close(mInotifyFd);
1586 mInotifyFd = -1;
Dan Sandler562d46d2020-05-11 17:09:22 -04001587 SLOGE("Could not add watch for %s: %s", SYSTEM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001588 return NO_INIT;
1589 }
1590
1591 addTimeDirWatch();
1592
1593 if (mBootAnimation->updateIsTimeAccurate()) {
1594 close(mInotifyFd);
1595 mInotifyFd = -1;
1596 return ALREADY_EXISTS;
1597 }
1598
1599 return NO_ERROR;
1600}
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602// ---------------------------------------------------------------------------
1603
Marin Shalamanov9070c052020-05-18 19:05:17 +02001604} // namespace android