1 /*
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 
17 #define LOG_NDEBUG 0
18 #define LOG_TAG "BootAnimation"
19 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 
21 #include <filesystem>
22 #include <vector>
23 
24 #include <stdint.h>
25 #include <inttypes.h>
26 #include <sys/inotify.h>
27 #include <sys/poll.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <math.h>
31 #include <fcntl.h>
32 #include <utils/misc.h>
33 #include <utils/Trace.h>
34 #include <signal.h>
35 #include <time.h>
36 
37 #include <cutils/atomic.h>
38 #include <cutils/properties.h>
39 
40 #include <android/imagedecoder.h>
41 #include <androidfw/AssetManager.h>
42 #include <binder/IPCThreadState.h>
43 #include <utils/Errors.h>
44 #include <utils/Log.h>
45 #include <utils/SystemClock.h>
46 
47 #include <android-base/properties.h>
48 
49 #include <ui/DisplayMode.h>
50 #include <ui/PixelFormat.h>
51 #include <ui/Rect.h>
52 #include <ui/Region.h>
53 
54 #include <gui/ISurfaceComposer.h>
55 #include <gui/DisplayEventReceiver.h>
56 #include <gui/Surface.h>
57 #include <gui/SurfaceComposerClient.h>
58 #include <GLES2/gl2.h>
59 #include <GLES2/gl2ext.h>
60 #include <EGL/eglext.h>
61 
62 #include "BootAnimation.h"
63 
64 #define ANIM_PATH_MAX 255
65 #define STR(x)   #x
66 #define STRTO(x) STR(x)
67 
68 namespace android {
69 
70 using ui::DisplayMode;
71 
72 static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
73 static const char PRODUCT_BOOTANIMATION_DARK_FILE[] = "/product/media/bootanimation-dark.zip";
74 static const char PRODUCT_BOOTANIMATION_FILE[] = "/product/media/bootanimation.zip";
75 static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
76 static const char APEX_BOOTANIMATION_FILE[] = "/apex/com.android.bootanimation/etc/bootanimation.zip";
77 static const char OEM_SHUTDOWNANIMATION_FILE[] = "/oem/media/shutdownanimation.zip";
78 static const char PRODUCT_SHUTDOWNANIMATION_FILE[] = "/product/media/shutdownanimation.zip";
79 static const char SYSTEM_SHUTDOWNANIMATION_FILE[] = "/system/media/shutdownanimation.zip";
80 
81 static constexpr const char* PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE = "/product/media/userspace-reboot.zip";
82 static constexpr const char* OEM_USERSPACE_REBOOT_ANIMATION_FILE = "/oem/media/userspace-reboot.zip";
83 static constexpr const char* SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE = "/system/media/userspace-reboot.zip";
84 
85 static const char BOOTANIM_DATA_DIR_PATH[] = "/data/misc/bootanim";
86 static const char BOOTANIM_TIME_DIR_NAME[] = "time";
87 static const char BOOTANIM_TIME_DIR_PATH[] = "/data/misc/bootanim/time";
88 static const char CLOCK_FONT_ASSET[] = "images/clock_font.png";
89 static const char CLOCK_FONT_ZIP_NAME[] = "clock_font.png";
90 static const char PROGRESS_FONT_ASSET[] = "images/progress_font.png";
91 static const char PROGRESS_FONT_ZIP_NAME[] = "progress_font.png";
92 static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
93 static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/misc/bootanim/time/last_time_change";
94 static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
95 static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/misc/bootanim/time/time_is_accurate";
96 static const char TIME_FORMAT_12_HOUR_FLAG_FILE_PATH[] = "/data/misc/bootanim/time/time_format_12_hour";
97 // Java timestamp format. Don't show the clock if the date is before 2000-01-01 00:00:00.
98 static const long long ACCURATE_TIME_EPOCH = 946684800000;
99 static constexpr char FONT_BEGIN_CHAR = ' ';
100 static constexpr char FONT_END_CHAR = '~' + 1;
101 static constexpr size_t FONT_NUM_CHARS = FONT_END_CHAR - FONT_BEGIN_CHAR + 1;
102 static constexpr size_t FONT_NUM_COLS = 16;
103 static constexpr size_t FONT_NUM_ROWS = FONT_NUM_CHARS / FONT_NUM_COLS;
104 static const int TEXT_CENTER_VALUE = INT_MAX;
105 static const int TEXT_MISSING_VALUE = INT_MIN;
106 static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
107 static const char PROGRESS_PROP_NAME[] = "service.bootanim.progress";
108 static const char DISPLAYS_PROP_NAME[] = "persist.service.bootanim.displays";
109 static const char CLOCK_ENABLED_PROP_NAME[] = "persist.sys.bootanim.clock.enabled";
110 static const int ANIM_ENTRY_NAME_MAX = ANIM_PATH_MAX + 1;
111 static const int MAX_CHECK_EXIT_INTERVAL_US = 50000;
112 static constexpr size_t TEXT_POS_LEN_MAX = 16;
113 static const int DYNAMIC_COLOR_COUNT = 4;
114 static const char U_TEXTURE[] = "uTexture";
115 static const char U_FADE[] = "uFade";
116 static const char U_CROP_AREA[] = "uCropArea";
117 static const char U_START_COLOR_PREFIX[] = "uStartColor";
118 static const char U_END_COLOR_PREFIX[] = "uEndColor";
119 static const char U_COLOR_PROGRESS[] = "uColorProgress";
120 static const char A_UV[] = "aUv";
121 static const char A_POSITION[] = "aPosition";
122 static const char VERTEX_SHADER_SOURCE[] = R"(
123     precision mediump float;
124     attribute vec4 aPosition;
125     attribute highp vec2 aUv;
126     varying highp vec2 vUv;
127     void main() {
128         gl_Position = aPosition;
129         vUv = aUv;
130     })";
131 static const char IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE[] = R"(
132     precision mediump float;
133     const float cWhiteMaskThreshold = 0.05;
134     uniform sampler2D uTexture;
135     uniform float uFade;
136     uniform float uColorProgress;
137     uniform vec3 uStartColor0;
138     uniform vec3 uStartColor1;
139     uniform vec3 uStartColor2;
140     uniform vec3 uStartColor3;
141     uniform vec3 uEndColor0;
142     uniform vec3 uEndColor1;
143     uniform vec3 uEndColor2;
144     uniform vec3 uEndColor3;
145     varying highp vec2 vUv;
146     void main() {
147         vec4 mask = texture2D(uTexture, vUv);
148         float r = mask.r;
149         float g = mask.g;
150         float b = mask.b;
151         float a = mask.a;
152         // If all channels have values, render pixel as a shade of white.
153         float useWhiteMask = step(cWhiteMaskThreshold, r)
154             * step(cWhiteMaskThreshold, g)
155             * step(cWhiteMaskThreshold, b)
156             * step(cWhiteMaskThreshold, a);
157         vec3 color = r * mix(uStartColor0, uEndColor0, uColorProgress)
158                 + g * mix(uStartColor1, uEndColor1, uColorProgress)
159                 + b * mix(uStartColor2, uEndColor2, uColorProgress)
160                 + a * mix(uStartColor3, uEndColor3, uColorProgress);
161         color = mix(color, vec3((r + g + b + a) * 0.25), useWhiteMask);
162         gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade));
163     })";
164 static const char IMAGE_FRAG_SHADER_SOURCE[] = R"(
165     precision mediump float;
166     uniform sampler2D uTexture;
167     uniform float uFade;
168     varying highp vec2 vUv;
169     void main() {
170         vec4 color = texture2D(uTexture, vUv);
171         gl_FragColor = vec4(color.x, color.y, color.z, (1.0 - uFade)) * color.a;
172     })";
173 static const char TEXT_FRAG_SHADER_SOURCE[] = R"(
174     precision mediump float;
175     uniform sampler2D uTexture;
176     uniform vec4 uCropArea;
177     varying highp vec2 vUv;
178     void main() {
179         vec2 uv = vec2(mix(uCropArea.x, uCropArea.z, vUv.x),
180                        mix(uCropArea.y, uCropArea.w, vUv.y));
181         gl_FragColor = texture2D(uTexture, uv);
182     })";
183 
184 static GLfloat quadPositions[] = {
185     -0.5f, -0.5f,
186     +0.5f, -0.5f,
187     +0.5f, +0.5f,
188     +0.5f, +0.5f,
189     -0.5f, +0.5f,
190     -0.5f, -0.5f
191 };
192 static GLfloat quadUVs[] = {
193     0.0f, 1.0f,
194     1.0f, 1.0f,
195     1.0f, 0.0f,
196     1.0f, 0.0f,
197     0.0f, 0.0f,
198     0.0f, 1.0f
199 };
200 
201 // ---------------------------------------------------------------------------
202 
BootAnimation(sp<Callbacks> callbacks)203 BootAnimation::BootAnimation(sp<Callbacks> callbacks)
204         : Thread(false), mLooper(new Looper(false)), mClockEnabled(true), mTimeIsAccurate(false),
205         mTimeFormat12Hour(false), mTimeCheckThread(nullptr), mCallbacks(callbacks) {
206     ATRACE_CALL();
207     mSession = new SurfaceComposerClient();
208 
209     std::string powerCtl = android::base::GetProperty("sys.powerctl", "");
210     if (powerCtl.empty()) {
211         mShuttingDown = false;
212     } else {
213         mShuttingDown = true;
214     }
215     ALOGD("%sAnimationStartTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
216             elapsedRealtime());
217 }
218 
~BootAnimation()219 BootAnimation::~BootAnimation() {
220     ATRACE_CALL();
221     if (mAnimation != nullptr) {
222         releaseAnimation(mAnimation);
223         mAnimation = nullptr;
224     }
225     ALOGD("%sAnimationStopTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
226             elapsedRealtime());
227 }
228 
onFirstRef()229 void BootAnimation::onFirstRef() {
230     ATRACE_CALL();
231     status_t err = mSession->linkToComposerDeath(this);
232     SLOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
233     if (err == NO_ERROR) {
234         // Load the animation content -- this can be slow (eg 200ms)
235         // called before waitForSurfaceFlinger() in main() to avoid wait
236         ALOGD("%sAnimationPreloadTiming start time: %" PRId64 "ms",
237                 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
238         preloadAnimation();
239         ALOGD("%sAnimationPreloadStopTiming start time: %" PRId64 "ms",
240                 mShuttingDown ? "Shutdown" : "Boot", elapsedRealtime());
241     }
242 }
243 
session() const244 sp<SurfaceComposerClient> BootAnimation::session() const {
245     return mSession;
246 }
247 
binderDied(const wp<IBinder> &)248 void BootAnimation::binderDied(const wp<IBinder>&) {
249     ATRACE_CALL();
250     // woah, surfaceflinger died!
251     SLOGD("SurfaceFlinger died, exiting...");
252 
253     // calling requestExit() is not enough here because the Surface code
254     // might be blocked on a condition variable that will never be updated.
255     kill( getpid(), SIGKILL );
256     requestExit();
257 }
258 
decodeImage(const void * encodedData,size_t dataLength,AndroidBitmapInfo * outInfo,bool premultiplyAlpha)259 static void* decodeImage(const void* encodedData, size_t dataLength, AndroidBitmapInfo* outInfo,
260     bool premultiplyAlpha) {
261     ATRACE_CALL();
262     AImageDecoder* decoder = nullptr;
263     AImageDecoder_createFromBuffer(encodedData, dataLength, &decoder);
264     if (!decoder) {
265         return nullptr;
266     }
267 
268     const AImageDecoderHeaderInfo* info = AImageDecoder_getHeaderInfo(decoder);
269     outInfo->width = AImageDecoderHeaderInfo_getWidth(info);
270     outInfo->height = AImageDecoderHeaderInfo_getHeight(info);
271     outInfo->format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(info);
272     outInfo->stride = AImageDecoder_getMinimumStride(decoder);
273     outInfo->flags = 0;
274 
275     if (!premultiplyAlpha) {
276         AImageDecoder_setUnpremultipliedRequired(decoder, true);
277     }
278 
279     const size_t size = outInfo->stride * outInfo->height;
280     void* pixels = malloc(size);
281     int result = AImageDecoder_decodeImage(decoder, pixels, outInfo->stride, size);
282     AImageDecoder_delete(decoder);
283 
284     if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
285         free(pixels);
286         return nullptr;
287     }
288     return pixels;
289 }
290 
initTexture(Texture * texture,AssetManager & assets,const char * name,bool premultiplyAlpha)291 status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
292         const char* name, bool premultiplyAlpha) {
293     ATRACE_CALL();
294     Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
295     if (asset == nullptr)
296         return NO_INIT;
297 
298     AndroidBitmapInfo bitmapInfo;
299     void* pixels = decodeImage(asset->getBuffer(false), asset->getLength(), &bitmapInfo,
300         premultiplyAlpha);
301     auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
302 
303     asset->close();
304     delete asset;
305 
306     if (!pixels) {
307         return NO_INIT;
308     }
309 
310     const int w = bitmapInfo.width;
311     const int h = bitmapInfo.height;
312 
313     texture->w = w;
314     texture->h = h;
315 
316     glGenTextures(1, &texture->name);
317     glBindTexture(GL_TEXTURE_2D, texture->name);
318 
319     switch (bitmapInfo.format) {
320         case ANDROID_BITMAP_FORMAT_A_8:
321             glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
322                     GL_UNSIGNED_BYTE, pixels);
323             break;
324         case ANDROID_BITMAP_FORMAT_RGBA_4444:
325             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
326                     GL_UNSIGNED_SHORT_4_4_4_4, pixels);
327             break;
328         case ANDROID_BITMAP_FORMAT_RGBA_8888:
329             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
330                     GL_UNSIGNED_BYTE, pixels);
331             break;
332         case ANDROID_BITMAP_FORMAT_RGB_565:
333             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
334                     GL_UNSIGNED_SHORT_5_6_5, pixels);
335             break;
336         default:
337             break;
338     }
339 
340     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
341     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
342     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
343     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
344 
345     return NO_ERROR;
346 }
347 
initTexture(FileMap * map,int * width,int * height,bool premultiplyAlpha)348 status_t BootAnimation::initTexture(FileMap* map, int* width, int* height,
349     bool premultiplyAlpha) {
350     ATRACE_CALL();
351     AndroidBitmapInfo bitmapInfo;
352     void* pixels = decodeImage(map->getDataPtr(), map->getDataLength(), &bitmapInfo,
353         premultiplyAlpha);
354     auto pixelDeleter = std::unique_ptr<void, decltype(free)*>{ pixels, free };
355 
356     // FileMap memory is never released until application exit.
357     // Release it now as the texture is already loaded and the memory used for
358     // the packed resource can be released.
359     delete map;
360 
361     if (!pixels) {
362         return NO_INIT;
363     }
364 
365     const int w = bitmapInfo.width;
366     const int h = bitmapInfo.height;
367 
368     int tw = 1 << (31 - __builtin_clz(w));
369     int th = 1 << (31 - __builtin_clz(h));
370     if (tw < w) tw <<= 1;
371     if (th < h) th <<= 1;
372 
373     switch (bitmapInfo.format) {
374         case ANDROID_BITMAP_FORMAT_RGBA_8888:
375             if (!mUseNpotTextures && (tw != w || th != h)) {
376                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
377                         GL_UNSIGNED_BYTE, nullptr);
378                 glTexSubImage2D(GL_TEXTURE_2D, 0,
379                         0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
380             } else {
381                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
382                         GL_UNSIGNED_BYTE, pixels);
383             }
384             break;
385 
386         case ANDROID_BITMAP_FORMAT_RGB_565:
387             if (!mUseNpotTextures && (tw != w || th != h)) {
388                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
389                         GL_UNSIGNED_SHORT_5_6_5, nullptr);
390                 glTexSubImage2D(GL_TEXTURE_2D, 0,
391                         0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
392             } else {
393                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
394                         GL_UNSIGNED_SHORT_5_6_5, pixels);
395             }
396             break;
397         default:
398             break;
399     }
400 
401     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
402     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
403     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
404     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
405 
406     *width = w;
407     *height = h;
408 
409     return NO_ERROR;
410 }
411 
412 class BootAnimation::DisplayEventCallback : public LooperCallback {
413     BootAnimation* mBootAnimation;
414 
415 public:
DisplayEventCallback(BootAnimation * bootAnimation)416     DisplayEventCallback(BootAnimation* bootAnimation) {
417         ATRACE_CALL();
418         mBootAnimation = bootAnimation;
419     }
420 
handleEvent(int,int events,void *)421     int handleEvent(int /* fd */, int events, void* /* data */) {
422         ATRACE_CALL();
423         if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
424             ALOGE("Display event receiver pipe was closed or an error occurred. events=0x%x",
425                     events);
426             return 0; // remove the callback
427         }
428 
429         if (!(events & Looper::EVENT_INPUT)) {
430             ALOGW("Received spurious callback for unhandled poll event.  events=0x%x", events);
431             return 1; // keep the callback
432         }
433 
434         constexpr int kBufferSize = 100;
435         DisplayEventReceiver::Event buffer[kBufferSize];
436         ssize_t numEvents;
437         do {
438             numEvents = mBootAnimation->mDisplayEventReceiver->getEvents(buffer, kBufferSize);
439             for (size_t i = 0; i < static_cast<size_t>(numEvents); i++) {
440                 const auto& event = buffer[i];
441                 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
442                     SLOGV("Hotplug received");
443 
444                     if (!event.hotplug.connected) {
445                         // ignore hotplug disconnect
446                         continue;
447                     }
448                     auto token = SurfaceComposerClient::getPhysicalDisplayToken(
449                         event.header.displayId);
450 
451                     if (token != mBootAnimation->mDisplayToken) {
452                         // ignore hotplug of a secondary display
453                         continue;
454                     }
455 
456                     DisplayMode displayMode;
457                     const status_t error = SurfaceComposerClient::getActiveDisplayMode(
458                         mBootAnimation->mDisplayToken, &displayMode);
459                     if (error != NO_ERROR) {
460                         SLOGE("Can't get active display mode.");
461                     }
462                     mBootAnimation->resizeSurface(displayMode.resolution.getWidth(),
463                         displayMode.resolution.getHeight());
464                 }
465             }
466         } while (numEvents > 0);
467 
468         return 1;  // keep the callback
469     }
470 };
471 
getEglConfig(const EGLDisplay & display)472 EGLConfig BootAnimation::getEglConfig(const EGLDisplay& display) {
473     const EGLint attribs[] = {
474         EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
475         EGL_RED_SIZE,   8,
476         EGL_GREEN_SIZE, 8,
477         EGL_BLUE_SIZE,  8,
478         EGL_DEPTH_SIZE, 0,
479         EGL_NONE
480     };
481     EGLint numConfigs;
482     EGLConfig config;
483     eglChooseConfig(display, attribs, &config, 1, &numConfigs);
484     return config;
485 }
486 
limitSurfaceSize(int width,int height) const487 ui::Size BootAnimation::limitSurfaceSize(int width, int height) const {
488     ui::Size limited(width, height);
489     bool wasLimited = false;
490     const float aspectRatio = float(width) / float(height);
491     if (mMaxWidth != 0 && width > mMaxWidth) {
492         limited.height = mMaxWidth / aspectRatio;
493         limited.width = mMaxWidth;
494         wasLimited = true;
495     }
496     if (mMaxHeight != 0 && limited.height > mMaxHeight) {
497         limited.height = mMaxHeight;
498         limited.width = mMaxHeight * aspectRatio;
499         wasLimited = true;
500     }
501     SLOGV_IF(wasLimited, "Surface size has been limited to [%dx%d] from [%dx%d]",
502              limited.width, limited.height, width, height);
503     return limited;
504 }
505 
readyToRun()506 status_t BootAnimation::readyToRun() {
507     ATRACE_CALL();
508     mAssets.addDefaultAssets();
509 
510     const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds();
511     if (ids.empty()) {
512         SLOGE("Failed to get ID for any displays\n");
513         return NAME_NOT_FOUND;
514     }
515 
516     // this system property specifies multi-display IDs to show the boot animation
517     // multiple ids can be set with comma (,) as separator, for example:
518     // setprop persist.boot.animation.displays 19260422155234049,19261083906282754
519     Vector<PhysicalDisplayId> physicalDisplayIds;
520     char displayValue[PROPERTY_VALUE_MAX] = "";
521     property_get(DISPLAYS_PROP_NAME, displayValue, "");
522     bool isValid = displayValue[0] != '\0';
523     if (isValid) {
524         char *p = displayValue;
525         while (*p) {
526             if (!isdigit(*p) && *p != ',') {
527                 isValid = false;
528                 break;
529             }
530             p ++;
531         }
532         if (!isValid)
533             SLOGE("Invalid syntax for the value of system prop: %s", DISPLAYS_PROP_NAME);
534     }
535     if (isValid) {
536         std::istringstream stream(displayValue);
537         for (PhysicalDisplayId id; stream >> id.value; ) {
538             physicalDisplayIds.add(id);
539             if (stream.peek() == ',')
540                 stream.ignore();
541         }
542 
543         // the first specified display id is used to retrieve mDisplayToken
544         for (const auto id : physicalDisplayIds) {
545             if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
546                 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
547                     mDisplayToken = token;
548                     break;
549                 }
550             }
551         }
552     }
553 
554     // If the system property is not present or invalid, display 0 is used
555     if (mDisplayToken == nullptr) {
556         mDisplayToken = SurfaceComposerClient::getPhysicalDisplayToken(ids.front());
557         if (mDisplayToken == nullptr) {
558             return NAME_NOT_FOUND;
559         }
560     }
561 
562     DisplayMode displayMode;
563     const status_t error =
564             SurfaceComposerClient::getActiveDisplayMode(mDisplayToken, &displayMode);
565     if (error != NO_ERROR) {
566         return error;
567     }
568 
569     mMaxWidth = android::base::GetIntProperty("ro.surface_flinger.max_graphics_width", 0);
570     mMaxHeight = android::base::GetIntProperty("ro.surface_flinger.max_graphics_height", 0);
571     ui::Size resolution = displayMode.resolution;
572     resolution = limitSurfaceSize(resolution.width, resolution.height);
573     // create the native surface
574     sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
575             resolution.getWidth(), resolution.getHeight(), PIXEL_FORMAT_RGB_565,
576             ISurfaceComposerClient::eOpaque);
577 
578     SurfaceComposerClient::Transaction t;
579     if (isValid) {
580         // In the case of multi-display, boot animation shows on the specified displays
581         for (const auto id : physicalDisplayIds) {
582             if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
583                 if (const auto token = SurfaceComposerClient::getPhysicalDisplayToken(id)) {
584                     t.setDisplayLayerStack(token, ui::DEFAULT_LAYER_STACK);
585                 }
586             }
587         }
588         t.setLayerStack(control, ui::DEFAULT_LAYER_STACK);
589     }
590 
591     t.setLayer(control, 0x40000000)
592         .apply();
593 
594     sp<Surface> s = control->getSurface();
595 
596     // initialize opengl and egl
597     EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
598     eglInitialize(display, nullptr, nullptr);
599     EGLConfig config = getEglConfig(display);
600     EGLSurface surface = eglCreateWindowSurface(display, config, s.get(), nullptr);
601     // Initialize egl context with client version number 2.0.
602     EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
603     EGLContext context = eglCreateContext(display, config, nullptr, contextAttributes);
604     EGLint w, h;
605     eglQuerySurface(display, surface, EGL_WIDTH, &w);
606     eglQuerySurface(display, surface, EGL_HEIGHT, &h);
607 
608     if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
609         return NO_INIT;
610     }
611 
612     mDisplay = display;
613     mContext = context;
614     mSurface = surface;
615     mInitWidth = mWidth = w;
616     mInitHeight = mHeight = h;
617     mFlingerSurfaceControl = control;
618     mFlingerSurface = s;
619     mTargetInset = -1;
620 
621     // Rotate the boot animation according to the value specified in the sysprop
622     // ro.bootanim.set_orientation_<display_id>. Four values are supported: ORIENTATION_0,
623     // ORIENTATION_90, ORIENTATION_180 and ORIENTATION_270.
624     // If the value isn't specified or is ORIENTATION_0, nothing will be changed.
625     // This is needed to support having boot animation in orientations different from the natural
626     // device orientation. For example, on tablets that may want to keep natural orientation
627     // portrait for applications compatibility and to have the boot animation in landscape.
628     rotateAwayFromNaturalOrientationIfNeeded();
629 
630     projectSceneToWindow();
631 
632     // Register a display event receiver
633     mDisplayEventReceiver = std::make_unique<DisplayEventReceiver>();
634     status_t status = mDisplayEventReceiver->initCheck();
635     SLOGE_IF(status != NO_ERROR, "Initialization of DisplayEventReceiver failed with status: %d",
636             status);
637     mLooper->addFd(mDisplayEventReceiver->getFd(), 0, Looper::EVENT_INPUT,
638             new DisplayEventCallback(this), nullptr);
639 
640     return NO_ERROR;
641 }
642 
rotateAwayFromNaturalOrientationIfNeeded()643 void BootAnimation::rotateAwayFromNaturalOrientationIfNeeded() {
644     ATRACE_CALL();
645     const auto orientation = parseOrientationProperty();
646 
647     if (orientation == ui::ROTATION_0) {
648         // Do nothing if the sysprop isn't set or is set to ROTATION_0.
649         return;
650     }
651 
652     if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
653         std::swap(mWidth, mHeight);
654         std::swap(mInitWidth, mInitHeight);
655         mFlingerSurfaceControl->updateDefaultBufferSize(mWidth, mHeight);
656     }
657 
658     Rect displayRect(0, 0, mWidth, mHeight);
659     Rect layerStackRect(0, 0, mWidth, mHeight);
660 
661     SurfaceComposerClient::Transaction t;
662     t.setDisplayProjection(mDisplayToken, orientation, layerStackRect, displayRect);
663     t.apply();
664 }
665 
parseOrientationProperty()666 ui::Rotation BootAnimation::parseOrientationProperty() {
667     ATRACE_CALL();
668     const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
669     if (displayIds.size() == 0) {
670         return ui::ROTATION_0;
671     }
672     const auto displayId = displayIds[0];
673     const auto syspropName = [displayId] {
674         std::stringstream ss;
675         ss << "ro.bootanim.set_orientation_" << displayId.value;
676         return ss.str();
677     }();
678     auto syspropValue = android::base::GetProperty(syspropName, "");
679     if (syspropValue == "") {
680         syspropValue = android::base::GetProperty("ro.bootanim.set_orientation_logical_0", "");
681     }
682 
683     if (syspropValue == "ORIENTATION_90") {
684         return ui::ROTATION_90;
685     } else if (syspropValue == "ORIENTATION_180") {
686         return ui::ROTATION_180;
687     } else if (syspropValue == "ORIENTATION_270") {
688         return ui::ROTATION_270;
689     }
690     return ui::ROTATION_0;
691 }
692 
projectSceneToWindow()693 void BootAnimation::projectSceneToWindow() {
694     ATRACE_CALL();
695     glViewport(0, 0, mWidth, mHeight);
696     glScissor(0, 0, mWidth, mHeight);
697 }
698 
resizeSurface(int newWidth,int newHeight)699 void BootAnimation::resizeSurface(int newWidth, int newHeight) {
700     ATRACE_CALL();
701     // We assume this function is called on the animation thread.
702     if (newWidth == mWidth && newHeight == mHeight) {
703         return;
704     }
705     SLOGV("Resizing the boot animation surface to %d %d", newWidth, newHeight);
706 
707     eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
708     eglDestroySurface(mDisplay, mSurface);
709 
710     const auto limitedSize = limitSurfaceSize(newWidth, newHeight);
711     mWidth = limitedSize.width;
712     mHeight = limitedSize.height;
713 
714     mFlingerSurfaceControl->updateDefaultBufferSize(mWidth, mHeight);
715     EGLConfig config = getEglConfig(mDisplay);
716     EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr);
717     if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) {
718         SLOGE("Can't make the new surface current. Error %d", eglGetError());
719         return;
720     }
721 
722     projectSceneToWindow();
723 
724     mSurface = surface;
725 }
726 
preloadAnimation()727 bool BootAnimation::preloadAnimation() {
728     ATRACE_CALL();
729     findBootAnimationFile();
730     if (!mZipFileName.empty()) {
731         mAnimation = loadAnimation(mZipFileName);
732         return (mAnimation != nullptr);
733     }
734 
735     return false;
736 }
737 
findBootAnimationFileInternal(const std::vector<std::string> & files)738 bool BootAnimation::findBootAnimationFileInternal(const std::vector<std::string> &files) {
739     ATRACE_CALL();
740     for (const std::string& f : files) {
741         if (access(f.c_str(), R_OK) == 0) {
742             mZipFileName = f.c_str();
743             return true;
744         }
745     }
746     return false;
747 }
748 
findBootAnimationFile()749 void BootAnimation::findBootAnimationFile() {
750     ATRACE_CALL();
751     const bool playDarkAnim = android::base::GetIntProperty("ro.boot.theme", 0) == 1;
752     static const std::vector<std::string> bootFiles = {
753         APEX_BOOTANIMATION_FILE, playDarkAnim ? PRODUCT_BOOTANIMATION_DARK_FILE : PRODUCT_BOOTANIMATION_FILE,
754         OEM_BOOTANIMATION_FILE, SYSTEM_BOOTANIMATION_FILE
755     };
756     static const std::vector<std::string> shutdownFiles = {
757         PRODUCT_SHUTDOWNANIMATION_FILE, OEM_SHUTDOWNANIMATION_FILE, SYSTEM_SHUTDOWNANIMATION_FILE, ""
758     };
759     static const std::vector<std::string> userspaceRebootFiles = {
760         PRODUCT_USERSPACE_REBOOT_ANIMATION_FILE, OEM_USERSPACE_REBOOT_ANIMATION_FILE,
761         SYSTEM_USERSPACE_REBOOT_ANIMATION_FILE,
762     };
763 
764     if (android::base::GetBoolProperty("sys.init.userspace_reboot.in_progress", false)) {
765         findBootAnimationFileInternal(userspaceRebootFiles);
766     } else if (mShuttingDown) {
767         findBootAnimationFileInternal(shutdownFiles);
768     } else {
769         findBootAnimationFileInternal(bootFiles);
770     }
771 }
772 
compileShader(GLenum shaderType,const GLchar * source)773 GLuint compileShader(GLenum shaderType, const GLchar *source) {
774     ATRACE_CALL();
775     GLuint shader = glCreateShader(shaderType);
776     glShaderSource(shader, 1, &source, 0);
777     glCompileShader(shader);
778     GLint isCompiled = 0;
779     glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
780     if (isCompiled == GL_FALSE) {
781         SLOGE("Compile shader failed. Shader type: %d", shaderType);
782         GLint maxLength = 0;
783         glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
784         std::vector<GLchar> errorLog(maxLength);
785         glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
786         SLOGE("Shader compilation error: %s", &errorLog[0]);
787         return 0;
788     }
789     return shader;
790 }
791 
linkShader(GLuint vertexShader,GLuint fragmentShader)792 GLuint linkShader(GLuint vertexShader, GLuint fragmentShader) {
793     ATRACE_CALL();
794     GLuint program = glCreateProgram();
795     glAttachShader(program, vertexShader);
796     glAttachShader(program, fragmentShader);
797     glLinkProgram(program);
798     GLint isLinked = 0;
799     glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
800     if (isLinked == GL_FALSE) {
801         SLOGE("Linking shader failed. Shader handles: vert %d, frag %d",
802             vertexShader, fragmentShader);
803         return 0;
804     }
805     return program;
806 }
807 
initShaders()808 void BootAnimation::initShaders() {
809     ATRACE_CALL();
810     bool dynamicColoringEnabled = mAnimation != nullptr && mAnimation->dynamicColoringEnabled;
811     GLuint vertexShader = compileShader(GL_VERTEX_SHADER, (const GLchar *)VERTEX_SHADER_SOURCE);
812     GLuint imageFragmentShader =
813         compileShader(GL_FRAGMENT_SHADER, dynamicColoringEnabled
814             ? (const GLchar *)IMAGE_FRAG_DYNAMIC_COLORING_SHADER_SOURCE
815             : (const GLchar *)IMAGE_FRAG_SHADER_SOURCE);
816     GLuint textFragmentShader =
817         compileShader(GL_FRAGMENT_SHADER, (const GLchar *)TEXT_FRAG_SHADER_SOURCE);
818 
819     // Initialize image shader.
820     mImageShader = linkShader(vertexShader, imageFragmentShader);
821     GLint positionLocation = glGetAttribLocation(mImageShader, A_POSITION);
822     GLint uvLocation = glGetAttribLocation(mImageShader, A_UV);
823     mImageTextureLocation = glGetUniformLocation(mImageShader, U_TEXTURE);
824     mImageFadeLocation = glGetUniformLocation(mImageShader, U_FADE);
825     glEnableVertexAttribArray(positionLocation);
826     glVertexAttribPointer(positionLocation, 2,  GL_FLOAT, GL_FALSE, 0, quadPositions);
827     glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
828     glEnableVertexAttribArray(uvLocation);
829 
830     // Initialize text shader.
831     mTextShader = linkShader(vertexShader, textFragmentShader);
832     positionLocation = glGetAttribLocation(mTextShader, A_POSITION);
833     uvLocation = glGetAttribLocation(mTextShader, A_UV);
834     mTextTextureLocation = glGetUniformLocation(mTextShader, U_TEXTURE);
835     mTextCropAreaLocation = glGetUniformLocation(mTextShader, U_CROP_AREA);
836     glEnableVertexAttribArray(positionLocation);
837     glVertexAttribPointer(positionLocation, 2,  GL_FLOAT, GL_FALSE, 0, quadPositions);
838     glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, quadUVs);
839     glEnableVertexAttribArray(uvLocation);
840 }
841 
threadLoop()842 bool BootAnimation::threadLoop() {
843     ATRACE_CALL();
844     bool result;
845     initShaders();
846 
847     // We have no bootanimation file, so we use the stock android logo
848     // animation.
849     if (mZipFileName.empty()) {
850         ALOGD("No animation file");
851         result = android();
852     } else {
853         result = movie();
854     }
855 
856     mCallbacks->shutdown();
857     eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
858     eglDestroyContext(mDisplay, mContext);
859     eglDestroySurface(mDisplay, mSurface);
860     mFlingerSurface.clear();
861     mFlingerSurfaceControl.clear();
862     eglTerminate(mDisplay);
863     eglReleaseThread();
864     IPCThreadState::self()->stopProcess();
865     return result;
866 }
867 
android()868 bool BootAnimation::android() {
869     ATRACE_CALL();
870     glActiveTexture(GL_TEXTURE0);
871 
872     SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
873             elapsedRealtime());
874     initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
875     initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
876 
877     mCallbacks->init({});
878 
879     // clear screen
880     glDisable(GL_DITHER);
881     glDisable(GL_SCISSOR_TEST);
882     glUseProgram(mImageShader);
883 
884     glClearColor(0,0,0,1);
885     glClear(GL_COLOR_BUFFER_BIT);
886     eglSwapBuffers(mDisplay, mSurface);
887 
888     // Blend state
889     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
890 
891     const nsecs_t startTime = systemTime();
892     do {
893         processDisplayEvents();
894         const GLint xc = (mWidth  - mAndroid[0].w) / 2;
895         const GLint yc = (mHeight - mAndroid[0].h) / 2;
896         const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
897         glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
898                 updateRect.height());
899 
900         nsecs_t now = systemTime();
901         double time = now - startTime;
902         float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
903         GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
904         GLint x = xc - offset;
905 
906         glDisable(GL_SCISSOR_TEST);
907         glClear(GL_COLOR_BUFFER_BIT);
908 
909         glEnable(GL_SCISSOR_TEST);
910         glDisable(GL_BLEND);
911         glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
912         drawTexturedQuad(x,                 yc, mAndroid[1].w, mAndroid[1].h);
913         drawTexturedQuad(x + mAndroid[1].w, yc, mAndroid[1].w, mAndroid[1].h);
914 
915         glEnable(GL_BLEND);
916         glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
917         drawTexturedQuad(xc, yc, mAndroid[0].w, mAndroid[0].h);
918 
919         EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
920         if (res == EGL_FALSE)
921             break;
922 
923         // 12fps: don't animate too fast to preserve CPU
924         const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
925         if (sleepTime > 0)
926             usleep(sleepTime);
927 
928         checkExit();
929     } while (!exitPending());
930 
931     glDeleteTextures(1, &mAndroid[0].name);
932     glDeleteTextures(1, &mAndroid[1].name);
933     return false;
934 }
935 
checkExit()936 void BootAnimation::checkExit() {
937     ATRACE_CALL();
938     // Allow surface flinger to gracefully request shutdown
939     char value[PROPERTY_VALUE_MAX];
940     property_get(EXIT_PROP_NAME, value, "0");
941     int exitnow = atoi(value);
942     if (exitnow) {
943         requestExit();
944     }
945 }
946 
validClock(const Animation::Part & part)947 bool BootAnimation::validClock(const Animation::Part& part) {
948     ATRACE_CALL();
949     return part.clockPosX != TEXT_MISSING_VALUE && part.clockPosY != TEXT_MISSING_VALUE;
950 }
951 
parseTextCoord(const char * str,int * dest)952 bool parseTextCoord(const char* str, int* dest) {
953     ATRACE_CALL();
954     if (strcmp("c", str) == 0) {
955         *dest = TEXT_CENTER_VALUE;
956         return true;
957     }
958 
959     char* end;
960     int val = (int) strtol(str, &end, 0);
961     if (end == str || *end != '\0' || val == INT_MAX || val == INT_MIN) {
962         return false;
963     }
964     *dest = val;
965     return true;
966 }
967 
968 // Parse two position coordinates. If only string is non-empty, treat it as the y value.
parsePosition(const char * str1,const char * str2,int * x,int * y)969 void parsePosition(const char* str1, const char* str2, int* x, int* y) {
970     ATRACE_CALL();
971     bool success = false;
972     if (strlen(str1) == 0) {  // No values were specified
973         // success = false
974     } else if (strlen(str2) == 0) {  // we have only one value
975         if (parseTextCoord(str1, y)) {
976             *x = TEXT_CENTER_VALUE;
977             success = true;
978         }
979     } else {
980         if (parseTextCoord(str1, x) && parseTextCoord(str2, y)) {
981             success = true;
982         }
983     }
984 
985     if (!success) {
986         *x = TEXT_MISSING_VALUE;
987         *y = TEXT_MISSING_VALUE;
988     }
989 }
990 
991 // Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
992 // characters in str is a hex number in [0, 255], which are converted to
993 // floating point values in the range [0.0, 1.0] and placed in the
994 // corresponding elements of color.
995 //
996 // If the input string isn't valid, parseColor returns false and color is
997 // left unchanged.
parseColor(const char str[7],float color[3])998 static bool parseColor(const char str[7], float color[3]) {
999     ATRACE_CALL();
1000     float tmpColor[3];
1001     for (int i = 0; i < 3; i++) {
1002         int val = 0;
1003         for (int j = 0; j < 2; j++) {
1004             val *= 16;
1005             char c = str[2*i + j];
1006             if      (c >= '0' && c <= '9') val += c - '0';
1007             else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
1008             else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
1009             else                           return false;
1010         }
1011         tmpColor[i] = static_cast<float>(val) / 255.0f;
1012     }
1013     memcpy(color, tmpColor, sizeof(tmpColor));
1014     return true;
1015 }
1016 
1017 // Parse a color represented as a signed decimal int string.
1018 // E.g. "-2757722" (whose hex 2's complement is 0xFFD5EBA6).
1019 // If the input color string is empty, set color with values in defaultColor.
parseColorDecimalString(const std::string & colorString,float color[3],float defaultColor[3])1020 static void parseColorDecimalString(const std::string& colorString,
1021     float color[3], float defaultColor[3]) {
1022     ATRACE_CALL();
1023     if (colorString == "") {
1024         memcpy(color, defaultColor, sizeof(float) * 3);
1025         return;
1026     }
1027     int colorInt = atoi(colorString.c_str());
1028     color[0] = ((float)((colorInt >> 16) & 0xFF)) / 0xFF; // r
1029     color[1] = ((float)((colorInt >> 8) & 0xFF)) / 0xFF; // g
1030     color[2] = ((float)(colorInt & 0xFF)) / 0xFF; // b
1031 }
1032 
readFile(ZipFileRO * zip,const char * name,String8 & outString)1033 static bool readFile(ZipFileRO* zip, const char* name, String8& outString) {
1034     ATRACE_CALL();
1035     ZipEntryRO entry = zip->findEntryByName(name);
1036     SLOGE_IF(!entry, "couldn't find %s", name);
1037     if (!entry) {
1038         return false;
1039     }
1040 
1041     FileMap* entryMap = zip->createEntryFileMap(entry);
1042     zip->releaseEntry(entry);
1043     SLOGE_IF(!entryMap, "entryMap is null");
1044     if (!entryMap) {
1045         return false;
1046     }
1047 
1048     outString = String8((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
1049     delete entryMap;
1050     return true;
1051 }
1052 
1053 // The font image should be a 96x2 array of character images.  The
1054 // columns are the printable ASCII characters 0x20 - 0x7f.  The
1055 // top row is regular text; the bottom row is bold.
initFont(Font * font,const char * fallback)1056 status_t BootAnimation::initFont(Font* font, const char* fallback) {
1057     ATRACE_CALL();
1058     status_t status = NO_ERROR;
1059 
1060     if (font->map != nullptr) {
1061         glGenTextures(1, &font->texture.name);
1062         glBindTexture(GL_TEXTURE_2D, font->texture.name);
1063 
1064         status = initTexture(font->map, &font->texture.w, &font->texture.h);
1065 
1066         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1067         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1068         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1069         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1070     } else if (fallback != nullptr) {
1071         status = initTexture(&font->texture, mAssets, fallback);
1072     } else {
1073         return NO_INIT;
1074     }
1075 
1076     if (status == NO_ERROR) {
1077         font->char_width = font->texture.w / FONT_NUM_COLS;
1078         font->char_height = font->texture.h / FONT_NUM_ROWS / 2;  // There are bold and regular rows
1079     }
1080 
1081     return status;
1082 }
1083 
drawText(const char * str,const Font & font,bool bold,int * x,int * y)1084 void BootAnimation::drawText(const char* str, const Font& font, bool bold, int* x, int* y) {
1085     ATRACE_CALL();
1086     glEnable(GL_BLEND);  // Allow us to draw on top of the animation
1087     glBindTexture(GL_TEXTURE_2D, font.texture.name);
1088     glUseProgram(mTextShader);
1089     glUniform1i(mTextTextureLocation, 0);
1090 
1091     const int len = strlen(str);
1092     const int strWidth = font.char_width * len;
1093 
1094     if (*x == TEXT_CENTER_VALUE) {
1095         *x = (mWidth - strWidth) / 2;
1096     } else if (*x < 0) {
1097         *x = mWidth + *x - strWidth;
1098     }
1099     if (*y == TEXT_CENTER_VALUE) {
1100         *y = (mHeight - font.char_height) / 2;
1101     } else if (*y < 0) {
1102         *y = mHeight + *y - font.char_height;
1103     }
1104 
1105     for (int i = 0; i < len; i++) {
1106         char c = str[i];
1107 
1108         if (c < FONT_BEGIN_CHAR || c > FONT_END_CHAR) {
1109             c = '?';
1110         }
1111 
1112         // Crop the texture to only the pixels in the current glyph
1113         const int charPos = (c - FONT_BEGIN_CHAR);  // Position in the list of valid characters
1114         const int row = charPos / FONT_NUM_COLS;
1115         const int col = charPos % FONT_NUM_COLS;
1116         // Bold fonts are expected in the second half of each row.
1117         float v0 = (row + (bold ? 0.5f : 0.0f)) / FONT_NUM_ROWS;
1118         float u0 = ((float)col) / FONT_NUM_COLS;
1119         float v1 = v0 + 1.0f / FONT_NUM_ROWS / 2;
1120         float u1 = u0 + 1.0f / FONT_NUM_COLS;
1121         glUniform4f(mTextCropAreaLocation, u0, v0, u1, v1);
1122         drawTexturedQuad(*x, *y, font.char_width, font.char_height);
1123 
1124         *x += font.char_width;
1125     }
1126 
1127     glDisable(GL_BLEND);  // Return to the animation's default behaviour
1128     glBindTexture(GL_TEXTURE_2D, 0);
1129 }
1130 
1131 // We render 12 or 24 hour time.
drawClock(const Font & font,const int xPos,const int yPos)1132 void BootAnimation::drawClock(const Font& font, const int xPos, const int yPos) {
1133     ATRACE_CALL();
1134     static constexpr char TIME_FORMAT_12[] = "%l:%M";
1135     static constexpr char TIME_FORMAT_24[] = "%H:%M";
1136     static constexpr int TIME_LENGTH = 6;
1137 
1138     time_t rawtime;
1139     time(&rawtime);
1140     struct tm* timeInfo = localtime(&rawtime);
1141 
1142     char timeBuff[TIME_LENGTH];
1143     const char* timeFormat = mTimeFormat12Hour ? TIME_FORMAT_12 : TIME_FORMAT_24;
1144     size_t length = strftime(timeBuff, TIME_LENGTH, timeFormat, timeInfo);
1145 
1146     if (length != TIME_LENGTH - 1) {
1147         SLOGE("Couldn't format time; abandoning boot animation clock");
1148         mClockEnabled = false;
1149         return;
1150     }
1151 
1152     char* out = timeBuff[0] == ' ' ? &timeBuff[1] : &timeBuff[0];
1153     int x = xPos;
1154     int y = yPos;
1155     drawText(out, font, false, &x, &y);
1156 }
1157 
drawProgress(int percent,const Font & font,const int xPos,const int yPos)1158 void BootAnimation::drawProgress(int percent, const Font& font, const int xPos, const int yPos) {
1159     ATRACE_CALL();
1160     static constexpr int PERCENT_LENGTH = 5;
1161 
1162     char percentBuff[PERCENT_LENGTH];
1163     // ';' has the ascii code just after ':', and the font resource contains '%'
1164     // for that ascii code.
1165     sprintf(percentBuff, "%d;", percent);
1166     int x = xPos;
1167     int y = yPos;
1168     drawText(percentBuff, font, false, &x, &y);
1169 }
1170 
parseAnimationDesc(Animation & animation)1171 bool BootAnimation::parseAnimationDesc(Animation& animation)  {
1172     ATRACE_CALL();
1173     String8 desString;
1174 
1175     if (!readFile(animation.zip, "desc.txt", desString)) {
1176         return false;
1177     }
1178     char const* s = desString.c_str();
1179     std::string dynamicColoringPartName = "";
1180     bool postDynamicColoring = false;
1181 
1182     // Parse the description file
1183     for (;;) {
1184         const char* endl = strstr(s, "\n");
1185         if (endl == nullptr) break;
1186         String8 line(s, endl - s);
1187         const char* l = line.c_str();
1188         int fps = 0;
1189         int width = 0;
1190         int height = 0;
1191         int count = 0;
1192         int pause = 0;
1193         int progress = 0;
1194         int framesToFadeCount = 0;
1195         int colorTransitionStart = 0;
1196         int colorTransitionEnd = 0;
1197         char path[ANIM_ENTRY_NAME_MAX];
1198         char color[7] = "000000"; // default to black if unspecified
1199         char clockPos1[TEXT_POS_LEN_MAX + 1] = "";
1200         char clockPos2[TEXT_POS_LEN_MAX + 1] = "";
1201         char dynamicColoringPartNameBuffer[ANIM_ENTRY_NAME_MAX];
1202         char pathType;
1203         // start colors default to black if unspecified
1204         char start_color_0[7] = "000000";
1205         char start_color_1[7] = "000000";
1206         char start_color_2[7] = "000000";
1207         char start_color_3[7] = "000000";
1208 
1209         int nextReadPos;
1210 
1211         if (strlen(l) == 0) {
1212             s = ++endl;
1213             continue;
1214         }
1215 
1216         int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress);
1217         if (topLineNumbers == 3 || topLineNumbers == 4) {
1218             // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress);
1219             animation.width = width;
1220             animation.height = height;
1221             animation.fps = fps;
1222             if (topLineNumbers == 4) {
1223               animation.progressEnabled = (progress != 0);
1224             } else {
1225               animation.progressEnabled = false;
1226             }
1227         } else if (sscanf(l, "dynamic_colors %" STRTO(ANIM_PATH_MAX) "s #%6s #%6s #%6s #%6s %d %d",
1228             dynamicColoringPartNameBuffer,
1229             start_color_0, start_color_1, start_color_2, start_color_3,
1230             &colorTransitionStart, &colorTransitionEnd)) {
1231             animation.dynamicColoringEnabled = true;
1232             parseColor(start_color_0, animation.startColors[0]);
1233             parseColor(start_color_1, animation.startColors[1]);
1234             parseColor(start_color_2, animation.startColors[2]);
1235             parseColor(start_color_3, animation.startColors[3]);
1236             animation.colorTransitionStart = colorTransitionStart;
1237             animation.colorTransitionEnd = colorTransitionEnd;
1238             dynamicColoringPartName = std::string(dynamicColoringPartNameBuffer);
1239         } else if (sscanf(l, "%c %d %d %" STRTO(ANIM_PATH_MAX) "s%n",
1240                           &pathType, &count, &pause, path, &nextReadPos) >= 4) {
1241             if (pathType == 'f') {
1242                 sscanf(l + nextReadPos, " %d #%6s %16s %16s", &framesToFadeCount, color, clockPos1,
1243                        clockPos2);
1244             } else {
1245                 sscanf(l + nextReadPos, " #%6s %16s %16s", color, clockPos1, clockPos2);
1246             }
1247             // SLOGD("> type=%c, count=%d, pause=%d, path=%s, framesToFadeCount=%d, color=%s, "
1248             //       "clockPos1=%s, clockPos2=%s",
1249             //       pathType, count, pause, path, framesToFadeCount, color, clockPos1, clockPos2);
1250             Animation::Part part;
1251             if (path == dynamicColoringPartName) {
1252                 // Part is specified to use dynamic coloring.
1253                 part.useDynamicColoring = true;
1254                 part.postDynamicColoring = false;
1255                 postDynamicColoring = true;
1256             } else {
1257                 // Part does not use dynamic coloring.
1258                 part.useDynamicColoring = false;
1259                 part.postDynamicColoring =  postDynamicColoring;
1260             }
1261             part.playUntilComplete = pathType == 'c';
1262             part.framesToFadeCount = framesToFadeCount;
1263             part.count = count;
1264             part.pause = pause;
1265             part.path = path;
1266             part.audioData = nullptr;
1267             part.animation = nullptr;
1268             if (!parseColor(color, part.backgroundColor)) {
1269                 SLOGE("> invalid color '#%s'", color);
1270                 part.backgroundColor[0] = 0.0f;
1271                 part.backgroundColor[1] = 0.0f;
1272                 part.backgroundColor[2] = 0.0f;
1273             }
1274             parsePosition(clockPos1, clockPos2, &part.clockPosX, &part.clockPosY);
1275             animation.parts.add(part);
1276         }
1277         else if (strcmp(l, "$SYSTEM") == 0) {
1278             // SLOGD("> SYSTEM");
1279             Animation::Part part;
1280             part.playUntilComplete = false;
1281             part.framesToFadeCount = 0;
1282             part.count = 1;
1283             part.pause = 0;
1284             part.audioData = nullptr;
1285             part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
1286             if (part.animation != nullptr)
1287                 animation.parts.add(part);
1288         }
1289         s = ++endl;
1290     }
1291 
1292     return true;
1293 }
1294 
preloadZip(Animation & animation)1295 bool BootAnimation::preloadZip(Animation& animation) {
1296     ATRACE_CALL();
1297     // read all the data structures
1298     const size_t pcount = animation.parts.size();
1299     void *cookie = nullptr;
1300     ZipFileRO* zip = animation.zip;
1301     if (!zip->startIteration(&cookie)) {
1302         return false;
1303     }
1304 
1305     ZipEntryRO entry;
1306     char name[ANIM_ENTRY_NAME_MAX];
1307     while ((entry = zip->nextEntry(cookie)) != nullptr) {
1308         const int foundEntryName = zip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
1309         if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
1310             SLOGE("Error fetching entry file name");
1311             continue;
1312         }
1313 
1314         const std::filesystem::path entryName(name);
1315         const std::filesystem::path path(entryName.parent_path());
1316         const std::filesystem::path leaf(entryName.filename());
1317         if (!leaf.empty()) {
1318             if (entryName == CLOCK_FONT_ZIP_NAME) {
1319                 FileMap* map = zip->createEntryFileMap(entry);
1320                 if (map) {
1321                     animation.clockFont.map = map;
1322                 }
1323                 continue;
1324             }
1325 
1326             if (entryName == PROGRESS_FONT_ZIP_NAME) {
1327                 FileMap* map = zip->createEntryFileMap(entry);
1328                 if (map) {
1329                     animation.progressFont.map = map;
1330                 }
1331                 continue;
1332             }
1333 
1334             for (size_t j = 0; j < pcount; j++) {
1335                 if (path.string() == animation.parts[j].path.c_str()) {
1336                     uint16_t method;
1337                     // supports only stored png files
1338                     if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr,
1339                             nullptr, nullptr)) {
1340                         if (method == ZipFileRO::kCompressStored) {
1341                             FileMap* map = zip->createEntryFileMap(entry);
1342                             if (map) {
1343                                 Animation::Part& part(animation.parts.editItemAt(j));
1344                                 if (leaf == "audio.wav") {
1345                                     // a part may have at most one audio file
1346                                     part.audioData = (uint8_t *)map->getDataPtr();
1347                                     part.audioLength = map->getDataLength();
1348                                 } else if (leaf == "trim.txt") {
1349                                     part.trimData = String8((char const*)map->getDataPtr(),
1350                                                         map->getDataLength());
1351                                 } else {
1352                                     Animation::Frame frame;
1353                                     frame.name = leaf.c_str();
1354                                     frame.map = map;
1355                                     frame.trimWidth = animation.width;
1356                                     frame.trimHeight = animation.height;
1357                                     frame.trimX = 0;
1358                                     frame.trimY = 0;
1359                                     part.frames.add(frame);
1360                                 }
1361                             }
1362                         } else {
1363                             SLOGE("bootanimation.zip is compressed; must be only stored");
1364                         }
1365                     }
1366                 }
1367             }
1368         }
1369     }
1370 
1371     // If there is trimData present, override the positioning defaults.
1372     for (Animation::Part& part : animation.parts) {
1373         const char* trimDataStr = part.trimData.c_str();
1374         for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
1375             const char* endl = strstr(trimDataStr, "\n");
1376             // No more trimData for this part.
1377             if (endl == nullptr) {
1378                 break;
1379             }
1380             String8 line(trimDataStr, endl - trimDataStr);
1381             const char* lineStr = line.c_str();
1382             trimDataStr = ++endl;
1383             int width = 0, height = 0, x = 0, y = 0;
1384             if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
1385                 Animation::Frame& frame(part.frames.editItemAt(frameIdx));
1386                 frame.trimWidth = width;
1387                 frame.trimHeight = height;
1388                 frame.trimX = x;
1389                 frame.trimY = y;
1390             } else {
1391                 SLOGE("Error parsing trim.txt, line: %s", lineStr);
1392                 break;
1393             }
1394         }
1395     }
1396 
1397     zip->endIteration(cookie);
1398 
1399     return true;
1400 }
1401 
movie()1402 bool BootAnimation::movie() {
1403     ATRACE_CALL();
1404     if (mAnimation == nullptr) {
1405         mAnimation = loadAnimation(mZipFileName);
1406     }
1407 
1408     if (mAnimation == nullptr)
1409         return false;
1410 
1411     // mCallbacks->init() may get called recursively,
1412     // this loop is needed to get the same results
1413     for (const Animation::Part& part : mAnimation->parts) {
1414         if (part.animation != nullptr) {
1415             mCallbacks->init(part.animation->parts);
1416         }
1417     }
1418     mCallbacks->init(mAnimation->parts);
1419 
1420     bool anyPartHasClock = false;
1421     for (size_t i=0; i < mAnimation->parts.size(); i++) {
1422         if(validClock(mAnimation->parts[i])) {
1423             anyPartHasClock = true;
1424             break;
1425         }
1426     }
1427     if (!anyPartHasClock) {
1428         mClockEnabled = false;
1429     } else if (!android::base::GetBoolProperty(CLOCK_ENABLED_PROP_NAME, false)) {
1430         mClockEnabled = false;
1431     }
1432 
1433     // Check if npot textures are supported
1434     mUseNpotTextures = false;
1435     String8 gl_extensions;
1436     const char* exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
1437     if (!exts) {
1438         glGetError();
1439     } else {
1440         gl_extensions = exts;
1441         if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
1442             (gl_extensions.find("GL_OES_texture_npot") != -1)) {
1443             mUseNpotTextures = true;
1444         }
1445     }
1446 
1447     // Blend required to draw time on top of animation frames.
1448     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1449     glDisable(GL_DITHER);
1450     glDisable(GL_SCISSOR_TEST);
1451     glDisable(GL_BLEND);
1452 
1453     glEnable(GL_TEXTURE_2D);
1454     glBindTexture(GL_TEXTURE_2D, 0);
1455     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1456     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1457     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1458     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1459     bool clockFontInitialized = false;
1460     if (mClockEnabled) {
1461         clockFontInitialized =
1462             (initFont(&mAnimation->clockFont, CLOCK_FONT_ASSET) == NO_ERROR);
1463         mClockEnabled = clockFontInitialized;
1464     }
1465 
1466     initFont(&mAnimation->progressFont, PROGRESS_FONT_ASSET);
1467 
1468     if (mClockEnabled && !updateIsTimeAccurate()) {
1469         mTimeCheckThread = new TimeCheckThread(this);
1470         mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
1471     }
1472 
1473     if (mAnimation->dynamicColoringEnabled) {
1474         initDynamicColors();
1475     }
1476 
1477     playAnimation(*mAnimation);
1478 
1479     if (mTimeCheckThread != nullptr) {
1480         mTimeCheckThread->requestExit();
1481         mTimeCheckThread = nullptr;
1482     }
1483 
1484     if (clockFontInitialized) {
1485         glDeleteTextures(1, &mAnimation->clockFont.texture.name);
1486     }
1487 
1488     releaseAnimation(mAnimation);
1489     mAnimation = nullptr;
1490 
1491     return false;
1492 }
1493 
shouldStopPlayingPart(const Animation::Part & part,const int fadedFramesCount,const int lastDisplayedProgress)1494 bool BootAnimation::shouldStopPlayingPart(const Animation::Part& part,
1495                                           const int fadedFramesCount,
1496                                           const int lastDisplayedProgress) {
1497     ATRACE_CALL();
1498     // stop playing only if it is time to exit and it's a partial part which has been faded out
1499     return exitPending() && !part.playUntilComplete && fadedFramesCount >= part.framesToFadeCount &&
1500         (lastDisplayedProgress == 0 || lastDisplayedProgress == 100);
1501 }
1502 
1503 // Linear mapping from range <a1, a2> to range <b1, b2>
mapLinear(float x,float a1,float a2,float b1,float b2)1504 float mapLinear(float x, float a1, float a2, float b1, float b2) {
1505     return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
1506 }
1507 
drawTexturedQuad(float xStart,float yStart,float width,float height)1508 void BootAnimation::drawTexturedQuad(float xStart, float yStart, float width, float height) {
1509     ATRACE_CALL();
1510     // Map coordinates from screen space to world space.
1511     float x0 = mapLinear(xStart, 0, mWidth, -1, 1);
1512     float y0 = mapLinear(yStart, 0, mHeight, -1, 1);
1513     float x1 = mapLinear(xStart + width, 0, mWidth, -1, 1);
1514     float y1 = mapLinear(yStart + height, 0, mHeight, -1, 1);
1515     // Update quad vertex positions.
1516     quadPositions[0] = x0;
1517     quadPositions[1] = y0;
1518     quadPositions[2] = x1;
1519     quadPositions[3] = y0;
1520     quadPositions[4] = x1;
1521     quadPositions[5] = y1;
1522     quadPositions[6] = x1;
1523     quadPositions[7] = y1;
1524     quadPositions[8] = x0;
1525     quadPositions[9] = y1;
1526     quadPositions[10] = x0;
1527     quadPositions[11] = y0;
1528     glDrawArrays(GL_TRIANGLES, 0,
1529         sizeof(quadPositions) / sizeof(quadPositions[0]) / 2);
1530 }
1531 
initDynamicColors()1532 void BootAnimation::initDynamicColors() {
1533     ATRACE_CALL();
1534     for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1535         const auto syspropName = "persist.bootanim.color" + std::to_string(i + 1);
1536         const auto syspropValue = android::base::GetProperty(syspropName, "");
1537         if (syspropValue != "") {
1538             SLOGI("Loaded dynamic color: %s -> %s", syspropName.c_str(), syspropValue.c_str());
1539             mDynamicColorsApplied = true;
1540         }
1541         parseColorDecimalString(syspropValue,
1542             mAnimation->endColors[i], mAnimation->startColors[i]);
1543     }
1544     glUseProgram(mImageShader);
1545     SLOGI("Dynamically coloring boot animation. Sysprops loaded? %i", mDynamicColorsApplied);
1546     for (int i = 0; i < DYNAMIC_COLOR_COUNT; i++) {
1547         float *startColor = mAnimation->startColors[i];
1548         float *endColor = mAnimation->endColors[i];
1549         glUniform3f(glGetUniformLocation(mImageShader,
1550             (U_START_COLOR_PREFIX + std::to_string(i)).c_str()),
1551             startColor[0], startColor[1], startColor[2]);
1552         glUniform3f(glGetUniformLocation(mImageShader,
1553             (U_END_COLOR_PREFIX + std::to_string(i)).c_str()),
1554             endColor[0], endColor[1], endColor[2]);
1555     }
1556     mImageColorProgressLocation = glGetUniformLocation(mImageShader, U_COLOR_PROGRESS);
1557 }
1558 
playAnimation(const Animation & animation)1559 bool BootAnimation::playAnimation(const Animation& animation) {
1560     ATRACE_CALL();
1561     const size_t pcount = animation.parts.size();
1562     nsecs_t frameDuration = s2ns(1) / animation.fps;
1563 
1564     SLOGD("%sAnimationShownTiming start time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1565             elapsedRealtime());
1566 
1567     int fadedFramesCount = 0;
1568     int lastDisplayedProgress = 0;
1569     int colorTransitionStart = animation.colorTransitionStart;
1570     int colorTransitionEnd = animation.colorTransitionEnd;
1571     for (size_t i=0 ; i<pcount ; i++) {
1572         const Animation::Part& part(animation.parts[i]);
1573         const size_t fcount = part.frames.size();
1574         glBindTexture(GL_TEXTURE_2D, 0);
1575 
1576         // Handle animation package
1577         if (part.animation != nullptr) {
1578             playAnimation(*part.animation);
1579             if (exitPending())
1580                 break;
1581             continue; //to next part
1582         }
1583 
1584         // process the part not only while the count allows but also if already fading
1585         for (int r=0 ; !part.count || r<part.count || fadedFramesCount > 0 ; r++) {
1586             if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
1587 
1588             // It's possible that the sysprops were not loaded yet at this boot phase.
1589             // If that's the case, then we should keep trying until they are available.
1590             if (animation.dynamicColoringEnabled && !mDynamicColorsApplied
1591                 && (part.useDynamicColoring || part.postDynamicColoring)) {
1592                 SLOGD("Trying to load dynamic color sysprops.");
1593                 initDynamicColors();
1594                 if (mDynamicColorsApplied) {
1595                     // Sysprops were loaded. Next step is to adjust the animation if we loaded
1596                     // the colors after the animation should have started.
1597                     const int transitionLength = colorTransitionEnd - colorTransitionStart;
1598                     if (part.postDynamicColoring) {
1599                         colorTransitionStart = 0;
1600                         colorTransitionEnd = fmin(transitionLength, fcount - 1);
1601                     }
1602                 }
1603             }
1604 
1605             mCallbacks->playPart(i, part, r);
1606 
1607             glClearColor(
1608                     part.backgroundColor[0],
1609                     part.backgroundColor[1],
1610                     part.backgroundColor[2],
1611                     1.0f);
1612 
1613             ALOGD("Playing files = %s/%s, Requested repeat = %d, playUntilComplete = %s",
1614                     animation.fileName.c_str(), part.path.c_str(), part.count,
1615                     part.playUntilComplete ? "true" : "false");
1616 
1617             // For the last animation, if we have progress indicator from
1618             // the system, display it.
1619             int currentProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1620             bool displayProgress = animation.progressEnabled &&
1621                 (i == (pcount -1)) && currentProgress != 0;
1622 
1623             for (size_t j=0 ; j<fcount ; j++) {
1624                 if (shouldStopPlayingPart(part, fadedFramesCount, lastDisplayedProgress)) break;
1625 
1626                 // Color progress is
1627                 // - the animation progress, normalized from
1628                 //   [colorTransitionStart,colorTransitionEnd] to [0, 1] for the dynamic coloring
1629                 //   part.
1630                 // - 0 for parts that come before,
1631                 // - 1 for parts that come after.
1632                 float colorProgress = part.useDynamicColoring
1633                     ? fmin(fmax(
1634                         ((float)j - colorTransitionStart) /
1635                             fmax(colorTransitionEnd - colorTransitionStart, 1.0f), 0.0f), 1.0f)
1636                     : (part.postDynamicColoring ? 1 : 0);
1637 
1638                 processDisplayEvents();
1639 
1640                 const double ratio_w = static_cast<double>(mWidth) / mInitWidth;
1641                 const double ratio_h = static_cast<double>(mHeight) / mInitHeight;
1642                 const int animationX = (mWidth - animation.width * ratio_w) / 2;
1643                 const int animationY = (mHeight - animation.height * ratio_h) / 2;
1644 
1645                 const Animation::Frame& frame(part.frames[j]);
1646                 nsecs_t lastFrame = systemTime();
1647 
1648                 if (r > 0) {
1649                     glBindTexture(GL_TEXTURE_2D, frame.tid);
1650                 } else {
1651                     if (part.count != 1) {
1652                         glGenTextures(1, &frame.tid);
1653                         glBindTexture(GL_TEXTURE_2D, frame.tid);
1654                     }
1655                     int w, h;
1656                     // Set decoding option to alpha unpremultiplied so that the R, G, B channels
1657                     // of transparent pixels are preserved.
1658                     initTexture(frame.map, &w, &h, false /* don't premultiply alpha */);
1659                 }
1660 
1661                 const int trimWidth = frame.trimWidth * ratio_w;
1662                 const int trimHeight = frame.trimHeight * ratio_h;
1663                 const int trimX = frame.trimX * ratio_w;
1664                 const int trimY = frame.trimY * ratio_h;
1665                 const int xc = animationX + trimX;
1666                 const int yc = animationY + trimY;
1667                 glClear(GL_COLOR_BUFFER_BIT);
1668                 // specify the y center as ceiling((mHeight - frame.trimHeight) / 2)
1669                 // which is equivalent to mHeight - (yc + frame.trimHeight)
1670                 const int frameDrawY = mHeight - (yc + trimHeight);
1671 
1672                 float fade = 0;
1673                 // if the part hasn't been stopped yet then continue fading if necessary
1674                 if (exitPending() && part.hasFadingPhase()) {
1675                     fade = static_cast<float>(++fadedFramesCount) / part.framesToFadeCount;
1676                     if (fadedFramesCount >= part.framesToFadeCount) {
1677                         fadedFramesCount = MAX_FADED_FRAMES_COUNT; // no more fading
1678                     }
1679                 }
1680                 glUseProgram(mImageShader);
1681                 glUniform1i(mImageTextureLocation, 0);
1682                 glUniform1f(mImageFadeLocation, fade);
1683                 if (animation.dynamicColoringEnabled) {
1684                     glUniform1f(mImageColorProgressLocation, colorProgress);
1685                 }
1686                 glEnable(GL_BLEND);
1687                 drawTexturedQuad(xc, frameDrawY, trimWidth, trimHeight);
1688                 glDisable(GL_BLEND);
1689 
1690                 if (mClockEnabled && mTimeIsAccurate && validClock(part)) {
1691                     drawClock(animation.clockFont, part.clockPosX, part.clockPosY);
1692                 }
1693 
1694                 if (displayProgress) {
1695                     int newProgress = android::base::GetIntProperty(PROGRESS_PROP_NAME, 0);
1696                     // In case the new progress jumped suddenly, still show an
1697                     // increment of 1.
1698                     if (lastDisplayedProgress != 100) {
1699                       // Artificially sleep 1/10th a second to slow down the animation.
1700                       usleep(100000);
1701                       if (lastDisplayedProgress < newProgress) {
1702                         lastDisplayedProgress++;
1703                       }
1704                     }
1705                     // Put the progress percentage right below the animation.
1706                     int posY = animation.height / 3;
1707                     int posX = TEXT_CENTER_VALUE;
1708                     drawProgress(lastDisplayedProgress, animation.progressFont, posX, posY);
1709                 }
1710 
1711                 handleViewport(frameDuration);
1712 
1713                 eglSwapBuffers(mDisplay, mSurface);
1714 
1715                 nsecs_t now = systemTime();
1716                 nsecs_t delay = frameDuration - (now - lastFrame);
1717                 //SLOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
1718                 lastFrame = now;
1719 
1720                 if (delay > 0) {
1721                     struct timespec spec;
1722                     spec.tv_sec  = (now + delay) / 1000000000;
1723                     spec.tv_nsec = (now + delay) % 1000000000;
1724                     int err;
1725                     do {
1726                         err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, nullptr);
1727                     } while (err == EINTR);
1728                 }
1729 
1730                 checkExit();
1731             }
1732 
1733             int pauseDuration = part.pause * ns2us(frameDuration);
1734             while(pauseDuration > 0 && !exitPending()){
1735                 if (pauseDuration > MAX_CHECK_EXIT_INTERVAL_US) {
1736                     usleep(MAX_CHECK_EXIT_INTERVAL_US);
1737                     pauseDuration -= MAX_CHECK_EXIT_INTERVAL_US;
1738                 } else {
1739                     usleep(pauseDuration);
1740                     break;
1741                 }
1742                 checkExit();
1743             }
1744 
1745             if (exitPending() && !part.count && mCurrentInset >= mTargetInset &&
1746                 !part.hasFadingPhase()) {
1747                 if (lastDisplayedProgress != 0 && lastDisplayedProgress != 100) {
1748                     android::base::SetProperty(PROGRESS_PROP_NAME, "100");
1749                     continue;
1750                 }
1751                 break; // exit the infinite non-fading part when it has been played at least once
1752             }
1753         }
1754     }
1755 
1756     // Free textures created for looping parts now that the animation is done.
1757     for (const Animation::Part& part : animation.parts) {
1758         if (part.count != 1) {
1759             const size_t fcount = part.frames.size();
1760             for (size_t j = 0; j < fcount; j++) {
1761                 const Animation::Frame& frame(part.frames[j]);
1762                 glDeleteTextures(1, &frame.tid);
1763             }
1764         }
1765     }
1766 
1767     ALOGD("%sAnimationShownTiming End time: %" PRId64 "ms", mShuttingDown ? "Shutdown" : "Boot",
1768             elapsedRealtime());
1769 
1770     return true;
1771 }
1772 
processDisplayEvents()1773 void BootAnimation::processDisplayEvents() {
1774     ATRACE_CALL();
1775     // This will poll mDisplayEventReceiver and if there are new events it'll call
1776     // displayEventCallback synchronously.
1777     mLooper->pollOnce(0);
1778 }
1779 
handleViewport(nsecs_t timestep)1780 void BootAnimation::handleViewport(nsecs_t timestep) {
1781     ATRACE_CALL();
1782     if (mShuttingDown || !mFlingerSurfaceControl || mTargetInset == 0) {
1783         return;
1784     }
1785     if (mTargetInset < 0) {
1786         // Poll the amount for the top display inset. This will return -1 until persistent properties
1787         // have been loaded.
1788         mTargetInset = android::base::GetIntProperty("persist.sys.displayinset.top",
1789                 -1 /* default */, -1 /* min */, mHeight / 2 /* max */);
1790     }
1791     if (mTargetInset <= 0) {
1792         return;
1793     }
1794 
1795     if (mCurrentInset < mTargetInset) {
1796         // After the device boots, the inset will effectively be cropped away. We animate this here.
1797         float fraction = static_cast<float>(mCurrentInset) / mTargetInset;
1798         int interpolatedInset = (cosf((fraction + 1) * M_PI) / 2.0f + 0.5f) * mTargetInset;
1799 
1800         SurfaceComposerClient::Transaction()
1801                 .setCrop(mFlingerSurfaceControl, Rect(0, interpolatedInset, mWidth, mHeight))
1802                 .apply();
1803     } else {
1804         // At the end of the animation, we switch to the viewport that DisplayManager will apply
1805         // later. This changes the coordinate system, and means we must move the surface up by
1806         // the inset amount.
1807         Rect layerStackRect(0, 0, mWidth, mHeight - mTargetInset);
1808         Rect displayRect(0, mTargetInset, mWidth, mHeight);
1809 
1810         SurfaceComposerClient::Transaction t;
1811         t.setPosition(mFlingerSurfaceControl, 0, -mTargetInset)
1812                 .setCrop(mFlingerSurfaceControl, Rect(0, mTargetInset, mWidth, mHeight));
1813         t.setDisplayProjection(mDisplayToken, ui::ROTATION_0, layerStackRect, displayRect);
1814         t.apply();
1815 
1816         mTargetInset = mCurrentInset = 0;
1817     }
1818 
1819     int delta = timestep * mTargetInset / ms2ns(200);
1820     mCurrentInset += delta;
1821 }
1822 
releaseAnimation(Animation * animation) const1823 void BootAnimation::releaseAnimation(Animation* animation) const {
1824     ATRACE_CALL();
1825     for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
1826          e = animation->parts.end(); it != e; ++it) {
1827         if (it->animation)
1828             releaseAnimation(it->animation);
1829     }
1830     if (animation->zip)
1831         delete animation->zip;
1832     delete animation;
1833 }
1834 
loadAnimation(const String8 & fn)1835 BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
1836     ATRACE_CALL();
1837     if (mLoadedFiles.indexOf(fn) >= 0) {
1838         SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
1839             fn.c_str());
1840         return nullptr;
1841     }
1842     ZipFileRO *zip = ZipFileRO::open(fn.c_str());
1843     if (zip == nullptr) {
1844         SLOGE("Failed to open animation zip \"%s\": %s",
1845             fn.c_str(), strerror(errno));
1846         return nullptr;
1847     }
1848 
1849     ALOGD("%s is loaded successfully", fn.c_str());
1850 
1851     Animation *animation =  new Animation;
1852     animation->fileName = fn;
1853     animation->zip = zip;
1854     animation->clockFont.map = nullptr;
1855     mLoadedFiles.add(animation->fileName);
1856 
1857     parseAnimationDesc(*animation);
1858     if (!preloadZip(*animation)) {
1859         releaseAnimation(animation);
1860         return nullptr;
1861     }
1862 
1863     mLoadedFiles.remove(fn);
1864     return animation;
1865 }
1866 
updateIsTimeAccurate()1867 bool BootAnimation::updateIsTimeAccurate() {
1868     ATRACE_CALL();
1869     static constexpr long long MAX_TIME_IN_PAST =   60000LL * 60LL * 24LL * 30LL;  // 30 days
1870     static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL;  // 90 minutes
1871 
1872     if (mTimeIsAccurate) {
1873         return true;
1874     }
1875     if (mShuttingDown) return true;
1876     struct stat statResult;
1877 
1878     if(stat(TIME_FORMAT_12_HOUR_FLAG_FILE_PATH, &statResult) == 0) {
1879         mTimeFormat12Hour = true;
1880     }
1881 
1882     if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
1883         mTimeIsAccurate = true;
1884         return true;
1885     }
1886 
1887     FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
1888     if (file != nullptr) {
1889       long long lastChangedTime = 0;
1890       fscanf(file, "%lld", &lastChangedTime);
1891       fclose(file);
1892       if (lastChangedTime > 0) {
1893         struct timespec now;
1894         clock_gettime(CLOCK_REALTIME, &now);
1895         // Match the Java timestamp format
1896         long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
1897         if (ACCURATE_TIME_EPOCH < rtcNow
1898             && lastChangedTime > (rtcNow - MAX_TIME_IN_PAST)
1899             && lastChangedTime < (rtcNow + MAX_TIME_IN_FUTURE)) {
1900             mTimeIsAccurate = true;
1901         }
1902       }
1903     }
1904 
1905     return mTimeIsAccurate;
1906 }
1907 
TimeCheckThread(BootAnimation * bootAnimation)1908 BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
1909     mInotifyFd(-1), mBootAnimWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
1910 
~TimeCheckThread()1911 BootAnimation::TimeCheckThread::~TimeCheckThread() {
1912     ATRACE_CALL();
1913     // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
1914     close(mInotifyFd);
1915 }
1916 
threadLoop()1917 bool BootAnimation::TimeCheckThread::threadLoop() {
1918     ATRACE_CALL();
1919     bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
1920         && mBootAnimation->mClockEnabled;
1921     if (!shouldLoop) {
1922         close(mInotifyFd);
1923         mInotifyFd = -1;
1924     }
1925     return shouldLoop;
1926 }
1927 
doThreadLoop()1928 bool BootAnimation::TimeCheckThread::doThreadLoop() {
1929     ATRACE_CALL();
1930     static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
1931 
1932     // Poll instead of doing a blocking read so the Thread can exit if requested.
1933     struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
1934     ssize_t pollResult = poll(&pfd, 1, 1000);
1935 
1936     if (pollResult == 0) {
1937         return true;
1938     } else if (pollResult < 0) {
1939         SLOGE("Could not poll inotify events");
1940         return false;
1941     }
1942 
1943     char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
1944     ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
1945     if (length == 0) {
1946         return true;
1947     } else if (length < 0) {
1948         SLOGE("Could not read inotify events");
1949         return false;
1950     }
1951 
1952     const struct inotify_event *event;
1953     for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
1954         event = (const struct inotify_event *) ptr;
1955         if (event->wd == mBootAnimWd && strcmp(BOOTANIM_TIME_DIR_NAME, event->name) == 0) {
1956             addTimeDirWatch();
1957         } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
1958                 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
1959             return !mBootAnimation->updateIsTimeAccurate();
1960         }
1961     }
1962 
1963     return true;
1964 }
1965 
addTimeDirWatch()1966 void BootAnimation::TimeCheckThread::addTimeDirWatch() {
1967         ATRACE_CALL();
1968         mTimeWd = inotify_add_watch(mInotifyFd, BOOTANIM_TIME_DIR_PATH,
1969                 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
1970         if (mTimeWd > 0) {
1971             // No need to watch for the time directory to be created if it already exists
1972             inotify_rm_watch(mInotifyFd, mBootAnimWd);
1973             mBootAnimWd = -1;
1974         }
1975 }
1976 
readyToRun()1977 status_t BootAnimation::TimeCheckThread::readyToRun() {
1978     ATRACE_CALL();
1979     mInotifyFd = inotify_init();
1980     if (mInotifyFd < 0) {
1981         SLOGE("Could not initialize inotify fd");
1982         return NO_INIT;
1983     }
1984 
1985     mBootAnimWd = inotify_add_watch(mInotifyFd, BOOTANIM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
1986     if (mBootAnimWd < 0) {
1987         close(mInotifyFd);
1988         mInotifyFd = -1;
1989         SLOGE("Could not add watch for %s: %s", BOOTANIM_DATA_DIR_PATH, strerror(errno));
1990         return NO_INIT;
1991     }
1992 
1993     addTimeDirWatch();
1994 
1995     if (mBootAnimation->updateIsTimeAccurate()) {
1996         close(mInotifyFd);
1997         mInotifyFd = -1;
1998         return ALREADY_EXISTS;
1999     }
2000 
2001     return NO_ERROR;
2002 }
2003 
2004 // ---------------------------------------------------------------------------
2005 
2006 } // namespace android
2007