blob: 3109c5c1e0753e3ae3f0f0c307c06a2d35d7bc77 [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>
Mathias Agopian000479f2010-02-09 17:46:37 -080055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056#include <GLES/gl.h>
57#include <GLES/glext.h>
58#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
212 GLint crop[4] = { 0, h, w, -h };
213 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
240 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
266 GLint crop[4] = { 0, h, w, -h };
267 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
300 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
301
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
451 auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
452 constexpr uint32_t LAYER_STACK = 0;
453 for (auto id : physicalDisplayIds) {
454 if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
455 sp<IBinder> token = SurfaceComposerClient::getPhysicalDisplayToken(id);
456 if (token != nullptr)
457 t.setDisplayLayerStack(token, LAYER_STACK);
458 }
459 }
460 t.setLayerStack(control, LAYER_STACK);
461 }
462
Robert Carre13b58e2017-08-31 14:50:44 -0700463 t.setLayer(control, 0x40000000)
464 .apply();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465
Mathias Agopian17f638b2009-04-16 20:04:08 -0700466 sp<Surface> s = control->getSurface();
467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 // initialize opengl and egl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Yi Kong911ac232019-03-24 01:49:02 -0700470 eglInitialize(display, nullptr, nullptr);
Marin Shalamanov9070c052020-05-18 19:05:17 +0200471 EGLConfig config = getEglConfig(display);
472 EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
473 EGLContext context = eglCreateContext(display, config, nullptr, nullptr);
474 EGLint w, h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 eglQuerySurface(display, surface, EGL_WIDTH, &w);
476 eglQuerySurface(display, surface, EGL_HEIGHT, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700477
Mathias Agopianabac0102009-07-31 14:47:00 -0700478 if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
479 return NO_INIT;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 mDisplay = display;
482 mContext = context;
483 mSurface = surface;
484 mWidth = w;
485 mHeight = h;
Mathias Agopian17f638b2009-04-16 20:04:08 -0700486 mFlingerSurfaceControl = control;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 mFlingerSurface = s;
Adrian Roos9ee5dff2018-08-22 20:19:49 +0200488 mTargetInset = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200490 projectSceneToWindow();
491
Marin Shalamanov9070c052020-05-18 19:05:17 +0200492 // Register a display event receiver
493 mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
494 status_t status = mDisplayEventReceiver->initCheck();
495 SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
496 status);
497 mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
498 new DisplayEventCallback(this), nullptr);
499
Huihong Luo50a2f362018-08-11 09:27:57 -0700500 return NO_ERROR;
501}
502
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200503void BootAnimation::projectSceneToWindow() {
504 glViewport(0, 0, mWidth, mHeight);
505 glScissor(0, 0, mWidth, mHeight);
506 glMatrixMode(GL_PROJECTION);
507 glLoadIdentity();
508 glOrthof(0, static_cast<float>(mWidth), 0, static_cast<float>(mHeight), -1, 1);
509 glMatrixMode(GL_MODELVIEW);
510 glLoadIdentity();
511}
512
Marin Shalamanov9070c052020-05-18 19:05:17 +0200513void BootAnimation::resizeSurface(int newWidth, int newHeight) {
514 // We assume this function is called on the animation thread.
515 if (newWidth == mWidth && newHeight == mHeight) {
516 return;
517 }
518 SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
519
520 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
521 eglDestroySurface(mDisplay, mSurface);
522
Marin Shalamanov047802d2020-05-19 23:55:12 +0200523 const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
524 mWidth = limitedSize.width;
525 mHeight = limitedSize.height;
Marin Shalamanov9070c052020-05-18 19:05:17 +0200526
527 SurfaceComposerClient::Transaction t;
528 t.setSize(mFlingerSurfaceControl, mWidth, mHeight);
529 t.apply();
530
531 EGLConfig config = getEglConfig(mDisplay);
532 EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
533 if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
534 SLOGE("Can't make the new surface current. Error %d", eglGetError());
535 return;
536 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200537
538 projectSceneToWindow();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200539
540 mSurface = surface;
541}
542
Huihong Luo50a2f362018-08-11 09:27:57 -0700543bool BootAnimation::preloadAnimation() {
544 findBootAnimationFile();
545 if (!mZipFileName.isEmpty()) {
546 mAnimation = loadAnimation(mZipFileName);
547 return (mAnimation != nullptr);
548 }
549
550 return false;
551}
552
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000553bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
554 for (const std::string& f : files) {
555 if (access(f.c_str(), R_OK) == 0) {
556 mZipFileName = f.c_str();
557 return true;
558 }
559 }
560 return false;
561}
562
Huihong Luo50a2f362018-08-11 09:27:57 -0700563void BootAnimation::findBootAnimationFile() {
Elliott Hughesc367d482013-10-29 13:12:55 -0700564 // If the device has encryption turned on or is in process
Jason parksbd9a08d2011-01-31 15:04:34 -0600565 // of being encrypted we show the encrypted boot animation.
566 char decrypt[PROPERTY_VALUE_MAX];
567 property_get("vold.decrypt", decrypt, "");
568
Keun-young Parkb5938422017-03-23 13:46:24 -0700569 bool encryptedAnimation = atoi(decrypt) != 0 ||
570 !strcmp("trigger_restart_min_framework", decrypt);
Jason parksbd9a08d2011-01-31 15:04:34 -0600571
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900572 if (!mShuttingDown && encryptedAnimation) {
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000573 static const std::vector<std::string> encryptedBootFiles = {
574 PRODUCT_ENCRYPTED_BOOTANIMATION_FILE, SYSTEM_ENCRYPTED_BOOTANIMATION_FILE,
575 };
576 if (findBootAnimationFileInternal(encryptedBootFiles)) {
577 return;
Jaekyun Seokc521bb32018-01-30 11:52:47 +0900578 }
Jason parksbd9a08d2011-01-31 15:04:34 -0600579 }
Beverly34ffe252019-05-17 11:03:54 -0400580
581 const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000582 static const std::vector<std::string> bootFiles = {
583 APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
584 OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
585 };
586 static const std::vector<std::string> shutdownFiles = {
587 PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
588 };
589 static const std::vector<std::string> userspaceRebootFiles = {
590 PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
591 SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
592 };
Keun-young Parkb5938422017-03-23 13:46:24 -0700593
Nikita Ioffe06c986e2020-01-27 17:16:03 +0000594 if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
595 findBootAnimationFileInternal(userspaceRebootFiles);
596 } else if (mShuttingDown) {
597 findBootAnimationFileInternal(shutdownFiles);
598 } else {
599 findBootAnimationFileInternal(bootFiles);
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601}
602
Marin Shalamanov9070c052020-05-18 19:05:17 +0200603bool BootAnimation::threadLoop() {
604 bool result;
Narayan Kamathafd31e02013-12-03 13:16:03 +0000605 // We have no bootanimation file, so we use the stock android logo
606 // animation.
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700607 if (mZipFileName.isEmpty()) {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200608 result = android();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700609 } else {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200610 result = movie();
Mathias Agopiana8826d62009-10-01 03:10:14 -0700611 }
612
Philip Junker60600562020-11-25 18:16:16 +0100613 mCallbacks->shutdown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
615 eglDestroyContext(mDisplay, mContext);
616 eglDestroySurface(mDisplay, mSurface);
Mathias Agopian6cf0db22009-04-17 19:36:26 -0700617 mFlingerSurface.clear();
Mathias Agopian17f638b2009-04-16 20:04:08 -0700618 mFlingerSurfaceControl.clear();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700619 eglTerminate(mDisplay);
Sai Kiran Korwar3eee9fb2015-06-16 17:13:35 +0530620 eglReleaseThread();
Mathias Agopian627e7b52009-05-21 19:21:59 -0700621 IPCThreadState::self()->stopProcess();
Marin Shalamanov9070c052020-05-18 19:05:17 +0200622 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623}
624
Marin Shalamanov9070c052020-05-18 19:05:17 +0200625bool BootAnimation::android() {
Wei Wang159a4102018-10-23 23:15:58 -0700626 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -0700627 elapsedRealtime());
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700628 initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
629 initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630
Ed Coyne7464ac92017-06-08 12:26:48 -0700631 mCallbacks->init({});
632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 // clear screen
Mathias Agopiana8826d62009-10-01 03:10:14 -0700634 glShadeModel(GL_FLAT);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700635 glDisable(GL_DITHER);
636 glDisable(GL_SCISSOR_TEST);
Mathias Agopian59f19e42011-05-06 19:22:12 -0700637 glClearColor(0,0,0,1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 glClear(GL_COLOR_BUFFER_BIT);
639 eglSwapBuffers(mDisplay, mSurface);
640
Mathias Agopiana8826d62009-10-01 03:10:14 -0700641 glEnable(GL_TEXTURE_2D);
642 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
643
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700644 // Blend state
645 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
646 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 const nsecs_t startTime = systemTime();
649 do {
Marin Shalamanov9070c052020-05-18 19:05:17 +0200650 processDisplayEvents();
651 const GLint xc = (mWidth - mAndroid[0].w) / 2;
652 const GLint yc = (mHeight - mAndroid[0].h) / 2;
653 const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
654 glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
655 updateRect.height());
656
Mathias Agopian13796652009-03-24 22:49:21 -0700657 nsecs_t now = systemTime();
658 double time = now - startTime;
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700659 float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
660 GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
661 GLint x = xc - offset;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662
Mathias Agopian81668642009-07-28 11:41:30 -0700663 glDisable(GL_SCISSOR_TEST);
664 glClear(GL_COLOR_BUFFER_BIT);
665
666 glEnable(GL_SCISSOR_TEST);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 glDisable(GL_BLEND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700669 glDrawTexiOES(x, yc, 0, mAndroid[1].w, mAndroid[1].h);
670 glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
Mathias Agopianb2cf9542009-03-24 18:34:16 -0700672 glEnable(GL_BLEND);
673 glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
674 glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675
Mathias Agopian627e7b52009-05-21 19:21:59 -0700676 EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
677 if (res == EGL_FALSE)
678 break;
679
Mathias Agopian13796652009-03-24 22:49:21 -0700680 // 12fps: don't animate too fast to preserve CPU
681 const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
682 if (sleepTime > 0)
Mathias Agopiana8826d62009-10-01 03:10:14 -0700683 usleep(sleepTime);
Kevin Hesterd3782b22012-04-26 10:38:55 -0700684
685 checkExit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 } while (!exitPending());
687
688 glDeleteTextures(1, &mAndroid[0].name);
689 glDeleteTextures(1, &mAndroid[1].name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 return false;
691}
692
Kevin Hesterd3782b22012-04-26 10:38:55 -0700693void BootAnimation::checkExit() {
694 // Allow surface flinger to gracefully request shutdown
695 char value[PROPERTY_VALUE_MAX];
696 property_get(EXIT_PROP_NAME, value, "0");
697 int exitnow = atoi(value);
698 if (exitnow) {
699 requestExit();
700 }
701}
702
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700703bool BootAnimation::validClock(const Animation::Part& part) {
704 return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
705}
706
707bool parseTextCoord(const char* str, int* dest) {
708 if (strcmp("c", str) == 0) {
709 *dest = TEXT_CENTER_VALUE;
710 return true;
711 }
712
713 char* end;
714 int val = (int) strtol(str, &end, 0);
715 if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
716 return false;
717 }
718 *dest = val;
719 return true;
720}
721
722// Parse two position coordinates. If only string is non-empty, treat it as the y value.
723void parsePosition(const char* str1, const char* str2, int* x, int* y) {
724 bool success = false;
725 if (strlen(str1) == 0) { // No values were specified
726 // success = false
727 } else if (strlen(str2) == 0) { // we have only one value
728 if (parseTextCoord(str1, y)) {
729 *x = TEXT_CENTER_VALUE;
730 success = true;
731 }
732 } else {
733 if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
734 success = true;
735 }
736 }
737
738 if (!success) {
739 *x = TEXT_MISSING_VALUE;
740 *y = TEXT_MISSING_VALUE;
741 }
742}
743
Jesse Hall083b84c2014-09-22 10:51:09 -0700744// Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
745// characters in str is a hex number in [0, 255], which are converted to
746// floating point values in the range [0.0, 1.0] and placed in the
747// corresponding elements of color.
748//
749// If the input string isn't valid, parseColor returns false and color is
750// left unchanged.
751static bool parseColor(const char str[7], float color[3]) {
752 float tmpColor[3];
753 for (int i = 0; i < 3; i++) {
754 int val = 0;
755 for (int j = 0; j < 2; j++) {
756 val *= 16;
757 char c = str[2*i + j];
758 if (c >= '0' && c <= '9') val += c - '0';
759 else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
760 else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
761 else return false;
762 }
763 tmpColor[i] = static_cast<float>(val) / 255.0f;
764 }
765 memcpy(color, tmpColor, sizeof(tmpColor));
766 return true;
767}
768
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700769
Marin Shalamanov9070c052020-05-18 19:05:17 +0200770static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700771 ZipEntryRO entry = zip->findEntryByName(name);
Wei Wang159a4102018-10-23 23:15:58 -0700772 SLOGE_IF(!entry, "couldn't find %s", name);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700773 if (!entry) {
774 return false;
775 }
776
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700777 FileMap* entryMap = zip->createEntryFileMap(entry);
778 zip->releaseEntry(entry);
Wei Wang159a4102018-10-23 23:15:58 -0700779 SLOGE_IF(!entryMap, "entryMap is null");
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700780 if (!entryMap) {
781 return false;
782 }
783
784 outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
Narayan Kamath688ff4c2015-02-23 15:47:54 +0000785 delete entryMap;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700786 return true;
787}
788
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700789// The font image should be a 96x2 array of character images. The
790// columns are the printable ASCII characters 0x20 - 0x7f. The
791// top row is regular text; the bottom row is bold.
792status_t BootAnimation::initFont(Font* font, const char* fallback) {
793 status_t status = NO_ERROR;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800794
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700795 if (font->map != nullptr) {
796 glGenTextures(1, &font->texture.name);
797 glBindTexture(GL_TEXTURE_2D, font->texture.name);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800798
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700799 status = initTexture(font->map, &font->texture.w, &font->texture.h);
800
801 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
802 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
803 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
804 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
805 } else if (fallback != nullptr) {
806 status = initTexture(&font->texture, mAssets, fallback);
807 } else {
808 return NO_INIT;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800809 }
810
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700811 if (status == NO_ERROR) {
812 font->char_width = font->texture.w / FONT_NUM_COLS;
813 font->char_height = font->texture.h / FONT_NUM_ROWS / 2; // There are bold and regular rows
814 }
815
816 return status;
817}
818
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200819void BootAnimation::fadeFrame(const int frameLeft, const int frameBottom, const int frameWidth,
820 const int frameHeight, const Animation::Part& part,
821 const int fadedFramesCount) {
822 glEnable(GL_BLEND);
823 glEnableClientState(GL_VERTEX_ARRAY);
824 glDisable(GL_TEXTURE_2D);
825 // avoid creating a hole due to mixing result alpha with GL_REPLACE texture
826 glBlendFuncSeparateOES(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
827
828 const float alpha = static_cast<float>(fadedFramesCount) / part.framesToFadeCount;
829 glColor4f(part.backgroundColor[0], part.backgroundColor[1], part.backgroundColor[2], alpha);
830
831 const float frameStartX = static_cast<float>(frameLeft);
832 const float frameStartY = static_cast<float>(frameBottom);
833 const float frameEndX = frameStartX + frameWidth;
834 const float frameEndY = frameStartY + frameHeight;
835 const GLfloat frameRect[] = {
836 frameStartX, frameStartY,
837 frameEndX, frameStartY,
838 frameEndX, frameEndY,
839 frameStartX, frameEndY
840 };
841 glVertexPointer(2, GL_FLOAT, 0, frameRect);
842 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
843
844 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
845 glEnable(GL_TEXTURE_2D);
846 glDisableClientState(GL_VERTEX_ARRAY);
847 glDisable(GL_BLEND);
848}
849
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700850void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
851 glEnable(GL_BLEND); // Allow us to draw on top of the animation
852 glBindTexture(GL_TEXTURE_2D, font.texture.name);
853
854 const int len = strlen(str);
855 const int strWidth = font.char_width * len;
856
857 if (*x == TEXT_CENTER_VALUE) {
858 *x = (mWidth - strWidth) / 2;
859 } else if (*x < 0) {
860 *x = mWidth + *x - strWidth;
861 }
862 if (*y == TEXT_CENTER_VALUE) {
863 *y = (mHeight - font.char_height) / 2;
864 } else if (*y < 0) {
865 *y = mHeight + *y - font.char_height;
866 }
867
868 int cropRect[4] = { 0, 0, font.char_width, -font.char_height };
869
870 for (int i = 0; i < len; i++) {
871 char c = str[i];
872
873 if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
874 c = '?';
875 }
876
877 // Crop the texture to only the pixels in the current glyph
878 const int charPos = (c - FONT_BEGIN_CHAR); // Position in the list of valid characters
879 const int row = charPos / FONT_NUM_COLS;
880 const int col = charPos % FONT_NUM_COLS;
881 cropRect[0] = col * font.char_width; // Left of column
882 cropRect[1] = row * font.char_height * 2; // Top of row
883 // Move down to bottom of regular (one char_heigh) or bold (two char_heigh) line
884 cropRect[1] += bold ? 2 * font.char_height : font.char_height;
885 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
886
887 glDrawTexiOES(*x, *y, 0, font.char_width, font.char_height);
888
889 *x += font.char_width;
890 }
891
892 glDisable(GL_BLEND); // Return to the animation's default behaviour
893 glBindTexture(GL_TEXTURE_2D, 0);
894}
895
Damien Bargiacchi9071db12016-10-28 17:38:22 -0700896// We render 12 or 24 hour time.
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700897void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
Damien Bargiacchi9071db12016-10-28 17:38:22 -0700898 static constexpr char TIME_FORMAT_12[] = "%l:%M";
899 static constexpr char TIME_FORMAT_24[] = "%H:%M";
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700900 static constexpr int TIME_LENGTH = 6;
901
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800902 time_t rawtime;
903 time(&rawtime);
904 struct tm* timeInfo = localtime(&rawtime);
905
906 char timeBuff[TIME_LENGTH];
Damien Bargiacchi9071db12016-10-28 17:38:22 -0700907 const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
908 size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800909
910 if (length != TIME_LENGTH - 1) {
Wei Wang159a4102018-10-23 23:15:58 -0700911 SLOGE("Couldn't format time; abandoning boot animation clock");
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800912 mClockEnabled = false;
913 return;
914 }
915
Damien Bargiacchi45a76442016-12-05 18:02:18 -0800916 char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700917 int x = xPos;
918 int y = yPos;
Damien Bargiacchi45a76442016-12-05 18:02:18 -0800919 drawText(out, font, false, &x, &y);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800920}
921
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000922void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
923 static constexpr int PERCENT_LENGTH = 5;
924
925 char percentBuff[PERCENT_LENGTH];
926 // ';' has the ascii code just after ':', and the font resource contains '%'
927 // for that ascii code.
928 sprintf(percentBuff, "%d;", percent);
929 int x = xPos;
930 int y = yPos;
931 drawText(percentBuff, font, false, &x, &y);
932}
933
Marin Shalamanov9070c052020-05-18 19:05:17 +0200934bool BootAnimation::parseAnimationDesc(Animation& animation) {
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -0700935 String8 desString;
936
Andriy Naborskyy39218ba2015-08-16 21:32:50 -0700937 if (!readFile(animation.zip, "desc.txt", desString)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +0000938 return false;
939 }
Mathias Agopiana8826d62009-10-01 03:10:14 -0700940 char const* s = desString.string();
941
Mathias Agopiana8826d62009-10-01 03:10:14 -0700942 // Parse the description file
943 for (;;) {
944 const char* endl = strstr(s, "\n");
Yi Kong911ac232019-03-24 01:49:02 -0700945 if (endl == nullptr) break;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700946 String8 line(s, endl - s);
947 const char* l = line.string();
Damien Bargiacchia704b7d2016-02-16 16:55:49 -0800948 int fps = 0;
949 int width = 0;
950 int height = 0;
951 int count = 0;
952 int pause = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000953 int progress = 0;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200954 int framesToFadeCount = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +0000955 char path[ANIM_ENTRY_NAME_MAX];
Jesse Hall083b84c2014-09-22 10:51:09 -0700956 char color[7] = "000000"; // default to black if unspecified
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700957 char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
958 char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
Kevin Hesterd3782b22012-04-26 10:38:55 -0700959 char pathType;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200960
961 int nextReadPos;
962
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000963 int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
964 if (topLineNumbers == 3 || topLineNumbers == 4) {
965 // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700966 animation.width = width;
967 animation.height = height;
968 animation.fps = fps;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +0000969 if (topLineNumbers == 4) {
970 animation.progressEnabled = (progress != 0);
971 } else {
972 animation.progressEnabled = false;
973 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200974 } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
975 &pathType, &count, &pause, path, &nextReadPos) >= 4) {
976 if (pathType == 'f') {
977 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
978 clockPos2);
979 } else {
980 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
981 }
982 // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
983 // "clockPos1=%s, clockPos2=%s",
984 // pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
Mathias Agopiana8826d62009-10-01 03:10:14 -0700985 Animation::Part part;
Kevin Hesterd3782b22012-04-26 10:38:55 -0700986 part.playUntilComplete = pathType == 'c';
Yegor Malyshev6925e1b2020-09-10 16:42:20 +0200987 part.framesToFadeCount = framesToFadeCount;
Mathias Agopiana8826d62009-10-01 03:10:14 -0700988 part.count = count;
989 part.pause = pause;
990 part.path = path;
Yi Kong911ac232019-03-24 01:49:02 -0700991 part.audioData = nullptr;
992 part.animation = nullptr;
Jesse Hall083b84c2014-09-22 10:51:09 -0700993 if (!parseColor(color, part.backgroundColor)) {
Wei Wang159a4102018-10-23 23:15:58 -0700994 SLOGE("> invalid color '#%s'", color);
Jesse Hall083b84c2014-09-22 10:51:09 -0700995 part.backgroundColor[0] = 0.0f;
996 part.backgroundColor[1] = 0.0f;
997 part.backgroundColor[2] = 0.0f;
998 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -0700999 parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001000 animation.parts.add(part);
1001 }
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001002 else if (strcmp(l, "$SYSTEM") == 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001003 // SLOGD("> SYSTEM");
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001004 Animation::Part part;
1005 part.playUntilComplete = false;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001006 part.framesToFadeCount = 0;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001007 part.count = 1;
1008 part.pause = 0;
Yi Kong911ac232019-03-24 01:49:02 -07001009 part.audioData = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001010 part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
Yi Kong911ac232019-03-24 01:49:02 -07001011 if (part.animation != nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001012 animation.parts.add(part);
1013 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001014 s = ++endl;
1015 }
1016
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001017 return true;
1018}
1019
Marin Shalamanov9070c052020-05-18 19:05:17 +02001020bool BootAnimation::preloadZip(Animation& animation) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001021 // read all the data structures
1022 const size_t pcount = animation.parts.size();
Yi Kong911ac232019-03-24 01:49:02 -07001023 void *cookie = nullptr;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001024 ZipFileRO* zip = animation.zip;
1025 if (!zip->startIteration(&cookie)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001026 return false;
1027 }
1028
1029 ZipEntryRO entry;
1030 char name[ANIM_ENTRY_NAME_MAX];
Yi Kong911ac232019-03-24 01:49:02 -07001031 while ((entry = zip->nextEntry(cookie)) != nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001032 const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001033 if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
Wei Wang159a4102018-10-23 23:15:58 -07001034 SLOGE("Error fetching entry file name");
Narayan Kamathafd31e02013-12-03 13:16:03 +00001035 continue;
1036 }
1037
1038 const String8 entryName(name);
1039 const String8 path(entryName.getPathDir());
1040 const String8 leaf(entryName.getPathLeaf());
1041 if (leaf.size() > 0) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001042 if (entryName == CLOCK_FONT_ZIP_NAME) {
1043 FileMap* map = zip->createEntryFileMap(entry);
1044 if (map) {
1045 animation.clockFont.map = map;
1046 }
1047 continue;
1048 }
1049
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001050 if (entryName == PROGRESS_FONT_ZIP_NAME) {
1051 FileMap* map = zip->createEntryFileMap(entry);
1052 if (map) {
1053 animation.progressFont.map = map;
1054 }
1055 continue;
1056 }
1057
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001058 for (size_t j = 0; j < pcount; j++) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001059 if (path == animation.parts[j].path) {
Narayan Kamath4600dd02015-06-16 12:02:57 +01001060 uint16_t method;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001061 // supports only stored png files
Yi Kong911ac232019-03-24 01:49:02 -07001062 if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001063 if (method == ZipFileRO::kCompressStored) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001064 FileMap* map = zip->createEntryFileMap(entry);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001065 if (map) {
Narayan Kamathafd31e02013-12-03 13:16:03 +00001066 Animation::Part& part(animation.parts.editItemAt(j));
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001067 if (leaf == "audio.wav") {
1068 // a part may have at most one audio file
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001069 part.audioData = (uint8_t *)map->getDataPtr();
1070 part.audioLength = map->getDataLength();
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001071 } else if (leaf == "trim.txt") {
1072 part.trimData.setTo((char const*)map->getDataPtr(),
1073 map->getDataLength());
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001074 } else {
1075 Animation::Frame frame;
1076 frame.name = leaf;
1077 frame.map = map;
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001078 frame.trimWidth = animation.width;
1079 frame.trimHeight = animation.height;
1080 frame.trimX = 0;
1081 frame.trimY = 0;
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001082 part.frames.add(frame);
1083 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001084 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001085 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001086 SLOGE("bootanimation.zip is compressed; must be only stored");
Mathias Agopiana8826d62009-10-01 03:10:14 -07001087 }
1088 }
1089 }
1090 }
1091 }
1092 }
1093
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001094 // If there is trimData present, override the positioning defaults.
1095 for (Animation::Part& part : animation.parts) {
1096 const char* trimDataStr = part.trimData.string();
1097 for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1098 const char* endl = strstr(trimDataStr, "\n");
1099 // No more trimData for this part.
Yi Kong911ac232019-03-24 01:49:02 -07001100 if (endl == nullptr) {
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001101 break;
1102 }
1103 String8 line(trimDataStr, endl - trimDataStr);
1104 const char* lineStr = line.string();
1105 trimDataStr = ++endl;
1106 int width = 0, height = 0, x = 0, y = 0;
1107 if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1108 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1109 frame.trimWidth = width;
1110 frame.trimHeight = height;
1111 frame.trimX = x;
1112 frame.trimY = y;
1113 } else {
Wei Wang159a4102018-10-23 23:15:58 -07001114 SLOGE("Error parsing trim.txt, line: %s", lineStr);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001115 break;
1116 }
1117 }
1118 }
1119
1120 zip->endIteration(cookie);
Narayan Kamathafd31e02013-12-03 13:16:03 +00001121
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001122 return true;
1123}
1124
Marin Shalamanov9070c052020-05-18 19:05:17 +02001125bool BootAnimation::movie() {
Huihong Luo50a2f362018-08-11 09:27:57 -07001126 if (mAnimation == nullptr) {
1127 mAnimation = loadAnimation(mZipFileName);
1128 }
1129
1130 if (mAnimation == nullptr)
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001131 return false;
1132
Huihong Luo50a2f362018-08-11 09:27:57 -07001133 // mCallbacks->init() may get called recursively,
1134 // this loop is needed to get the same results
1135 for (const Animation::Part& part : mAnimation->parts) {
1136 if (part.animation != nullptr) {
1137 mCallbacks->init(part.animation->parts);
1138 }
1139 }
1140 mCallbacks->init(mAnimation->parts);
1141
Damien Bargiacchi97480862016-03-29 14:55:55 -07001142 bool anyPartHasClock = false;
Huihong Luo50a2f362018-08-11 09:27:57 -07001143 for (size_t i=0; i < mAnimation->parts.size(); i++) {
1144 if(validClock(mAnimation->parts[i])) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001145 anyPartHasClock = true;
1146 break;
1147 }
1148 }
1149 if (!anyPartHasClock) {
1150 mClockEnabled = false;
1151 }
1152
Sai Kiran Korwar27167492015-07-07 20:00:06 +05301153 // Check if npot textures are supported
1154 mUseNpotTextures = false;
1155 String8 gl_extensions;
1156 const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1157 if (!exts) {
1158 glGetError();
1159 } else {
1160 gl_extensions.setTo(exts);
1161 if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1162 (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1163 mUseNpotTextures = true;
1164 }
1165 }
1166
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001167 // Blend required to draw time on top of animation frames.
1168 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001169 glShadeModel(GL_FLAT);
1170 glDisable(GL_DITHER);
1171 glDisable(GL_SCISSOR_TEST);
1172 glDisable(GL_BLEND);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001173
1174 glBindTexture(GL_TEXTURE_2D, 0);
1175 glEnable(GL_TEXTURE_2D);
1176 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1177 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1178 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
1179 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1180 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1181
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001182 bool clockFontInitialized = false;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001183 if (mClockEnabled) {
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001184 clockFontInitialized =
Huihong Luo50a2f362018-08-11 09:27:57 -07001185 (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001186 mClockEnabled = clockFontInitialized;
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001187 }
1188
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001189 initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1190
Damien Bargiacchi97480862016-03-29 14:55:55 -07001191 if (mClockEnabled && !updateIsTimeAccurate()) {
1192 mTimeCheckThread = new TimeCheckThread(this);
1193 mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1194 }
1195
Huihong Luo50a2f362018-08-11 09:27:57 -07001196 playAnimation(*mAnimation);
Damien Bargiacchi97480862016-03-29 14:55:55 -07001197
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001198 if (mTimeCheckThread != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001199 mTimeCheckThread->requestExit();
Geoffrey Pitscha9173532016-07-19 14:56:39 -04001200 mTimeCheckThread = nullptr;
1201 }
1202
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001203 if (clockFontInitialized) {
Huihong Luo50a2f362018-08-11 09:27:57 -07001204 glDeleteTextures(1, &mAnimation->clockFont.texture.name);
Andriy Naborskyy815e51d2016-03-24 16:43:34 -07001205 }
1206
Huihong Luo50a2f362018-08-11 09:27:57 -07001207 releaseAnimation(mAnimation);
1208 mAnimation = nullptr;
Damien Bargiacchi1a8a2132018-07-24 15:20:26 -07001209
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001210 return false;
1211}
1212
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001213bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1214 const int fadedFramesCount,
1215 const int lastDisplayedProgress) {
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001216 // 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 +01001217 return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1218 (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001219}
1220
Marin Shalamanov9070c052020-05-18 19:05:17 +02001221bool BootAnimation::playAnimation(const Animation& animation) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001222 const size_t pcount = animation.parts.size();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001223 nsecs_t frameDuration = s2ns(1) / animation.fps;
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001224
Wei Wang159a4102018-10-23 23:15:58 -07001225 SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
Keun-young Parkd1794cd2017-04-04 12:21:19 -07001226 elapsedRealtime());
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001227
1228 int fadedFramesCount = 0;
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001229 int lastDisplayedProgress = 0;
Narayan Kamathafd31e02013-12-03 13:16:03 +00001230 for (size_t i=0 ; i<pcount ; i++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001231 const Animation::Part& part(animation.parts[i]);
1232 const size_t fcount = part.frames.size();
1233 glBindTexture(GL_TEXTURE_2D, 0);
1234
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001235 // Handle animation package
Yi Kong911ac232019-03-24 01:49:02 -07001236 if (part.animation != nullptr) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001237 playAnimation(*part.animation);
1238 if (exitPending())
1239 break;
1240 continue; //to next part
1241 }
1242
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001243 // process the part not only while the count allows but also if already fading
1244 for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001245 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Kevin Hesterd3782b22012-04-26 10:38:55 -07001246
Ed Coyne7464ac92017-06-08 12:26:48 -07001247 mCallbacks->playPart(i, part, r);
Mike Lockwoodebf9a0d2014-10-02 16:08:47 -07001248
Jesse Hall083b84c2014-09-22 10:51:09 -07001249 glClearColor(
1250 part.backgroundColor[0],
1251 part.backgroundColor[1],
1252 part.backgroundColor[2],
1253 1.0f);
1254
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001255 // For the last animation, if we have progress indicator from
1256 // the system, display it.
1257 int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1258 bool displayProgress = animation.progressEnabled &&
1259 (i == (pcount -1)) && currentProgress != 0;
1260
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001261 for (size_t j=0 ; j<fcount ; j++) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001262 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001263
Marin Shalamanov9070c052020-05-18 19:05:17 +02001264 processDisplayEvents();
1265
1266 const int animationX = (mWidth - animation.width) / 2;
1267 const int animationY = (mHeight - animation.height) / 2;
1268
Mathias Agopiana8826d62009-10-01 03:10:14 -07001269 const Animation::Frame& frame(part.frames[j]);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001270 nsecs_t lastFrame = systemTime();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001271
1272 if (r > 0) {
1273 glBindTexture(GL_TEXTURE_2D, frame.tid);
1274 } else {
1275 if (part.count != 1) {
1276 glGenTextures(1, &frame.tid);
1277 glBindTexture(GL_TEXTURE_2D, frame.tid);
1278 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1279 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1280 }
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001281 int w, h;
1282 initTexture(frame.map, &w, &h);
Mathias Agopiana8826d62009-10-01 03:10:14 -07001283 }
1284
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001285 const int xc = animationX + frame.trimX;
1286 const int yc = animationY + frame.trimY;
1287 Region clearReg(Rect(mWidth, mHeight));
1288 clearReg.subtractSelf(Rect(xc, yc, xc+frame.trimWidth, yc+frame.trimHeight));
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001289 if (!clearReg.isEmpty()) {
1290 Region::const_iterator head(clearReg.begin());
1291 Region::const_iterator tail(clearReg.end());
1292 glEnable(GL_SCISSOR_TEST);
1293 while (head != tail) {
Andreas Gampecfedceb2014-09-30 21:48:18 -07001294 const Rect& r2(*head++);
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001295 glScissor(r2.left, mHeight - r2.bottom, r2.width(), r2.height());
Mathias Agopian9f3020d2009-11-06 16:30:18 -08001296 glClear(GL_COLOR_BUFFER_BIT);
1297 }
1298 glDisable(GL_SCISSOR_TEST);
1299 }
Geoffrey Pitschdd214a72016-06-27 17:14:30 -04001300 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1301 // which is equivalent to mHeight - (yc + frame.trimHeight)
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001302 const int frameDrawY = mHeight - (yc + frame.trimHeight);
1303 glDrawTexiOES(xc, frameDrawY, 0, frame.trimWidth, frame.trimHeight);
1304
1305 // if the part hasn't been stopped yet then continue fading if necessary
1306 if (exitPending() && part.hasFadingPhase()) {
1307 fadeFrame(xc, frameDrawY, frame.trimWidth, frame.trimHeight, part,
1308 ++fadedFramesCount);
1309 if (fadedFramesCount >= part.framesToFadeCount) {
1310 fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1311 }
1312 }
1313
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001314 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1315 drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001316 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001317
Nicolas Geoffray41fffb42020-12-15 10:50:29 +00001318 if (displayProgress) {
1319 int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1320 // In case the new progress jumped suddenly, still show an
1321 // increment of 1.
1322 if (lastDisplayedProgress != 100) {
1323 // Artificially sleep 1/10th a second to slow down the animation.
1324 usleep(100000);
1325 if (lastDisplayedProgress < newProgress) {
1326 lastDisplayedProgress++;
1327 }
1328 }
1329 // Put the progress percentage right below the animation.
1330 int posY = animation.height / 3;
1331 int posX = TEXT_CENTER_VALUE;
1332 drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1333 }
1334
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001335 handleViewport(frameDuration);
Damien Bargiacchia704b7d2016-02-16 16:55:49 -08001336
Mathias Agopiana8826d62009-10-01 03:10:14 -07001337 eglSwapBuffers(mDisplay, mSurface);
1338
1339 nsecs_t now = systemTime();
1340 nsecs_t delay = frameDuration - (now - lastFrame);
Wei Wang159a4102018-10-23 23:15:58 -07001341 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
Mathias Agopiana8826d62009-10-01 03:10:14 -07001342 lastFrame = now;
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001343
1344 if (delay > 0) {
1345 struct timespec spec;
1346 spec.tv_sec = (now + delay) / 1000000000;
1347 spec.tv_nsec = (now + delay) % 1000000000;
1348 int err;
1349 do {
Yi Kong911ac232019-03-24 01:49:02 -07001350 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
Mathias Agopiandb7dd2a2012-05-12 15:08:21 -07001351 } while (err<0 && errno == EINTR);
1352 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001353
1354 checkExit();
Mathias Agopiana8826d62009-10-01 03:10:14 -07001355 }
Kevin Hesterd3782b22012-04-26 10:38:55 -07001356
Mathias Agopiana8826d62009-10-01 03:10:14 -07001357 usleep(part.pause * ns2us(frameDuration));
Kevin Hesterd3782b22012-04-26 10:38:55 -07001358
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001359 if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1360 !part.hasFadingPhase()) {
Nicolas Geoffraya1298752021-04-20 15:15:06 +01001361 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1362 android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1363 continue;
1364 }
Yegor Malyshev6925e1b2020-09-10 16:42:20 +02001365 break; // exit the infinite non-fading part when it has been played at least once
1366 }
Mathias Agopiana8826d62009-10-01 03:10:14 -07001367 }
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001368 }
1369
1370 // Free textures created for looping parts now that the animation is done.
1371 for (const Animation::Part& part : animation.parts) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001372 if (part.count != 1) {
Geoffrey Pitsch2fb30fb2016-07-06 16:16:20 -04001373 const size_t fcount = part.frames.size();
1374 for (size_t j = 0; j < fcount; j++) {
Mathias Agopiana8826d62009-10-01 03:10:14 -07001375 const Animation::Frame& frame(part.frames[j]);
1376 glDeleteTextures(1, &frame.tid);
1377 }
1378 }
1379 }
Geoffrey Pitschd6d9a1d2016-06-08 00:38:58 -07001380
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001381 return true;
Mathias Agopiana8826d62009-10-01 03:10:14 -07001382}
1383
Marin Shalamanov9070c052020-05-18 19:05:17 +02001384void BootAnimation::processDisplayEvents() {
1385 // This will poll mDisplayEventReceiver and if there are new events it'll call
1386 // displayEventCallback synchronously.
1387 mLooper->pollOnce(0);
1388}
1389
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001390void BootAnimation::handleViewport(nsecs_t timestep) {
1391 if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1392 return;
1393 }
1394 if (mTargetInset < 0) {
1395 // Poll the amount for the top display inset. This will return -1 until persistent properties
1396 // have been loaded.
1397 mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1398 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1399 }
1400 if (mTargetInset <= 0) {
1401 return;
1402 }
1403
1404 if (mCurrentInset < mTargetInset) {
1405 // After the device boots, the inset will effectively be cropped away. We animate this here.
1406 float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1407 int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1408
1409 SurfaceComposerClient::Transaction()
1410 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1411 .apply();
1412 } else {
1413 // At the end of the animation, we switch to the viewport that DisplayManager will apply
1414 // later. This changes the coordinate system, and means we must move the surface up by
1415 // the inset amount.
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001416 Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1417 Rect displayRect(0, mTargetInset, mWidth, mHeight);
1418
1419 SurfaceComposerClient::Transaction t;
1420 t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1421 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
Dominik Laskowski2a3d9aa2019-11-18 20:26:39 -08001422 t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
Adrian Roos9ee5dff2018-08-22 20:19:49 +02001423 t.apply();
1424
1425 mTargetInset = mCurrentInset = 0;
1426 }
1427
1428 int delta = timestep * mTargetInset / ms2ns(200);
1429 mCurrentInset += delta;
1430}
1431
Marin Shalamanov9070c052020-05-18 19:05:17 +02001432void BootAnimation::releaseAnimation(Animation* animation) const {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001433 for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1434 e = animation->parts.end(); it != e; ++it) {
1435 if (it->animation)
1436 releaseAnimation(it->animation);
1437 }
1438 if (animation->zip)
1439 delete animation->zip;
1440 delete animation;
1441}
1442
Marin Shalamanov9070c052020-05-18 19:05:17 +02001443BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001444 if (mLoadedFiles.indexOf(fn) >= 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001445 SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001446 fn.string());
Yi Kong911ac232019-03-24 01:49:02 -07001447 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001448 }
1449 ZipFileRO *zip = ZipFileRO::open(fn);
Yi Kong911ac232019-03-24 01:49:02 -07001450 if (zip == nullptr) {
Wei Wang159a4102018-10-23 23:15:58 -07001451 SLOGE("Failed to open animation zip \"%s\": %s",
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001452 fn.string(), strerror(errno));
Yi Kong911ac232019-03-24 01:49:02 -07001453 return nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001454 }
1455
1456 Animation *animation = new Animation;
1457 animation->fileName = fn;
1458 animation->zip = zip;
Damien Bargiacchi0e3d2ab2016-08-29 04:11:19 -07001459 animation->clockFont.map = nullptr;
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001460 mLoadedFiles.add(animation->fileName);
1461
1462 parseAnimationDesc(*animation);
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001463 if (!preloadZip(*animation)) {
Greg Kaiser7426ec82019-09-11 14:34:27 -07001464 releaseAnimation(animation);
Yi Kong911ac232019-03-24 01:49:02 -07001465 return nullptr;
Geoffrey Pitscha91a2d72016-07-12 14:46:19 -04001466 }
1467
Andriy Naborskyy39218ba2015-08-16 21:32:50 -07001468 mLoadedFiles.remove(fn);
1469 return animation;
1470}
Damien Bargiacchi97480862016-03-29 14:55:55 -07001471
1472bool BootAnimation::updateIsTimeAccurate() {
1473 static constexpr long long MAX_TIME_IN_PAST = 60000LL * 60LL * 24LL * 30LL; // 30 days
1474 static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL; // 90 minutes
1475
1476 if (mTimeIsAccurate) {
1477 return true;
1478 }
Keun-young Parkb5938422017-03-23 13:46:24 -07001479 if (mShuttingDown) return true;
Damien Bargiacchi97480862016-03-29 14:55:55 -07001480 struct stat statResult;
Damien Bargiacchi9071db12016-10-28 17:38:22 -07001481
1482 if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1483 mTimeFormat12Hour = true;
1484 }
1485
Damien Bargiacchi97480862016-03-29 14:55:55 -07001486 if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1487 mTimeIsAccurate = true;
1488 return true;
1489 }
1490
1491 FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
Yi Kong911ac232019-03-24 01:49:02 -07001492 if (file != nullptr) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001493 long long lastChangedTime = 0;
1494 fscanf(file, "%lld", &lastChangedTime);
1495 fclose(file);
1496 if (lastChangedTime > 0) {
1497 struct timespec now;
1498 clock_gettime(CLOCK_REALTIME, &now);
1499 // Match the Java timestamp format
1500 long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
Damien Bargiacchi96762812016-07-12 15:53:40 -07001501 if (ACCURATE_TIME_EPOCH < rtcNow
1502 && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1503 && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
Damien Bargiacchi97480862016-03-29 14:55:55 -07001504 mTimeIsAccurate = true;
1505 }
1506 }
1507 }
1508
1509 return mTimeIsAccurate;
1510}
1511
1512BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1513 mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1514
1515BootAnimation::TimeCheckThread::~TimeCheckThread() {
1516 // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1517 close(mInotifyFd);
1518}
1519
1520bool BootAnimation::TimeCheckThread::threadLoop() {
1521 bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1522 && mBootAnimation->mClockEnabled;
1523 if (!shouldLoop) {
1524 close(mInotifyFd);
1525 mInotifyFd = -1;
1526 }
1527 return shouldLoop;
1528}
1529
1530bool BootAnimation::TimeCheckThread::doThreadLoop() {
1531 static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1532
1533 // Poll instead of doing a blocking read so the Thread can exit if requested.
1534 struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1535 ssize_t pollResult = poll(&pfd, 1, 1000);
1536
1537 if (pollResult == 0) {
1538 return true;
1539 } else if (pollResult < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001540 SLOGE("Could not poll inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001541 return false;
1542 }
1543
1544 char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1545 ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1546 if (length == 0) {
1547 return true;
1548 } else if (length < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001549 SLOGE("Could not read inotify events");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001550 return false;
1551 }
1552
1553 const struct inotify_event *event;
1554 for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1555 event = (const struct inotify_event *) ptr;
1556 if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
1557 addTimeDirWatch();
1558 } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1559 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1560 return !mBootAnimation->updateIsTimeAccurate();
1561 }
1562 }
1563
1564 return true;
1565}
1566
1567void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1568 mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
1569 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1570 if (mTimeWd > 0) {
1571 // No need to watch for the time directory to be created if it already exists
1572 inotify_rm_watch(mInotifyFd, mSystemWd);
1573 mSystemWd = -1;
1574 }
1575}
1576
1577status_t BootAnimation::TimeCheckThread::readyToRun() {
1578 mInotifyFd = inotify_init();
1579 if (mInotifyFd < 0) {
Wei Wang159a4102018-10-23 23:15:58 -07001580 SLOGE("Could not initialize inotify fd");
Damien Bargiacchi97480862016-03-29 14:55:55 -07001581 return NO_INIT;
1582 }
1583
1584 mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1585 if (mSystemWd < 0) {
1586 close(mInotifyFd);
1587 mInotifyFd = -1;
Dan Sandler562d46d2020-05-11 17:09:22 -04001588 SLOGE("Could not add watch for %s: %s", SYSTEM_DATA_DIR_PATH, strerror(errno));
Damien Bargiacchi97480862016-03-29 14:55:55 -07001589 return NO_INIT;
1590 }
1591
1592 addTimeDirWatch();
1593
1594 if (mBootAnimation->updateIsTimeAccurate()) {
1595 close(mInotifyFd);
1596 mInotifyFd = -1;
1597 return ALREADY_EXISTS;
1598 }
1599
1600 return NO_ERROR;
1601}
1602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603// ---------------------------------------------------------------------------
1604
Marin Shalamanov9070c052020-05-18 19:05:17 +02001605} // namespace android