blob: 26f4232ff83530f275ab2611b1e6223fa6e33572 [file] [log] [blame]
Romain Guy3b748a42013-04-17 18:54:38 -07001/*
2 * Copyright (C) 2013 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
17package com.android.server;
18
19import android.content.Context;
20import android.content.pm.PackageInfo;
21import android.content.pm.PackageManager;
22import android.content.res.Resources;
23import android.graphics.Atlas;
24import android.graphics.Bitmap;
25import android.graphics.Canvas;
26import android.graphics.Paint;
27import android.graphics.PixelFormat;
28import android.graphics.PorterDuff;
29import android.graphics.PorterDuffXfermode;
30import android.graphics.drawable.Drawable;
31import android.os.Environment;
32import android.os.RemoteException;
33import android.os.SystemProperties;
34import android.util.Log;
35import android.util.LongSparseArray;
36import android.view.GraphicBuffer;
37import android.view.IAssetAtlas;
38
39import java.io.BufferedReader;
40import java.io.BufferedWriter;
41import java.io.File;
42import java.io.FileInputStream;
43import java.io.FileNotFoundException;
44import java.io.FileOutputStream;
45import java.io.IOException;
46import java.io.InputStreamReader;
47import java.io.OutputStreamWriter;
48import java.util.ArrayList;
John Reckdad7d84c2014-12-09 12:33:26 -080049import java.util.Collection;
Romain Guy3b748a42013-04-17 18:54:38 -070050import java.util.Collections;
51import java.util.Comparator;
John Reckdad7d84c2014-12-09 12:33:26 -080052import java.util.HashSet;
Romain Guy3b748a42013-04-17 18:54:38 -070053import java.util.List;
54import java.util.concurrent.CountDownLatch;
55import java.util.concurrent.TimeUnit;
56import java.util.concurrent.atomic.AtomicBoolean;
57
58/**
59 * This service is responsible for packing preloaded bitmaps into a single
60 * atlas texture. The resulting texture can be shared across processes to
61 * reduce overall memory usage.
62 *
63 * @hide
64 */
65public class AssetAtlasService extends IAssetAtlas.Stub {
66 /**
67 * Name of the <code>AssetAtlasService</code>.
68 */
69 public static final String ASSET_ATLAS_SERVICE = "assetatlas";
70
John Reckdad7d84c2014-12-09 12:33:26 -080071 private static final String LOG_TAG = "AssetAtlas";
Romain Guy3b748a42013-04-17 18:54:38 -070072
73 // Turns debug logs on/off. Debug logs are kept to a minimum and should
74 // remain on to diagnose issues
75 private static final boolean DEBUG_ATLAS = true;
76
77 // When set to true the content of the atlas will be saved to disk
78 // in /data/system/atlas.png. The shared GraphicBuffer may be empty
79 private static final boolean DEBUG_ATLAS_TEXTURE = false;
80
81 // Minimum size in pixels to consider for the resulting texture
82 private static final int MIN_SIZE = 768;
83 // Maximum size in pixels to consider for the resulting texture
84 private static final int MAX_SIZE = 2048;
85 // Increment in number of pixels between size variants when looking
86 // for the best texture dimensions
87 private static final int STEP = 64;
88
89 // This percentage of the total number of pixels represents the minimum
90 // number of pixels we want to be able to pack in the atlas
91 private static final float PACKING_THRESHOLD = 0.8f;
92
93 // Defines the number of int fields used to represent a single entry
94 // in the atlas map. This number defines the size of the array returned
95 // by the getMap(). See the mAtlasMap field for more information
96 private static final int ATLAS_MAP_ENTRY_FIELD_COUNT = 4;
97
98 // Specifies how our GraphicBuffer will be used. To get proper swizzling
99 // the buffer will be written to using OpenGL (from JNI) so we can leave
100 // the software flag set to "never"
101 private static final int GRAPHIC_BUFFER_USAGE = GraphicBuffer.USAGE_SW_READ_NEVER |
102 GraphicBuffer.USAGE_SW_WRITE_NEVER | GraphicBuffer.USAGE_HW_TEXTURE;
103
104 // This boolean is set to true if an atlas was successfully
105 // computed and rendered
106 private final AtomicBoolean mAtlasReady = new AtomicBoolean(false);
107
108 private final Context mContext;
109
110 // Version name of the current build, used to identify changes to assets list
111 private final String mVersionName;
112
113 // Holds the atlas' data. This buffer can be mapped to
114 // OpenGL using an EGLImage
115 private GraphicBuffer mBuffer;
116
117 // Describes how bitmaps are placed in the atlas. Each bitmap is
118 // represented by several entries in the array:
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000119 // long0: SkBitmap*, the native bitmap object
120 // long1: x position
121 // long2: y position
122 // long3: rotated, 1 if the bitmap must be rotated, 0 otherwise
123 private long[] mAtlasMap;
Romain Guy3b748a42013-04-17 18:54:38 -0700124
125 /**
126 * Creates a new service. Upon creating, the service will gather the list of
127 * assets to consider for packing into the atlas and spawn a new thread to
128 * start the packing work.
129 *
130 * @param context The context giving access to preloaded resources
131 */
132 public AssetAtlasService(Context context) {
133 mContext = context;
134 mVersionName = queryVersionName(context);
135
John Reckdad7d84c2014-12-09 12:33:26 -0800136 Collection<Bitmap> bitmaps = new HashSet<Bitmap>(300);
Romain Guy3b748a42013-04-17 18:54:38 -0700137 int totalPixelCount = 0;
138
139 // We only care about drawables that hold bitmaps
140 final Resources resources = context.getResources();
141 final LongSparseArray<Drawable.ConstantState> drawables = resources.getPreloadedDrawables();
142
143 final int count = drawables.size();
144 for (int i = 0; i < count; i++) {
John Reckdad7d84c2014-12-09 12:33:26 -0800145 try {
146 totalPixelCount += drawables.valueAt(i).addAtlasableBitmaps(bitmaps);
147 } catch (Throwable t) {
148 Log.e("AssetAtlas", "Failed to fetch preloaded drawable state", t);
149 throw t;
Romain Guy3b748a42013-04-17 18:54:38 -0700150 }
151 }
152
John Reckdad7d84c2014-12-09 12:33:26 -0800153 ArrayList<Bitmap> sortedBitmaps = new ArrayList<Bitmap>(bitmaps);
Romain Guy3b748a42013-04-17 18:54:38 -0700154 // Our algorithms perform better when the bitmaps are first sorted
155 // The comparator will sort the bitmap by width first, then by height
John Reckdad7d84c2014-12-09 12:33:26 -0800156 Collections.sort(sortedBitmaps, new Comparator<Bitmap>() {
Romain Guy3b748a42013-04-17 18:54:38 -0700157 @Override
158 public int compare(Bitmap b1, Bitmap b2) {
159 if (b1.getWidth() == b2.getWidth()) {
160 return b2.getHeight() - b1.getHeight();
161 }
162 return b2.getWidth() - b1.getWidth();
163 }
164 });
165
166 // Kick off the packing work on a worker thread
John Reckdad7d84c2014-12-09 12:33:26 -0800167 new Thread(new Renderer(sortedBitmaps, totalPixelCount)).start();
Romain Guy3b748a42013-04-17 18:54:38 -0700168 }
169
170 /**
171 * Queries the version name stored in framework's AndroidManifest.
172 * The version name can be used to identify possible changes to
173 * framework resources.
174 *
175 * @see #getBuildIdentifier(String)
176 */
177 private static String queryVersionName(Context context) {
178 try {
179 String packageName = context.getPackageName();
180 PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
181 return info.versionName;
182 } catch (PackageManager.NameNotFoundException e) {
183 Log.w(LOG_TAG, "Could not get package info", e);
184 }
185 return null;
186 }
187
188 /**
189 * Callback invoked by the server thread to indicate we can now run
190 * 3rd party code.
191 */
Svetoslav Ganova0027152013-06-25 14:59:53 -0700192 public void systemRunning() {
Romain Guy3b748a42013-04-17 18:54:38 -0700193 }
194
195 /**
196 * The renderer does all the work:
197 */
198 private class Renderer implements Runnable {
199 private final ArrayList<Bitmap> mBitmaps;
200 private final int mPixelCount;
201
Romain Guy3b748a42013-04-17 18:54:38 -0700202 Renderer(ArrayList<Bitmap> bitmaps, int pixelCount) {
203 mBitmaps = bitmaps;
204 mPixelCount = pixelCount;
205 }
206
207 /**
208 * 1. On first boot or after every update, brute-force through all the
209 * possible atlas configurations and look for the best one (maximimize
210 * number of packed assets and minimize texture size)
211 * a. If a best configuration was computed, write it out to disk for
212 * future use
213 * 2. Read best configuration from disk
214 * 3. Compute the packing using the best configuration
215 * 4. Allocate a GraphicBuffer
216 * 5. Render assets in the buffer
217 */
218 @Override
219 public void run() {
220 Configuration config = chooseConfiguration(mBitmaps, mPixelCount, mVersionName);
221 if (DEBUG_ATLAS) Log.d(LOG_TAG, "Loaded configuration: " + config);
222
223 if (config != null) {
224 mBuffer = GraphicBuffer.create(config.width, config.height,
225 PixelFormat.RGBA_8888, GRAPHIC_BUFFER_USAGE);
226
227 if (mBuffer != null) {
228 Atlas atlas = new Atlas(config.type, config.width, config.height, config.flags);
229 if (renderAtlas(mBuffer, atlas, config.count)) {
230 mAtlasReady.set(true);
231 }
232 }
233 }
234 }
235
236 /**
237 * Renders a list of bitmaps into the atlas. The position of each bitmap
238 * was decided by the packing algorithm and will be honored by this
239 * method. If need be this method will also rotate bitmaps.
240 *
241 * @param buffer The buffer to render the atlas entries into
242 * @param atlas The atlas to pack the bitmaps into
243 * @param packCount The number of bitmaps that will be packed in the atlas
244 *
245 * @return true if the atlas was rendered, false otherwise
246 */
247 @SuppressWarnings("MismatchedReadAndWriteOfArray")
248 private boolean renderAtlas(GraphicBuffer buffer, Atlas atlas, int packCount) {
249 // Use a Source blend mode to improve performance, the target bitmap
250 // will be zero'd out so there's no need to waste time applying blending
251 final Paint paint = new Paint();
252 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
253
254 // We always render the atlas into a bitmap. This bitmap is then
255 // uploaded into the GraphicBuffer using OpenGL to swizzle the content
John Reck87ffb632015-04-15 13:24:47 -0700256 final Bitmap atlasBitmap = Bitmap.createBitmap(
257 buffer.getWidth(), buffer.getHeight(), Bitmap.Config.ARGB_8888);
258 final Canvas canvas = new Canvas(atlasBitmap);
Romain Guy3b748a42013-04-17 18:54:38 -0700259
260 final Atlas.Entry entry = new Atlas.Entry();
261
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000262 mAtlasMap = new long[packCount * ATLAS_MAP_ENTRY_FIELD_COUNT];
263 long[] atlasMap = mAtlasMap;
Romain Guy3b748a42013-04-17 18:54:38 -0700264 int mapIndex = 0;
265
266 boolean result = false;
John Reck87ffb632015-04-15 13:24:47 -0700267 final long startRender = System.nanoTime();
268 final int count = mBitmaps.size();
Romain Guy3b748a42013-04-17 18:54:38 -0700269
John Reck87ffb632015-04-15 13:24:47 -0700270 for (int i = 0; i < count; i++) {
271 final Bitmap bitmap = mBitmaps.get(i);
272 if (atlas.pack(bitmap.getWidth(), bitmap.getHeight(), entry) != null) {
273 // We have more bitmaps to pack than the current configuration
274 // says, we were most likely not able to detect a change in the
275 // list of preloaded drawables, abort and delete the configuration
276 if (mapIndex >= mAtlasMap.length) {
277 deleteDataFile();
278 break;
Romain Guy3b748a42013-04-17 18:54:38 -0700279 }
John Reck87ffb632015-04-15 13:24:47 -0700280
281 canvas.save();
282 canvas.translate(entry.x, entry.y);
283 if (entry.rotated) {
284 canvas.translate(bitmap.getHeight(), 0.0f);
285 canvas.rotate(90.0f);
286 }
287 canvas.drawBitmap(bitmap, 0.0f, 0.0f, null);
288 canvas.restore();
289 atlasMap[mapIndex++] = bitmap.refSkPixelRef();
290 atlasMap[mapIndex++] = entry.x;
291 atlasMap[mapIndex++] = entry.y;
292 atlasMap[mapIndex++] = entry.rotated ? 1 : 0;
Romain Guy3b748a42013-04-17 18:54:38 -0700293 }
John Reck87ffb632015-04-15 13:24:47 -0700294 }
Romain Guy3b748a42013-04-17 18:54:38 -0700295
John Reck87ffb632015-04-15 13:24:47 -0700296 final long endRender = System.nanoTime();
297 releaseCanvas(canvas, atlasBitmap);
298 result = nUploadAtlas(buffer, atlasBitmap);
299 atlasBitmap.recycle();
300 final long endUpload = System.nanoTime();
Romain Guy3b748a42013-04-17 18:54:38 -0700301
John Reck87ffb632015-04-15 13:24:47 -0700302 if (DEBUG_ATLAS) {
303 float renderDuration = (endRender - startRender) / 1000.0f / 1000.0f;
304 float uploadDuration = (endUpload - endRender) / 1000.0f / 1000.0f;
305 Log.d(LOG_TAG, String.format("Rendered atlas in %.2fms (%.2f+%.2fms)",
306 renderDuration + uploadDuration, renderDuration, uploadDuration));
Romain Guy3b748a42013-04-17 18:54:38 -0700307 }
308
309 return result;
310 }
311
312 /**
Romain Guy3b748a42013-04-17 18:54:38 -0700313 * Releases the canvas used to render into the buffer. Calling this method
314 * will release any resource previously acquired. If {@link #DEBUG_ATLAS_TEXTURE}
315 * is turend on, calling this method will write the content of the atlas
316 * to disk in /data/system/atlas.png for debugging.
317 */
John Reck87ffb632015-04-15 13:24:47 -0700318 private void releaseCanvas(Canvas canvas, Bitmap atlasBitmap) {
John Reckc294d122015-04-13 15:20:29 -0700319 canvas.setBitmap(null);
Romain Guy3b748a42013-04-17 18:54:38 -0700320 if (DEBUG_ATLAS_TEXTURE) {
Romain Guy3b748a42013-04-17 18:54:38 -0700321
322 File systemDirectory = new File(Environment.getDataDirectory(), "system");
323 File dataFile = new File(systemDirectory, "atlas.png");
324
325 try {
326 FileOutputStream out = new FileOutputStream(dataFile);
John Reck87ffb632015-04-15 13:24:47 -0700327 atlasBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Romain Guy3b748a42013-04-17 18:54:38 -0700328 out.close();
329 } catch (FileNotFoundException e) {
330 // Ignore
331 } catch (IOException e) {
332 // Ignore
333 }
Romain Guy3b748a42013-04-17 18:54:38 -0700334 }
335 }
336 }
337
John Reckc294d122015-04-13 15:20:29 -0700338 private static native boolean nUploadAtlas(GraphicBuffer buffer, Bitmap bitmap);
Romain Guy3b748a42013-04-17 18:54:38 -0700339
340 @Override
Romain Guy80b12fc2013-05-29 15:54:25 -0700341 public boolean isCompatible(int ppid) {
342 return ppid == android.os.Process.myPpid();
343 }
344
345 @Override
Romain Guy3b748a42013-04-17 18:54:38 -0700346 public GraphicBuffer getBuffer() throws RemoteException {
347 return mAtlasReady.get() ? mBuffer : null;
348 }
349
350 @Override
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000351 public long[] getMap() throws RemoteException {
Romain Guy3b748a42013-04-17 18:54:38 -0700352 return mAtlasReady.get() ? mAtlasMap : null;
353 }
354
355 /**
356 * Finds the best atlas configuration to pack the list of supplied bitmaps.
357 * This method takes advantage of multi-core systems by spawning a number
358 * of threads equal to the number of available cores.
359 */
360 private static Configuration computeBestConfiguration(
361 ArrayList<Bitmap> bitmaps, int pixelCount) {
362 if (DEBUG_ATLAS) Log.d(LOG_TAG, "Computing best atlas configuration...");
363
364 long begin = System.nanoTime();
365 List<WorkerResult> results = Collections.synchronizedList(new ArrayList<WorkerResult>());
366
367 // Don't bother with an extra thread if there's only one processor
368 int cpuCount = Runtime.getRuntime().availableProcessors();
369 if (cpuCount == 1) {
370 new ComputeWorker(MIN_SIZE, MAX_SIZE, STEP, bitmaps, pixelCount, results, null).run();
371 } else {
ztenghui072be092015-04-01 13:26:08 -0700372 int start = MIN_SIZE + (cpuCount - 1) * STEP;
373 int end = MAX_SIZE;
Romain Guy3b748a42013-04-17 18:54:38 -0700374 int step = STEP * cpuCount;
375
376 final CountDownLatch signal = new CountDownLatch(cpuCount);
377
ztenghui072be092015-04-01 13:26:08 -0700378 for (int i = 0; i < cpuCount; i++, start -= STEP, end -= STEP) {
Romain Guy3b748a42013-04-17 18:54:38 -0700379 ComputeWorker worker = new ComputeWorker(start, end, step,
380 bitmaps, pixelCount, results, signal);
381 new Thread(worker, "Atlas Worker #" + (i + 1)).start();
382 }
383
Xiaohui Chenab7f01d2015-04-07 10:12:24 -0700384 boolean isAllWorkerFinished;
Romain Guy3b748a42013-04-17 18:54:38 -0700385 try {
Xiaohui Chenab7f01d2015-04-07 10:12:24 -0700386 isAllWorkerFinished = signal.await(10, TimeUnit.SECONDS);
Romain Guy3b748a42013-04-17 18:54:38 -0700387 } catch (InterruptedException e) {
388 Log.w(LOG_TAG, "Could not complete configuration computation");
389 return null;
390 }
Xiaohui Chenab7f01d2015-04-07 10:12:24 -0700391
392 if (!isAllWorkerFinished) {
393 // We have to abort here, otherwise the async updates on "results" would crash the
394 // sort later.
395 Log.w(LOG_TAG, "Could not complete configuration computation before timeout.");
396 return null;
397 }
Romain Guy3b748a42013-04-17 18:54:38 -0700398 }
399
400 // Maximize the number of packed bitmaps, minimize the texture size
401 Collections.sort(results, new Comparator<WorkerResult>() {
402 @Override
403 public int compare(WorkerResult r1, WorkerResult r2) {
404 int delta = r2.count - r1.count;
405 if (delta != 0) return delta;
406 return r1.width * r1.height - r2.width * r2.height;
407 }
408 });
409
410 if (DEBUG_ATLAS) {
411 float delay = (System.nanoTime() - begin) / 1000.0f / 1000.0f / 1000.0f;
ztenghui072be092015-04-01 13:26:08 -0700412 Log.d(LOG_TAG, String.format("Found best atlas configuration (out of %d) in %.2fs",
413 results.size(), delay));
Romain Guy3b748a42013-04-17 18:54:38 -0700414 }
415
416 WorkerResult result = results.get(0);
417 return new Configuration(result.type, result.width, result.height, result.count);
418 }
419
420 /**
421 * Returns the path to the file containing the best computed
422 * atlas configuration.
423 */
424 private static File getDataFile() {
425 File systemDirectory = new File(Environment.getDataDirectory(), "system");
426 return new File(systemDirectory, "framework_atlas.config");
427 }
428
429 private static void deleteDataFile() {
430 Log.w(LOG_TAG, "Current configuration inconsistent with assets list");
431 if (!getDataFile().delete()) {
432 Log.w(LOG_TAG, "Could not delete the current configuration");
433 }
434 }
435
436 private File getFrameworkResourcesFile() {
437 return new File(mContext.getApplicationInfo().sourceDir);
438 }
439
440 /**
441 * Returns the best known atlas configuration. This method will either
442 * read the configuration from disk or start a brute-force search
443 * and save the result out to disk.
444 */
445 private Configuration chooseConfiguration(ArrayList<Bitmap> bitmaps, int pixelCount,
446 String versionName) {
447 Configuration config = null;
448
449 final File dataFile = getDataFile();
450 if (dataFile.exists()) {
451 config = readConfiguration(dataFile, versionName);
452 }
453
454 if (config == null) {
455 config = computeBestConfiguration(bitmaps, pixelCount);
456 if (config != null) writeConfiguration(config, dataFile, versionName);
457 }
458
459 return config;
460 }
461
462 /**
463 * Writes the specified atlas configuration to the specified file.
464 */
465 private void writeConfiguration(Configuration config, File file, String versionName) {
466 BufferedWriter writer = null;
467 try {
468 writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
469 writer.write(getBuildIdentifier(versionName));
470 writer.newLine();
471 writer.write(config.type.toString());
472 writer.newLine();
473 writer.write(String.valueOf(config.width));
474 writer.newLine();
475 writer.write(String.valueOf(config.height));
476 writer.newLine();
477 writer.write(String.valueOf(config.count));
478 writer.newLine();
479 writer.write(String.valueOf(config.flags));
480 writer.newLine();
481 } catch (FileNotFoundException e) {
482 Log.w(LOG_TAG, "Could not write " + file, e);
483 } catch (IOException e) {
484 Log.w(LOG_TAG, "Could not write " + file, e);
485 } finally {
486 if (writer != null) {
487 try {
488 writer.close();
489 } catch (IOException e) {
490 // Ignore
491 }
492 }
493 }
494 }
495
496 /**
497 * Reads an atlas configuration from the specified file. This method
498 * returns null if an error occurs or if the configuration is invalid.
499 */
500 private Configuration readConfiguration(File file, String versionName) {
501 BufferedReader reader = null;
502 Configuration config = null;
503 try {
504 reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
505
506 if (checkBuildIdentifier(reader, versionName)) {
507 Atlas.Type type = Atlas.Type.valueOf(reader.readLine());
508 int width = readInt(reader, MIN_SIZE, MAX_SIZE);
509 int height = readInt(reader, MIN_SIZE, MAX_SIZE);
510 int count = readInt(reader, 0, Integer.MAX_VALUE);
511 int flags = readInt(reader, Integer.MIN_VALUE, Integer.MAX_VALUE);
512
513 config = new Configuration(type, width, height, count, flags);
514 }
515 } catch (IllegalArgumentException e) {
516 Log.w(LOG_TAG, "Invalid parameter value in " + file, e);
517 } catch (FileNotFoundException e) {
518 Log.w(LOG_TAG, "Could not read " + file, e);
519 } catch (IOException e) {
520 Log.w(LOG_TAG, "Could not read " + file, e);
521 } finally {
522 if (reader != null) {
523 try {
524 reader.close();
525 } catch (IOException e) {
526 // Ignore
527 }
528 }
529 }
530 return config;
531 }
532
533 private static int readInt(BufferedReader reader, int min, int max) throws IOException {
534 return Math.max(min, Math.min(max, Integer.parseInt(reader.readLine())));
535 }
536
537 /**
538 * Compares the next line in the specified buffered reader to the current
539 * build identifier. Returns whether the two values are equal.
540 *
541 * @see #getBuildIdentifier(String)
542 */
543 private boolean checkBuildIdentifier(BufferedReader reader, String versionName)
544 throws IOException {
545 String deviceBuildId = getBuildIdentifier(versionName);
546 String buildId = reader.readLine();
547 return deviceBuildId.equals(buildId);
548 }
549
550 /**
551 * Returns an identifier for the current build that can be used to detect
552 * likely changes to framework resources. The build identifier is made of
553 * several distinct values:
554 *
555 * build fingerprint/framework version name/file size of framework resources apk
556 *
557 * Only the build fingerprint should be necessary on user builds but
558 * the other values are useful to detect changes on eng builds during
559 * development.
560 *
561 * This identifier does not attempt to be exact: a new identifier does not
562 * necessarily mean the preloaded drawables have changed. It is important
563 * however that whenever the list of preloaded drawables changes, this
564 * identifier changes as well.
565 *
566 * @see #checkBuildIdentifier(java.io.BufferedReader, String)
567 */
568 private String getBuildIdentifier(String versionName) {
569 return SystemProperties.get("ro.build.fingerprint", "") + '/' + versionName + '/' +
570 String.valueOf(getFrameworkResourcesFile().length());
571 }
572
573 /**
574 * Atlas configuration. Specifies the algorithm, dimensions and flags to use.
575 */
576 private static class Configuration {
577 final Atlas.Type type;
578 final int width;
579 final int height;
580 final int count;
581 final int flags;
582
583 Configuration(Atlas.Type type, int width, int height, int count) {
584 this(type, width, height, count, Atlas.FLAG_DEFAULTS);
585 }
586
587 Configuration(Atlas.Type type, int width, int height, int count, int flags) {
588 this.type = type;
589 this.width = width;
590 this.height = height;
591 this.count = count;
592 this.flags = flags;
593 }
594
595 @Override
596 public String toString() {
597 return type.toString() + " (" + width + "x" + height + ") flags=0x" +
598 Integer.toHexString(flags) + " count=" + count;
599 }
600 }
601
602 /**
603 * Used during the brute-force search to gather information about each
604 * variant of the packing algorithm.
605 */
606 private static class WorkerResult {
607 Atlas.Type type;
608 int width;
609 int height;
610 int count;
611
612 WorkerResult(Atlas.Type type, int width, int height, int count) {
613 this.type = type;
614 this.width = width;
615 this.height = height;
616 this.count = count;
617 }
618
619 @Override
620 public String toString() {
621 return String.format("%s %dx%d", type.toString(), width, height);
622 }
623 }
624
625 /**
626 * A compute worker will try a finite number of variations of the packing
627 * algorithms and save the results in a supplied list.
628 */
629 private static class ComputeWorker implements Runnable {
630 private final int mStart;
631 private final int mEnd;
632 private final int mStep;
633 private final List<Bitmap> mBitmaps;
634 private final List<WorkerResult> mResults;
635 private final CountDownLatch mSignal;
636 private final int mThreshold;
637
638 /**
639 * Creates a new compute worker to brute-force through a range of
640 * packing algorithms variants.
641 *
642 * @param start The minimum texture width to try
643 * @param end The maximum texture width to try
644 * @param step The number of pixels to increment the texture width by at each step
645 * @param bitmaps The list of bitmaps to pack in the atlas
646 * @param pixelCount The total number of pixels occupied by the list of bitmaps
647 * @param results The list of results in which to save the brute-force search results
648 * @param signal Latch to decrement when this worker is done, may be null
649 */
650 ComputeWorker(int start, int end, int step, List<Bitmap> bitmaps, int pixelCount,
651 List<WorkerResult> results, CountDownLatch signal) {
652 mStart = start;
653 mEnd = end;
654 mStep = step;
655 mBitmaps = bitmaps;
656 mResults = results;
657 mSignal = signal;
658
659 // Minimum number of pixels we want to be able to pack
660 int threshold = (int) (pixelCount * PACKING_THRESHOLD);
661 // Make sure we can find at least one configuration
662 while (threshold > MAX_SIZE * MAX_SIZE) {
663 threshold >>= 1;
664 }
665 mThreshold = threshold;
666 }
667
668 @Override
669 public void run() {
670 if (DEBUG_ATLAS) Log.d(LOG_TAG, "Running " + Thread.currentThread().getName());
671
672 Atlas.Entry entry = new Atlas.Entry();
673 for (Atlas.Type type : Atlas.Type.values()) {
ztenghui072be092015-04-01 13:26:08 -0700674 for (int width = mEnd; width > mStart; width -= mStep) {
675 for (int height = MAX_SIZE; height > MIN_SIZE; height -= STEP) {
Romain Guy3b748a42013-04-17 18:54:38 -0700676 // If the atlas is not big enough, skip it
677 if (width * height <= mThreshold) continue;
678
679 final int count = packBitmaps(type, width, height, entry);
680 if (count > 0) {
681 mResults.add(new WorkerResult(type, width, height, count));
682 // If we were able to pack everything let's stop here
683 // Increasing the height further won't make things better
684 if (count == mBitmaps.size()) {
685 break;
686 }
687 }
688 }
689 }
690 }
691
692 if (mSignal != null) {
693 mSignal.countDown();
694 }
695 }
696
697 private int packBitmaps(Atlas.Type type, int width, int height, Atlas.Entry entry) {
698 int total = 0;
699 Atlas atlas = new Atlas(type, width, height);
700
701 final int count = mBitmaps.size();
702 for (int i = 0; i < count; i++) {
703 final Bitmap bitmap = mBitmaps.get(i);
704 if (atlas.pack(bitmap.getWidth(), bitmap.getHeight(), entry) != null) {
705 total++;
706 }
707 }
708
709 return total;
710 }
711 }
712}