OSDN Git Service

Merge "Update dock stack create mode after rotation if dock side changed" into nyc-dev
[android-x86/frameworks-base.git] / cmds / bootanimation / BootAnimation.cpp
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 <stdint.h>
21 #include <sys/inotify.h>
22 #include <sys/poll.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <math.h>
26 #include <fcntl.h>
27 #include <utils/misc.h>
28 #include <signal.h>
29 #include <time.h>
30
31 #include <cutils/properties.h>
32
33 #include <androidfw/AssetManager.h>
34 #include <binder/IPCThreadState.h>
35 #include <utils/Atomic.h>
36 #include <utils/Errors.h>
37 #include <utils/Log.h>
38
39 #include <ui/PixelFormat.h>
40 #include <ui/Rect.h>
41 #include <ui/Region.h>
42 #include <ui/DisplayInfo.h>
43
44 #include <gui/ISurfaceComposer.h>
45 #include <gui/Surface.h>
46 #include <gui/SurfaceComposerClient.h>
47
48 // TODO: Fix Skia.
49 #pragma GCC diagnostic push
50 #pragma GCC diagnostic ignored "-Wunused-parameter"
51 #include <SkBitmap.h>
52 #include <SkStream.h>
53 #include <SkImageDecoder.h>
54 #pragma GCC diagnostic pop
55
56 #include <GLES/gl.h>
57 #include <GLES/glext.h>
58 #include <EGL/eglext.h>
59
60 #include "BootAnimation.h"
61 #include "AudioPlayer.h"
62
63 namespace android {
64
65 static const char OEM_BOOTANIMATION_FILE[] = "/oem/media/bootanimation.zip";
66 static const char SYSTEM_BOOTANIMATION_FILE[] = "/system/media/bootanimation.zip";
67 static const char SYSTEM_ENCRYPTED_BOOTANIMATION_FILE[] = "/system/media/bootanimation-encrypted.zip";
68 static const char SYSTEM_DATA_DIR_PATH[] = "/data/system";
69 static const char SYSTEM_TIME_DIR_NAME[] = "time";
70 static const char SYSTEM_TIME_DIR_PATH[] = "/data/system/time";
71 static const char LAST_TIME_CHANGED_FILE_NAME[] = "last_time_change";
72 static const char LAST_TIME_CHANGED_FILE_PATH[] = "/data/system/time/last_time_change";
73 static const char ACCURATE_TIME_FLAG_FILE_NAME[] = "time_is_accurate";
74 static const char ACCURATE_TIME_FLAG_FILE_PATH[] = "/data/system/time/time_is_accurate";
75 static const char EXIT_PROP_NAME[] = "service.bootanim.exit";
76 static const int ANIM_ENTRY_NAME_MAX = 256;
77
78 // ---------------------------------------------------------------------------
79
80 BootAnimation::BootAnimation() : Thread(false), mClockEnabled(true), mTimeIsAccurate(false),
81         mTimeCheckThread(NULL) {
82     mSession = new SurfaceComposerClient();
83 }
84
85 BootAnimation::~BootAnimation() {}
86
87 void BootAnimation::onFirstRef() {
88     status_t err = mSession->linkToComposerDeath(this);
89     ALOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
90     if (err == NO_ERROR) {
91         run("BootAnimation", PRIORITY_DISPLAY);
92     }
93 }
94
95 sp<SurfaceComposerClient> BootAnimation::session() const {
96     return mSession;
97 }
98
99
100 void BootAnimation::binderDied(const wp<IBinder>&)
101 {
102     // woah, surfaceflinger died!
103     ALOGD("SurfaceFlinger died, exiting...");
104
105     // calling requestExit() is not enough here because the Surface code
106     // might be blocked on a condition variable that will never be updated.
107     kill( getpid(), SIGKILL );
108     requestExit();
109     if (mAudioPlayer != NULL) {
110         mAudioPlayer->requestExit();
111     }
112 }
113
114 status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets,
115         const char* name) {
116     Asset* asset = assets.open(name, Asset::ACCESS_BUFFER);
117     if (asset == NULL)
118         return NO_INIT;
119     SkBitmap bitmap;
120     SkImageDecoder::DecodeMemory(asset->getBuffer(false), asset->getLength(),
121             &bitmap, kUnknown_SkColorType, SkImageDecoder::kDecodePixels_Mode);
122     asset->close();
123     delete asset;
124
125     // ensure we can call getPixels(). No need to call unlock, since the
126     // bitmap will go out of scope when we return from this method.
127     bitmap.lockPixels();
128
129     const int w = bitmap.width();
130     const int h = bitmap.height();
131     const void* p = bitmap.getPixels();
132
133     GLint crop[4] = { 0, h, w, -h };
134     texture->w = w;
135     texture->h = h;
136
137     glGenTextures(1, &texture->name);
138     glBindTexture(GL_TEXTURE_2D, texture->name);
139
140     switch (bitmap.colorType()) {
141         case kAlpha_8_SkColorType:
142             glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
143                     GL_UNSIGNED_BYTE, p);
144             break;
145         case kARGB_4444_SkColorType:
146             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
147                     GL_UNSIGNED_SHORT_4_4_4_4, p);
148             break;
149         case kN32_SkColorType:
150             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
151                     GL_UNSIGNED_BYTE, p);
152             break;
153         case kRGB_565_SkColorType:
154             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
155                     GL_UNSIGNED_SHORT_5_6_5, p);
156             break;
157         default:
158             break;
159     }
160
161     glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
162     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
163     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
164     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
165     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
166     return NO_ERROR;
167 }
168
169 status_t BootAnimation::initTexture(const Animation::Frame& frame)
170 {
171     //StopWatch watch("blah");
172
173     SkBitmap bitmap;
174     SkMemoryStream  stream(frame.map->getDataPtr(), frame.map->getDataLength());
175     SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
176     if (codec != NULL) {
177         codec->setDitherImage(false);
178         codec->decode(&stream, &bitmap,
179                 kN32_SkColorType,
180                 SkImageDecoder::kDecodePixels_Mode);
181         delete codec;
182     }
183
184     // FileMap memory is never released until application exit.
185     // Release it now as the texture is already loaded and the memory used for
186     // the packed resource can be released.
187     delete frame.map;
188
189     // ensure we can call getPixels(). No need to call unlock, since the
190     // bitmap will go out of scope when we return from this method.
191     bitmap.lockPixels();
192
193     const int w = bitmap.width();
194     const int h = bitmap.height();
195     const void* p = bitmap.getPixels();
196
197     GLint crop[4] = { 0, h, w, -h };
198     int tw = 1 << (31 - __builtin_clz(w));
199     int th = 1 << (31 - __builtin_clz(h));
200     if (tw < w) tw <<= 1;
201     if (th < h) th <<= 1;
202
203     switch (bitmap.colorType()) {
204         case kN32_SkColorType:
205             if (tw != w || th != h) {
206                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
207                         GL_UNSIGNED_BYTE, 0);
208                 glTexSubImage2D(GL_TEXTURE_2D, 0,
209                         0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
210             } else {
211                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
212                         GL_UNSIGNED_BYTE, p);
213             }
214             break;
215
216         case kRGB_565_SkColorType:
217             if (tw != w || th != h) {
218                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
219                         GL_UNSIGNED_SHORT_5_6_5, 0);
220                 glTexSubImage2D(GL_TEXTURE_2D, 0,
221                         0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p);
222             } else {
223                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
224                         GL_UNSIGNED_SHORT_5_6_5, p);
225             }
226             break;
227         default:
228             break;
229     }
230
231     glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
232
233     return NO_ERROR;
234 }
235
236 status_t BootAnimation::readyToRun() {
237     mAssets.addDefaultAssets();
238
239     sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
240             ISurfaceComposer::eDisplayIdMain));
241     DisplayInfo dinfo;
242     status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &dinfo);
243     if (status)
244         return -1;
245
246     // create the native surface
247     sp<SurfaceControl> control = session()->createSurface(String8("BootAnimation"),
248             dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565);
249
250     SurfaceComposerClient::openGlobalTransaction();
251     control->setLayer(0x40000000);
252     SurfaceComposerClient::closeGlobalTransaction();
253
254     sp<Surface> s = control->getSurface();
255
256     // initialize opengl and egl
257     const EGLint attribs[] = {
258             EGL_RED_SIZE,   8,
259             EGL_GREEN_SIZE, 8,
260             EGL_BLUE_SIZE,  8,
261             EGL_DEPTH_SIZE, 0,
262             EGL_NONE
263     };
264     EGLint w, h;
265     EGLint numConfigs;
266     EGLConfig config;
267     EGLSurface surface;
268     EGLContext context;
269
270     EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
271
272     eglInitialize(display, 0, 0);
273     eglChooseConfig(display, attribs, &config, 1, &numConfigs);
274     surface = eglCreateWindowSurface(display, config, s.get(), NULL);
275     context = eglCreateContext(display, config, NULL, NULL);
276     eglQuerySurface(display, surface, EGL_WIDTH, &w);
277     eglQuerySurface(display, surface, EGL_HEIGHT, &h);
278
279     if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
280         return NO_INIT;
281
282     mDisplay = display;
283     mContext = context;
284     mSurface = surface;
285     mWidth = w;
286     mHeight = h;
287     mFlingerSurfaceControl = control;
288     mFlingerSurface = s;
289
290     // If the device has encryption turned on or is in process
291     // of being encrypted we show the encrypted boot animation.
292     char decrypt[PROPERTY_VALUE_MAX];
293     property_get("vold.decrypt", decrypt, "");
294
295     bool encryptedAnimation = atoi(decrypt) != 0 || !strcmp("trigger_restart_min_framework", decrypt);
296
297     if (encryptedAnimation && (access(SYSTEM_ENCRYPTED_BOOTANIMATION_FILE, R_OK) == 0)) {
298         mZipFileName = SYSTEM_ENCRYPTED_BOOTANIMATION_FILE;
299     }
300     else if (access(OEM_BOOTANIMATION_FILE, R_OK) == 0) {
301         mZipFileName = OEM_BOOTANIMATION_FILE;
302     }
303     else if (access(SYSTEM_BOOTANIMATION_FILE, R_OK) == 0) {
304         mZipFileName = SYSTEM_BOOTANIMATION_FILE;
305     }
306     return NO_ERROR;
307 }
308
309 bool BootAnimation::threadLoop()
310 {
311     bool r;
312     // We have no bootanimation file, so we use the stock android logo
313     // animation.
314     if (mZipFileName.isEmpty()) {
315         r = android();
316     } else {
317         r = movie();
318     }
319
320     eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
321     eglDestroyContext(mDisplay, mContext);
322     eglDestroySurface(mDisplay, mSurface);
323     mFlingerSurface.clear();
324     mFlingerSurfaceControl.clear();
325     eglTerminate(mDisplay);
326     IPCThreadState::self()->stopProcess();
327     return r;
328 }
329
330 bool BootAnimation::android()
331 {
332     initTexture(&mAndroid[0], mAssets, "images/android-logo-mask.png");
333     initTexture(&mAndroid[1], mAssets, "images/android-logo-shine.png");
334
335     // clear screen
336     glShadeModel(GL_FLAT);
337     glDisable(GL_DITHER);
338     glDisable(GL_SCISSOR_TEST);
339     glClearColor(0,0,0,1);
340     glClear(GL_COLOR_BUFFER_BIT);
341     eglSwapBuffers(mDisplay, mSurface);
342
343     glEnable(GL_TEXTURE_2D);
344     glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
345
346     const GLint xc = (mWidth  - mAndroid[0].w) / 2;
347     const GLint yc = (mHeight - mAndroid[0].h) / 2;
348     const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
349
350     glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
351             updateRect.height());
352
353     // Blend state
354     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
355     glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
356
357     const nsecs_t startTime = systemTime();
358     do {
359         nsecs_t now = systemTime();
360         double time = now - startTime;
361         float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
362         GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
363         GLint x = xc - offset;
364
365         glDisable(GL_SCISSOR_TEST);
366         glClear(GL_COLOR_BUFFER_BIT);
367
368         glEnable(GL_SCISSOR_TEST);
369         glDisable(GL_BLEND);
370         glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
371         glDrawTexiOES(x,                 yc, 0, mAndroid[1].w, mAndroid[1].h);
372         glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);
373
374         glEnable(GL_BLEND);
375         glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
376         glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);
377
378         EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
379         if (res == EGL_FALSE)
380             break;
381
382         // 12fps: don't animate too fast to preserve CPU
383         const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
384         if (sleepTime > 0)
385             usleep(sleepTime);
386
387         checkExit();
388     } while (!exitPending());
389
390     glDeleteTextures(1, &mAndroid[0].name);
391     glDeleteTextures(1, &mAndroid[1].name);
392     return false;
393 }
394
395
396 void BootAnimation::checkExit() {
397     // Allow surface flinger to gracefully request shutdown
398     char value[PROPERTY_VALUE_MAX];
399     property_get(EXIT_PROP_NAME, value, "0");
400     int exitnow = atoi(value);
401     if (exitnow) {
402         requestExit();
403         if (mAudioPlayer != NULL) {
404             mAudioPlayer->requestExit();
405         }
406     }
407 }
408
409 // Parse a color represented as an HTML-style 'RRGGBB' string: each pair of
410 // characters in str is a hex number in [0, 255], which are converted to
411 // floating point values in the range [0.0, 1.0] and placed in the
412 // corresponding elements of color.
413 //
414 // If the input string isn't valid, parseColor returns false and color is
415 // left unchanged.
416 static bool parseColor(const char str[7], float color[3]) {
417     float tmpColor[3];
418     for (int i = 0; i < 3; i++) {
419         int val = 0;
420         for (int j = 0; j < 2; j++) {
421             val *= 16;
422             char c = str[2*i + j];
423             if      (c >= '0' && c <= '9') val += c - '0';
424             else if (c >= 'A' && c <= 'F') val += (c - 'A') + 10;
425             else if (c >= 'a' && c <= 'f') val += (c - 'a') + 10;
426             else                           return false;
427         }
428         tmpColor[i] = static_cast<float>(val) / 255.0f;
429     }
430     memcpy(color, tmpColor, sizeof(tmpColor));
431     return true;
432 }
433
434
435 static bool readFile(ZipFileRO* zip, const char* name, String8& outString)
436 {
437     ZipEntryRO entry = zip->findEntryByName(name);
438     ALOGE_IF(!entry, "couldn't find %s", name);
439     if (!entry) {
440         return false;
441     }
442
443     FileMap* entryMap = zip->createEntryFileMap(entry);
444     zip->releaseEntry(entry);
445     ALOGE_IF(!entryMap, "entryMap is null");
446     if (!entryMap) {
447         return false;
448     }
449
450     outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
451     delete entryMap;
452     return true;
453 }
454
455 // The time glyphs are stored in a single image of height 64 pixels. Each digit is 40 pixels wide,
456 // and the colon character is half that at 20 pixels. The glyph order is '0123456789:'.
457 // We render 24 hour time.
458 void BootAnimation::drawTime(const Texture& clockTex, const int yPos) {
459     static constexpr char TIME_FORMAT[] = "%H:%M";
460     static constexpr int TIME_LENGTH = sizeof(TIME_FORMAT);
461
462     static constexpr int DIGIT_HEIGHT = 64;
463     static constexpr int DIGIT_WIDTH = 40;
464     static constexpr int COLON_WIDTH = DIGIT_WIDTH / 2;
465     static constexpr int TIME_WIDTH = (DIGIT_WIDTH * 4) + COLON_WIDTH;
466
467     if (clockTex.h < DIGIT_HEIGHT || clockTex.w < (10 * DIGIT_WIDTH + COLON_WIDTH)) {
468         ALOGE("Clock texture is too small; abandoning boot animation clock");
469         mClockEnabled = false;
470         return;
471     }
472
473     time_t rawtime;
474     time(&rawtime);
475     struct tm* timeInfo = localtime(&rawtime);
476
477     char timeBuff[TIME_LENGTH];
478     size_t length = strftime(timeBuff, TIME_LENGTH, TIME_FORMAT, timeInfo);
479
480     if (length != TIME_LENGTH - 1) {
481         ALOGE("Couldn't format time; abandoning boot animation clock");
482         mClockEnabled = false;
483         return;
484     }
485
486     glEnable(GL_BLEND);  // Allow us to draw on top of the animation
487     glBindTexture(GL_TEXTURE_2D, clockTex.name);
488
489     int xPos = (mWidth - TIME_WIDTH) / 2;
490     int cropRect[4] = { 0, DIGIT_HEIGHT, DIGIT_WIDTH, -DIGIT_HEIGHT };
491
492     for (int i = 0; i < TIME_LENGTH - 1; i++) {
493         char c = timeBuff[i];
494         int width = DIGIT_WIDTH;
495         int pos = c - '0';  // Position in the character list
496         if (pos < 0 || pos > 10) {
497             continue;
498         }
499         if (c == ':') {
500             width = COLON_WIDTH;
501         }
502
503         // Crop the texture to only the pixels in the current glyph
504         int left = pos * DIGIT_WIDTH;
505         cropRect[0] = left;
506         cropRect[2] = width;
507         glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
508
509         glDrawTexiOES(xPos, yPos, 0, width, DIGIT_HEIGHT);
510
511         xPos += width;
512     }
513
514     glDisable(GL_BLEND);  // Return to the animation's default behaviour
515     glBindTexture(GL_TEXTURE_2D, 0);
516 }
517
518 bool BootAnimation::parseAnimationDesc(Animation& animation)
519 {
520     String8 desString;
521
522     if (!readFile(animation.zip, "desc.txt", desString)) {
523         return false;
524     }
525     char const* s = desString.string();
526
527     // Create and initialize an AudioPlayer if we have an audio_conf.txt file
528     String8 audioConf;
529     if (readFile(animation.zip, "audio_conf.txt", audioConf)) {
530         mAudioPlayer = new AudioPlayer;
531         if (!mAudioPlayer->init(audioConf.string())) {
532             ALOGE("mAudioPlayer.init failed");
533             mAudioPlayer = NULL;
534         }
535     }
536
537     // Parse the description file
538     for (;;) {
539         const char* endl = strstr(s, "\n");
540         if (endl == NULL) break;
541         String8 line(s, endl - s);
542         const char* l = line.string();
543         int fps = 0;
544         int width = 0;
545         int height = 0;
546         int count = 0;
547         int pause = 0;
548         int clockPosY = -1;
549         char path[ANIM_ENTRY_NAME_MAX];
550         char color[7] = "000000"; // default to black if unspecified
551
552         char pathType;
553         if (sscanf(l, "%d %d %d", &width, &height, &fps) == 3) {
554             // ALOGD("> w=%d, h=%d, fps=%d", width, height, fps);
555             animation.width = width;
556             animation.height = height;
557             animation.fps = fps;
558         } else if (sscanf(l, " %c %d %d %s #%6s %d",
559                           &pathType, &count, &pause, path, color, &clockPosY) >= 4) {
560             // ALOGD("> type=%c, count=%d, pause=%d, path=%s, color=%s, clockPosY=%d", pathType, count, pause, path, color, clockPosY);
561             Animation::Part part;
562             part.playUntilComplete = pathType == 'c';
563             part.count = count;
564             part.pause = pause;
565             part.path = path;
566             part.clockPosY = clockPosY;
567             part.audioFile = NULL;
568             part.animation = NULL;
569             if (!parseColor(color, part.backgroundColor)) {
570                 ALOGE("> invalid color '#%s'", color);
571                 part.backgroundColor[0] = 0.0f;
572                 part.backgroundColor[1] = 0.0f;
573                 part.backgroundColor[2] = 0.0f;
574             }
575             animation.parts.add(part);
576         }
577         else if (strcmp(l, "$SYSTEM") == 0) {
578             // ALOGD("> SYSTEM");
579             Animation::Part part;
580             part.playUntilComplete = false;
581             part.count = 1;
582             part.pause = 0;
583             part.audioFile = NULL;
584             part.animation = loadAnimation(String8(SYSTEM_BOOTANIMATION_FILE));
585             if (part.animation != NULL)
586                 animation.parts.add(part);
587         }
588         s = ++endl;
589     }
590
591     return true;
592 }
593
594 bool BootAnimation::preloadZip(Animation& animation)
595 {
596     // read all the data structures
597     const size_t pcount = animation.parts.size();
598     void *cookie = NULL;
599     ZipFileRO* mZip = animation.zip;
600     if (!mZip->startIteration(&cookie)) {
601         return false;
602     }
603
604     ZipEntryRO entry;
605     char name[ANIM_ENTRY_NAME_MAX];
606     while ((entry = mZip->nextEntry(cookie)) != NULL) {
607         const int foundEntryName = mZip->getEntryFileName(entry, name, ANIM_ENTRY_NAME_MAX);
608         if (foundEntryName > ANIM_ENTRY_NAME_MAX || foundEntryName == -1) {
609             ALOGE("Error fetching entry file name");
610             continue;
611         }
612
613         const String8 entryName(name);
614         const String8 path(entryName.getPathDir());
615         const String8 leaf(entryName.getPathLeaf());
616         if (leaf.size() > 0) {
617             for (size_t j=0 ; j<pcount ; j++) {
618                 if (path == animation.parts[j].path) {
619                     uint16_t method;
620                     // supports only stored png files
621                     if (mZip->getEntryInfo(entry, &method, NULL, NULL, NULL, NULL, NULL)) {
622                         if (method == ZipFileRO::kCompressStored) {
623                             FileMap* map = mZip->createEntryFileMap(entry);
624                             if (map) {
625                                 Animation::Part& part(animation.parts.editItemAt(j));
626                                 if (leaf == "audio.wav") {
627                                     // a part may have at most one audio file
628                                     part.audioFile = map;
629                                 } else {
630                                     Animation::Frame frame;
631                                     frame.name = leaf;
632                                     frame.map = map;
633                                     part.frames.add(frame);
634                                 }
635                             }
636                         }
637                     }
638                 }
639             }
640         }
641     }
642
643     mZip->endIteration(cookie);
644
645     return true;
646 }
647
648 bool BootAnimation::movie()
649 {
650     Animation* animation = loadAnimation(mZipFileName);
651     if (animation == NULL)
652         return false;
653
654     bool anyPartHasClock = false;
655     for (size_t i=0; i < animation->parts.size(); i++) {
656         if(animation->parts[i].clockPosY >= 0) {
657             anyPartHasClock = true;
658             break;
659         }
660     }
661     if (!anyPartHasClock) {
662         mClockEnabled = false;
663     }
664
665     // Blend required to draw time on top of animation frames.
666     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
667     glShadeModel(GL_FLAT);
668     glDisable(GL_DITHER);
669     glDisable(GL_SCISSOR_TEST);
670     glDisable(GL_BLEND);
671
672     glBindTexture(GL_TEXTURE_2D, 0);
673     glEnable(GL_TEXTURE_2D);
674     glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
675     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
676     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
677     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
678     glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
679
680     bool clockTextureInitialized = false;
681     if (mClockEnabled) {
682         clockTextureInitialized = (initTexture(&mClock, mAssets, "images/clock64.png") == NO_ERROR);
683         mClockEnabled = clockTextureInitialized;
684     }
685
686     if (mClockEnabled && !updateIsTimeAccurate()) {
687         mTimeCheckThread = new TimeCheckThread(this);
688         mTimeCheckThread->run("BootAnimation::TimeCheckThread", PRIORITY_NORMAL);
689     }
690
691     playAnimation(*animation);
692
693     if (mTimeCheckThread != NULL) {
694         mTimeCheckThread->requestExit();
695         mTimeCheckThread = NULL;
696     }
697
698     releaseAnimation(animation);
699
700     if (clockTextureInitialized) {
701         glDeleteTextures(1, &mClock.name);
702     }
703
704     return false;
705 }
706
707 bool BootAnimation::playAnimation(const Animation& animation)
708 {
709     const size_t pcount = animation.parts.size();
710     const int xc = (mWidth - animation.width) / 2;
711     const int yc = ((mHeight - animation.height) / 2);
712     nsecs_t frameDuration = s2ns(1) / animation.fps;
713
714     Region clearReg(Rect(mWidth, mHeight));
715     clearReg.subtractSelf(Rect(xc, yc, xc+animation.width, yc+animation.height));
716
717     for (size_t i=0 ; i<pcount ; i++) {
718         const Animation::Part& part(animation.parts[i]);
719         const size_t fcount = part.frames.size();
720         glBindTexture(GL_TEXTURE_2D, 0);
721
722         // Handle animation package
723         if (part.animation != NULL) {
724             playAnimation(*part.animation);
725             if (exitPending())
726                 break;
727             continue; //to next part
728         }
729
730         for (int r=0 ; !part.count || r<part.count ; r++) {
731             // Exit any non playuntil complete parts immediately
732             if(exitPending() && !part.playUntilComplete)
733                 break;
734
735             // only play audio file the first time we animate the part
736             if (r == 0 && mAudioPlayer != NULL && part.audioFile) {
737                 mAudioPlayer->playFile(part.audioFile);
738             }
739
740             glClearColor(
741                     part.backgroundColor[0],
742                     part.backgroundColor[1],
743                     part.backgroundColor[2],
744                     1.0f);
745
746             for (size_t j=0 ; j<fcount && (!exitPending() || part.playUntilComplete) ; j++) {
747                 const Animation::Frame& frame(part.frames[j]);
748                 nsecs_t lastFrame = systemTime();
749
750                 if (r > 0) {
751                     glBindTexture(GL_TEXTURE_2D, frame.tid);
752                 } else {
753                     if (part.count != 1) {
754                         glGenTextures(1, &frame.tid);
755                         glBindTexture(GL_TEXTURE_2D, frame.tid);
756                         glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
757                         glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
758                     }
759                     initTexture(frame);
760                 }
761
762                 if (!clearReg.isEmpty()) {
763                     Region::const_iterator head(clearReg.begin());
764                     Region::const_iterator tail(clearReg.end());
765                     glEnable(GL_SCISSOR_TEST);
766                     while (head != tail) {
767                         const Rect& r2(*head++);
768                         glScissor(r2.left, mHeight - r2.bottom,
769                                 r2.width(), r2.height());
770                         glClear(GL_COLOR_BUFFER_BIT);
771                     }
772                     glDisable(GL_SCISSOR_TEST);
773                 }
774                 // specify the y center as ceiling((mHeight - animation.height) / 2)
775                 // which is equivalent to mHeight - (yc + animation.height)
776                 glDrawTexiOES(xc, mHeight - (yc + animation.height),
777                               0, animation.width, animation.height);
778                 if (mClockEnabled && mTimeIsAccurate && part.clockPosY >= 0) {
779                     drawTime(mClock, part.clockPosY);
780                 }
781
782                 eglSwapBuffers(mDisplay, mSurface);
783
784                 nsecs_t now = systemTime();
785                 nsecs_t delay = frameDuration - (now - lastFrame);
786                 //ALOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
787                 lastFrame = now;
788
789                 if (delay > 0) {
790                     struct timespec spec;
791                     spec.tv_sec  = (now + delay) / 1000000000;
792                     spec.tv_nsec = (now + delay) % 1000000000;
793                     int err;
794                     do {
795                         err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
796                     } while (err<0 && errno == EINTR);
797                 }
798
799                 checkExit();
800             }
801
802             usleep(part.pause * ns2us(frameDuration));
803
804             // For infinite parts, we've now played them at least once, so perhaps exit
805             if(exitPending() && !part.count)
806                 break;
807         }
808
809         // free the textures for this part
810         if (part.count != 1) {
811             for (size_t j=0 ; j<fcount ; j++) {
812                 const Animation::Frame& frame(part.frames[j]);
813                 glDeleteTextures(1, &frame.tid);
814             }
815         }
816     }
817     return true;
818 }
819
820 void BootAnimation::releaseAnimation(Animation* animation) const
821 {
822     for (Vector<Animation::Part>::iterator it = animation->parts.begin(),
823          e = animation->parts.end(); it != e; ++it) {
824         if (it->animation)
825             releaseAnimation(it->animation);
826     }
827     if (animation->zip)
828         delete animation->zip;
829     delete animation;
830 }
831
832 BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn)
833 {
834     if (mLoadedFiles.indexOf(fn) >= 0) {
835         ALOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
836             fn.string());
837         return NULL;
838     }
839     ZipFileRO *zip = ZipFileRO::open(fn);
840     if (zip == NULL) {
841         ALOGE("Failed to open animation zip \"%s\": %s",
842             fn.string(), strerror(errno));
843         return NULL;
844     }
845
846     Animation *animation =  new Animation;
847     animation->fileName = fn;
848     animation->zip = zip;
849     mLoadedFiles.add(animation->fileName);
850
851     parseAnimationDesc(*animation);
852     preloadZip(*animation);
853
854     mLoadedFiles.remove(fn);
855     return animation;
856 }
857
858 bool BootAnimation::updateIsTimeAccurate() {
859     static constexpr long long MAX_TIME_IN_PAST =   60000LL * 60LL * 24LL * 30LL;  // 30 days
860     static constexpr long long MAX_TIME_IN_FUTURE = 60000LL * 90LL;  // 90 minutes
861
862     if (mTimeIsAccurate) {
863         return true;
864     }
865
866     struct stat statResult;
867     if(stat(ACCURATE_TIME_FLAG_FILE_PATH, &statResult) == 0) {
868         mTimeIsAccurate = true;
869         return true;
870     }
871
872     FILE* file = fopen(LAST_TIME_CHANGED_FILE_PATH, "r");
873     if (file != NULL) {
874       long long lastChangedTime = 0;
875       fscanf(file, "%lld", &lastChangedTime);
876       fclose(file);
877       if (lastChangedTime > 0) {
878         struct timespec now;
879         clock_gettime(CLOCK_REALTIME, &now);
880         // Match the Java timestamp format
881         long long rtcNow = (now.tv_sec * 1000LL) + (now.tv_nsec / 1000000LL);
882         if (lastChangedTime > rtcNow - MAX_TIME_IN_PAST
883             && lastChangedTime < rtcNow + MAX_TIME_IN_FUTURE) {
884             mTimeIsAccurate = true;
885         }
886       }
887     }
888
889     return mTimeIsAccurate;
890 }
891
892 BootAnimation::TimeCheckThread::TimeCheckThread(BootAnimation* bootAnimation) : Thread(false),
893     mInotifyFd(-1), mSystemWd(-1), mTimeWd(-1), mBootAnimation(bootAnimation) {}
894
895 BootAnimation::TimeCheckThread::~TimeCheckThread() {
896     // mInotifyFd may be -1 but that's ok since we're not at risk of attempting to close a valid FD.
897     close(mInotifyFd);
898 }
899
900 bool BootAnimation::TimeCheckThread::threadLoop() {
901     bool shouldLoop = doThreadLoop() && !mBootAnimation->mTimeIsAccurate
902         && mBootAnimation->mClockEnabled;
903     if (!shouldLoop) {
904         close(mInotifyFd);
905         mInotifyFd = -1;
906     }
907     return shouldLoop;
908 }
909
910 bool BootAnimation::TimeCheckThread::doThreadLoop() {
911     static constexpr int BUFF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1));
912
913     // Poll instead of doing a blocking read so the Thread can exit if requested.
914     struct pollfd pfd = { mInotifyFd, POLLIN, 0 };
915     ssize_t pollResult = poll(&pfd, 1, 1000);
916
917     if (pollResult == 0) {
918         return true;
919     } else if (pollResult < 0) {
920         ALOGE("Could not poll inotify events");
921         return false;
922     }
923
924     char buff[BUFF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
925     ssize_t length = read(mInotifyFd, buff, BUFF_LEN);
926     if (length == 0) {
927         return true;
928     } else if (length < 0) {
929         ALOGE("Could not read inotify events");
930         return false;
931     }
932
933     const struct inotify_event *event;
934     for (char* ptr = buff; ptr < buff + length; ptr += sizeof(struct inotify_event) + event->len) {
935         event = (const struct inotify_event *) ptr;
936         if (event->wd == mSystemWd && strcmp(SYSTEM_TIME_DIR_NAME, event->name) == 0) {
937             addTimeDirWatch();
938         } else if (event->wd == mTimeWd && (strcmp(LAST_TIME_CHANGED_FILE_NAME, event->name) == 0
939                 || strcmp(ACCURATE_TIME_FLAG_FILE_NAME, event->name) == 0)) {
940             return !mBootAnimation->updateIsTimeAccurate();
941         }
942     }
943
944     return true;
945 }
946
947 void BootAnimation::TimeCheckThread::addTimeDirWatch() {
948         mTimeWd = inotify_add_watch(mInotifyFd, SYSTEM_TIME_DIR_PATH,
949                 IN_CLOSE_WRITE | IN_MOVED_TO | IN_ATTRIB);
950         if (mTimeWd > 0) {
951             // No need to watch for the time directory to be created if it already exists
952             inotify_rm_watch(mInotifyFd, mSystemWd);
953             mSystemWd = -1;
954         }
955 }
956
957 status_t BootAnimation::TimeCheckThread::readyToRun() {
958     mInotifyFd = inotify_init();
959     if (mInotifyFd < 0) {
960         ALOGE("Could not initialize inotify fd");
961         return NO_INIT;
962     }
963
964     mSystemWd = inotify_add_watch(mInotifyFd, SYSTEM_DATA_DIR_PATH, IN_CREATE | IN_ATTRIB);
965     if (mSystemWd < 0) {
966         close(mInotifyFd);
967         mInotifyFd = -1;
968         ALOGE("Could not add watch for %s", SYSTEM_DATA_DIR_PATH);
969         return NO_INIT;
970     }
971
972     addTimeDirWatch();
973
974     if (mBootAnimation->updateIsTimeAccurate()) {
975         close(mInotifyFd);
976         mInotifyFd = -1;
977         return ALREADY_EXISTS;
978     }
979
980     return NO_ERROR;
981 }
982
983 // ---------------------------------------------------------------------------
984
985 }
986 ; // namespace android