Welcome to Ndroid-tech-frontier Open Source project, regular translation of foreign Android high-quality technology, open Source Library, software architecture design, test and other articles
- Original link: Introducing fresco:a new Image Library for Android
- Translator: Zhaokaiqiang
- Reviewer: chaossss
- Reviewer: bboyfeiyu
- Reviewer: billionwang
- Status: Complete
On Android devices, high-speed and efficient display of images is extremely important.
Over the past few years, we have encountered a lot of problems in how to efficiently store images.
The picture is too big, but the memory of the phone is very small. The R, G, B, and alpha channels of each pixel occupy a total of 4byte of space.
Assuming the phone's screen is 480*800, a screen-sized picture takes up 1.5M of memory. The phone's memory is usually small, especially if the Android device allocates memory for each application. On some devices. The memory allocated to the Facebook app is only 16MB.
A picture is going to occupy one of its very memory.
What happens when your app's memory overflows? Of course it will crash!
We have developed a library to solve the problem, we call it fresco.
It can manage the images and memory used, and the app no longer crashes.
Memory Area
To understand exactly what Facebook is doing. Before we do, we need to understand the difference between the heap memory that Android can use. The Java heap memory size of each app in Android is strictly limited.
Each object is instantiated in heap memory using Java new, which is a relatively secure area in memory.
The memory has a garbage collection mechanism, so when the app is not using memory. The system will take its own initiative to reclaim the memory.
Unfortunately, it is. The process of garbage collection of memory is exactly where the problem lies. When memory is garbage collected, memory is not just garbage collected. The Android app was completely terminated. This is one of the reasons why users are most likely to lag or briefly suspend their animation when using the App.
This makes it frustrating for users who are using the app, and then they may be anxious to swipe the screen or click the button, but the app's only response is to get the app back to normal. Ask the user to wait patiently
Compared with. The native heap is assigned by the new C + + program.
There are a lot of other available memory in the native heap, and the app is limited only by the physical available memory of the device, and there is no garbage collection mechanism or other thing to drag.
But the C + + program ape has to reclaim every chunk of memory that it allocates, or it will cause a memory leak that eventually causes the program to crash.
Android has a second area of memory called Ashmem.
It operates more like a native heap. However, there are additional system calls. When Android operates the Ashmem heap, it extracts the memory area of the heap that contains the data from the Ashmem heap, rather than releasing it, which is a weak memory release mode This part of the memory that is extracted is only released when the system really needs a lot of other memory (system memory is not enough). When Android put this part of the memory that was extracted back into the Ashmem heap, only the memory space to be extracted is not released. The previous data will be restored to the appropriate location.
Bitmap that can be eliminated
Ashmem cannot be processed directly by the Java application. But there are some exceptions. The picture is one of them. When you create a bitmap that is not compressed. The Android API agrees that you specify whether it can be cleared.
BitmapFactory.Options = new BitmapFactory.Options();options.inPurgeable = true;Bitmap bitmap = BitmapFactory.decodeByteArray0, jpeg.length, options);
After the above code is processed, the bitmap that can be purged reside in the Ashmem heap. No matter what happens, the garbage collector does not proactively reclaim these Bitmap. When the Android drawing system renders these images, the Android system library extracts the Bitmap from the Ashmem heap. And when the rendering is finished, these Bitmap are returned to their original positions.
Suppose that a drawn picture needs to be redrawn again, and the system just needs to decode it again, which is a very fast operation.
It sounds like a perfect solution. The problem is that the bitmap decoding operation is running on the UI thread. Bitmap decoding is CPU intensive and can cause UI congestion when consumed too much. For this reason, Google does not recommend using this feature. Now they recommend using a different feature,--inbitmap. However, this feature is not supported until after Android3.0. Even so, this feature is not very practical, unless all the images in the App are the same size. This is obviously not applicable to the Fackbook.
Until the 4.4 version number. This restriction was removed. But what we need is a generic solution that can run on Android 2.3-the latest version number.
Self - reliance
For the "decoding operation that caused the UI to feign death" as mentioned above, we found a solution that made the UI display and memory management work well at the same time. Suppose we put the extracted memory area back in place before the UI thread renders it, and make sure that it will never be extracted again, then we can put the images in the Ashmem. There is no problem with the UI suspended animation at the same time. Fortunately, there is a function in the NDK of Android that perfectly implements this requirement. The name is called Androidbitmap_lockpixels. This function was originally intended to be run after calling Unlockpixels to extract the memory area again.
We made a breakthrough when we realized that there was no need for us to do so. Assuming we just call lockpixels without invoking the corresponding unlockpixels, we can create a memory-safe image in Java's heap memory. And does not cause the UI thread to load slowly. With just a few lines of C + + code, we've conquered the problem perfectly.
Write Java code in C + + 's mind
As the Spider-Man said: "The stronger the ability." The greater the responsibility. "Bitmap that can be purged are neither reclaimed by the garbage collector nor handled by the ASHMEM built-in cleanup mechanism, which makes it possible to use them to cause memory leaks."
So we can only rely on ourselves.
In C + +, the usual solution is to create a smart pointer class that implements a reference count. These need to take advantage of the language features of C + +-copy constructors, assignment operators, and deterministic destructors.
Such a syntax does not exist in Java. Because the garbage collector can handle all this. So we have to implement these assurance mechanisms in C + + in some way in Java.
We have created two classes to complete this event. One of them is called "sharedreference", it has addreference and deletereference two methods, the caller must take the base class object or let it out of scope. Once the reference counter is zeroed, resource processing (bitmap.recycle) occurs.
However. Obviously, it's easy to make mistakes for Java developers to call these methods. The Java language is designed to avoid doing such a thing!
So above the sharedreference, we built the Closeablereference class. It not only realizes the Java Closeable interface, but also implements the Cloneable interface. Its constructor and clone () method call AddReference (), and the Close () method calls Deletereference (). So Java developers need to follow the following two simple rules:
- When assigning closeablereference new objects, call. Clone ().
- Call. Close () when it is out of scope, typically in a finally code block.
These rules can effectively prevent memory leaks and allow us to enjoy native memory management and communication in large Java programs like Fackbook's androidclient.
Not just the loading program, it's a pipe
There are a number of steps required to display pictures on a mobile device:
Several excellent open source libraries are run in this order, such as Picasso,universal Image loader,glide and volley, and so on. These open source libraries have made a significant contribution to the development of Android. We believe that Fresco will perform better in several important ways.
The difference is that the above steps are considered to be pipelines, not just the loader. Each step and other aspect should be as independent as possible, pass the data and the parameters in, then produce an output, it is so simple. It should be able to do some operations. Whether it is parallel or serial.
Some operations can only operate under the characteristic conditions. Some have special requirements to run on the thread.
In addition, when we consider improving the image. All the pictures will become very complicated. Many people use Facebook at low speeds, and we want these people to see pictures as quickly as possible. Even before the picture is completely downloaded.
Don't fret, embrace the stream
In Java. Asynchronous code has historically been run through the future mechanism. In another thread the code is submitted to run, and then a future-like object can check that the result of the run is complete. But. This is only assuming that there is only one outcome to the situation. When dealing with progressive images, we want to be able to display the results in a complete and continuous sequence.
Our solution is to define a more generalized future version number. Called DataSource. It provides a subscription method. The caller must pass in a datasubscriber and executor.
Datasubscriber is able to get the results from datasource to processing and processing, and provides a very simple way to differentiate.
Because we need to deal with these objects very often. So there must be a clear close call, fortunately. DataSource itself is closeable.
In the background. Each box above implements a new framework called "producer/Consumer". The problem is that we are getting inspiration from Reactivex.
Our system has a similar interface to Rxjava. However, it is more suitable for mobile devices and has built-in support for Closeables.
Keep the interface simple. Producer only has a method called Produceresults. This method requires a consumer object. Conversely, consumer has a Onnewresult method.
We use systems like this to connect producer.
Suppose we have a producer job of converting Type I to type O, then it should look like this:
Public class outputproducer<I, O> implements Producer< O> { Private FinalProducer<i> Minputproducer; PublicOutputproducer (producer<i> inputproducer) { This. minputproducer = Inputproducer; } Public voidProduceresults (consumer<o> Outputconsumer, Producercontext context) {consumer<i> InputConsumer =NewInputconsumer (Outputconsumer); Minputproducer.produceresults (Inputconsumer, context); }Private Static class Inputconsumer implements Consumer<I> { Private FinalConsumer<o> Moutputconsumer; PublicInputconsumer (consumer<o> outputconsumer) {moutputconsumer = Outputconsumer; } Public voidOnnewresult (I Newresult,BooleanIslast) {O output = Doactualwork (Newresult); Moutputconsumer.onnewresult (output, islast); } }}
This allows us to string together a very complex set of steps. They are also able to maintain their logical independence at the same time.
Full coverage of animations
People who use Facebook are very fond of stickers. Because it can be animated to store GIF and web formats. Assuming that these formats are supported, new challenges are required. Since each animation is made up of more than one picture, you need to decode each image, store it in memory, and then display it. For a larger animation. It is not feasible to put each frame of picture in memory.
We built animateddrawable, a powerful drawable capable of rendering animations, supported in GIF and WEBP formats at the same time. Animateddrawable implements the standard Android Animatable interface, so the caller can start or stop the animation arbitrarily. In order to optimize memory usage. Suppose the picture is small enough. We cache the images in memory, but the assumptions are too large. We are able to decode these images quickly. These behavior callers are completely controllable.
All the backstage is implemented in C + + code.
We keep a copy of the decoding data and metadata parsing, such as width and height. We quoted technical data, which agreed that multiple Java-side drawables visited a WEBP image at the same time.
How to Love you? I'll tell you ...
When a picture is downloaded from the Web, we want to display a bitmap. Assuming the download fails, we will display an error flag. When the picture is loaded. We have a gradient animation. By using hardware acceleration, we can scale proportionally, or the matrix is transformed into the size we want and then rendered.
We don't always shrink from the center of the picture. Then we are able to customize the focus point of the indentation. Sometimes we want to show rounded corners and even rounded pictures. All of these actions should be quick and smooth.
Our previous implementation was to use the Android View Object-The time has come to be able to replace the placeholder view with ImageView.
This operation is very slow.
Changing the view will allow Android to force the entire layout to refresh when the user swipes. This is definitely not the effect you want to see.
It is wiser to use Android's Drawables, which can be quickly replaced.
So we created the Drawee. This is a picture display framework like the MVC architecture. The model is called Draweehierarchy. It is implemented as a layer of drawables, and for the underlying image, each zengdu has a specific function-imaging, cascading, gradients, or retraction.
The draweecontrollers is piped to the image--or other images loaded into the library--and handles picture manipulation in the background. They receive events from pipelines and decide what to do with them. They control the actual operation of the draweehierarchy-whether it is a placeholder picture, an error condition, or a finished picture.
Draweeviews is not much of a function, but it is essential.
They monitor Android's view no longer displays system events on the screen.
When the picture leaves the screen, Draweeview is able to tell Draweecontroller to turn off the used image resource.
This prevents memory leaks. Also, assuming that it is not already within the screen range, the controller tells the picture pipeline to cancel the network request. Therefore, when scrolling a long list of pictures like Fackbook, there will be no frequent network requests.
Through these efforts, the hard work of displaying pictures is gone. The calling code only needs to instantiate a draweeview and then specify a URI and other optional parameters to be able to do so. All the rest will be on their own initiative.
Developers don't need to worry about managing image memory. or update the image stream. Fresco did everything for them.
Fresco
After this image shows and operates a complex library of tools, we want to share it with the Android developer community. We are pleased to announce that from today onwards, this project has been opened as an open source code!
Murals are painting techniques that have been welcomed by people all over the world for centuries.
Many of our great artists use such names, from the Italian Renaissance master Raphael to the mural artist Sri Lanka. We're not pretending to reach this great level, and we really want Android developers to be as good as we did in creating this open Source library. Very enjoyable to use it.
Many other
Fresco Chinese documents
Facebook launches Android images loaded into storage-fresco