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