19 Commits

Author SHA1 Message Date
ibireme 24c8bd4911 update podspec 2016-02-27 19:14:15 +08:00
ibireme 6e8f23ff62 update podspec 2016-02-27 19:12:28 +08:00
ibireme 7af0c1422f bumping the version to 0.9.4 2016-02-27 18:50:27 +08:00
ibireme c4c9eb2c93 bumped the libwebp framework to 0.5 2016-02-27 18:24:03 +08:00
ibireme eb6365610b swift api compatibility 2016-02-26 19:03:42 +08:00
ibireme b5b08df802 bugfix: wrong result when encodeing UIImage which orientation is not UIImageOrientationUp 2016-02-26 00:27:26 +08:00
ibireme f5f6072415 potential problem in _YYAnimatedImageViewFetchOperation 2016-02-25 22:39:38 +08:00
ibireme b7beeaa301 support broken webp file 2016-02-25 00:27:28 +08:00
ibireme 0524b61698 potentially problem in low memory device 2016-02-22 14:49:38 +08:00
ibireme df8881a906 bugfix:#14 2016-02-17 22:42:16 +08:00
ibireme 23c4176773 updated readme 2016-01-28 00:43:14 +08:00
ibireme a6ad8b6cb4 updated readme 2016-01-22 11:27:15 +08:00
ibireme 30704ca61a bumping the version to 0.9.3 2016-01-18 00:11:47 +08:00
ibireme e6b0a5133f Stop using spinlocks
Apple engineers have pointed out that OSSpinLocks are vulnerable to live locking
on iOS in cases of priority inversion:

. http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
. https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
2016-01-15 15:42:36 +08:00
ibireme f64128caa6 bugfix: YYAnimatedImageView.autoPlayAnimatedImage is NO when created from xib 2016-01-14 18:48:39 +08:00
Yaoyuan 8f49e73c7d Merge pull request #9 from SergioChan/master
Missed extension support for apng
2016-01-06 21:18:10 +08:00
Sergio Chan 43caa9750b Missed extension support for apng
Missed extension support for apng file like ‘xx.apng’
2016-01-06 17:02:41 +08:00
ibireme 9dbf057ee2 code optimising 2015-12-28 23:42:40 +08:00
ibireme 2712c6a356 Fix typo 2015-12-24 13:37:10 +08:00
21 changed files with 626 additions and 254 deletions
+1 -1
View File
@@ -572,7 +572,7 @@ static inline void YYBenchmark(void (^block)(void), void (^complete)(double ms))
CoverDecodeBlock yyCoverDecoder = ^(NSData *data) {
@autoreleasepool {
YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:1];
[decoder frameAtIndex:0 decodeForDisplay:YES];;
[decoder frameAtIndex:0 decodeForDisplay:YES];
}
};
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.9.2</string>
<string>0.9.4</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+5 -4
View File
@@ -1,4 +1,4 @@
YYImage <a href="#中文介绍">中文介绍</a>
YYImage
==============
[![License MIT](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/ibireme/YYImage/master/LICENSE)&nbsp;
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)&nbsp;
@@ -328,7 +328,7 @@ YYImage: 功能强大的 iOS 图像框架。<br/>
### 手动安装
1. 下载 YYImage 文件夹内的所有内容。
2. 将 YYModel 内的源文件添加(拖放)到你的工程。
2. 将 YYImage 内的源文件添加(拖放)到你的工程。
3. 链接以下 frameworks:
* UIKit
* CoreFoundation
@@ -353,11 +353,12 @@ YYImage: 功能强大的 iOS 图像框架。<br/>
许可证
==============
YYModel 使用 MIT 许可证,详情见 LICENSE 文件。
YYImage 使用 MIT 许可证,详情见 LICENSE 文件。
相关链接
==============
[移动端图片格式调研](http://blog.ibireme.com/2015/11/02/mobile_image_benchmark/)<br/>
[iOS 处理图片的一些小 Tip](http://blog.ibireme.com/2015/11/02/ios_image_tips/)
[iOS 处理图片的一些小 Tip](http://blog.ibireme.com/2015/11/02/ios_image_tips/)
+6 -3
View File
@@ -78,7 +78,7 @@
#define PACKAGE_NAME "libwebp"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libwebp 0.4.4"
#define PACKAGE_STRING "libwebp 0.5.0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libwebp"
@@ -87,7 +87,7 @@
#define PACKAGE_URL "http://developers.google.com/speed/webp"
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.4.4"
#define PACKAGE_VERSION "0.5.0"
/* Define to necessary symbol if this constant uses a non-standard name on
your system. */
@@ -97,7 +97,7 @@
#define STDC_HEADERS 1
/* Version number of package */
#define VERSION "0.4.4"
#define VERSION "0.5.0"
/* Enable experimental code */
/* #undef WEBP_EXPERIMENTAL_FEATURES */
@@ -123,6 +123,9 @@
/* Set to 1 if SSE2 is supported */
/* #undef WEBP_HAVE_SSE2 */
/* Set to 1 if SSE4.1 is supported */
/* #undef WEBP_HAVE_SSE41 */
/* Set to 1 if TIFF library is installed */
/* #undef WEBP_HAVE_TIFF */
+9 -24
View File
@@ -20,7 +20,7 @@
extern "C" {
#endif
#define WEBP_DECODER_ABI_VERSION 0x0203 // MAJOR(8b) + MINOR(8b)
#define WEBP_DECODER_ABI_VERSION 0x0208 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
@@ -48,7 +48,7 @@ WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size,
// Decodes WebP images pointed to by 'data' and returns RGBA samples, along
// with the dimensions in *width and *height. The ordering of samples in
// memory is R, G, B, A, R, G, B, A... in scan order (endian-independent).
// The returned pointer should be deleted calling free().
// The returned pointer should be deleted calling WebPFree().
// Returns NULL in case of error.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size,
int* width, int* height);
@@ -73,9 +73,9 @@ WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size,
// Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer
// returned is the Y samples buffer. Upon return, *u and *v will point to
// the U and V chroma data. These U and V buffers need NOT be free()'d,
// unlike the returned Y luma one. The dimension of the U and V planes
// are both (*width + 1) / 2 and (*height + 1)/ 2.
// the U and V chroma data. These U and V buffers need NOT be passed to
// WebPFree(), unlike the returned Y luma one. The dimension of the U and V
// planes are both (*width + 1) / 2 and (*height + 1)/ 2.
// Upon return, the Y buffer has a stride returned as '*stride', while U and V
// have a common stride returned as '*uv_stride'.
// Return NULL in case of error.
@@ -85,6 +85,9 @@ WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size,
uint8_t** u, uint8_t** v,
int* stride, int* uv_stride);
// Releases memory returned by the WebPDecode*() functions above.
WEBP_EXTERN(void) WebPFree(void* ptr);
// These five functions are variants of the above ones, that decode the image
// directly into a pre-allocated buffer 'output_buffer'. The maximum storage
// available in this buffer is indicated by 'output_buffer_size'. If this
@@ -406,12 +409,7 @@ struct WebPBitstreamFeatures {
int has_animation; // True if the bitstream is an animation.
int format; // 0 = undefined (/mixed), 1 = lossy, 2 = lossless
// Unused for now:
int no_incremental_decoding; // if true, using incremental decoding is not
// recommended.
int rotate; // TODO(later)
int uv_sampling; // should be 0 for now. TODO(later)
uint32_t pad[2]; // padding for later use
uint32_t pad[5]; // padding for later use
};
// Internal, version-checked, entry point
@@ -442,23 +440,10 @@ struct WebPDecoderOptions {
int scaled_width, scaled_height; // final resolution
int use_threads; // if true, use multi-threaded decoding
int dithering_strength; // dithering strength (0=Off, 100=full)
#if WEBP_DECODER_ABI_VERSION > 0x0203
int flip; // flip output vertically
#endif
#if WEBP_DECODER_ABI_VERSION > 0x0204
int alpha_dithering_strength; // alpha dithering strength in [0..100]
#endif
// Unused for now:
int force_rotation; // forced rotation (to be applied _last_)
int no_enhancement; // if true, discard enhancement layer
#if WEBP_DECODER_ABI_VERSION < 0x0203
uint32_t pad[5]; // padding for later use
#elif WEBP_DECODER_ABI_VERSION < 0x0204
uint32_t pad[4]; // padding for later use
#else
uint32_t pad[3]; // padding for later use
#endif
};
// Main object storing the configuration for advanced decoding.
+148 -14
View File
@@ -48,13 +48,14 @@
#ifndef WEBP_WEBP_DEMUX_H_
#define WEBP_WEBP_DEMUX_H_
#include "./decode.h" // for WEBP_CSP_MODE
#include "./mux_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WEBP_DEMUX_ABI_VERSION 0x0101 // MAJOR(8b) + MINOR(8b)
#define WEBP_DEMUX_ABI_VERSION 0x0107 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
@@ -63,6 +64,8 @@ extern "C" {
typedef struct WebPDemuxer WebPDemuxer;
typedef struct WebPIterator WebPIterator;
typedef struct WebPChunkIterator WebPChunkIterator;
typedef struct WebPAnimInfo WebPAnimInfo;
typedef struct WebPAnimDecoderOptions WebPAnimDecoderOptions;
//------------------------------------------------------------------------------
@@ -85,7 +88,8 @@ typedef enum WebPDemuxState {
WEBP_EXTERN(WebPDemuxer*) WebPDemuxInternal(
const WebPData*, int, WebPDemuxState*, int);
// Parses the full WebP file given by 'data'.
// Parses the full WebP file given by 'data'. For single images the WebP file
// header alone or the file header and the chunk header may be absent.
// Returns a WebPDemuxer object on successful parse, NULL otherwise.
static WEBP_INLINE WebPDemuxer* WebPDemux(const WebPData* data) {
return WebPDemuxInternal(data, 0, NULL, WEBP_DEMUX_ABI_VERSION);
@@ -134,17 +138,15 @@ WEBP_EXTERN(uint32_t) WebPDemuxGetI(
struct WebPIterator {
int frame_num;
int num_frames; // equivalent to WEBP_FF_FRAME_COUNT.
int fragment_num;
int num_fragments;
int x_offset, y_offset; // offset relative to the canvas.
int width, height; // dimensions of this frame or fragment.
int width, height; // dimensions of this frame.
int duration; // display duration in milliseconds.
WebPMuxAnimDispose dispose_method; // dispose method for the frame.
int complete; // true if 'fragment' contains a full frame. partial images
// may still be decoded with the WebP incremental decoder.
WebPData fragment; // The frame or fragment given by 'frame_num' and
// 'fragment_num'.
int has_alpha; // True if the frame or fragment contains transparency.
WebPData fragment; // The frame given by 'frame_num'. Note for historical
// reasons this is called a fragment.
int has_alpha; // True if the frame contains transparency.
WebPMuxAnimBlend blend_method; // Blend operation for the frame.
uint32_t pad[2]; // padding for later use.
@@ -152,8 +154,7 @@ struct WebPIterator {
};
// Retrieves frame 'frame_number' from 'dmux'.
// 'iter->fragment' points to the first fragment on return from this function.
// Individual fragments may be extracted using WebPDemuxSelectFragment().
// 'iter->fragment' points to the frame on return from this function.
// Setting 'frame_number' equal to 0 will return the last frame of the image.
// Returns false if 'dmux' is NULL or frame 'frame_number' is not present.
// Call WebPDemuxReleaseIterator() when use of the iterator is complete.
@@ -167,10 +168,6 @@ WEBP_EXTERN(int) WebPDemuxGetFrame(
WEBP_EXTERN(int) WebPDemuxNextFrame(WebPIterator* iter);
WEBP_EXTERN(int) WebPDemuxPrevFrame(WebPIterator* iter);
// Sets 'iter->fragment' to reflect fragment number 'fragment_num'.
// Returns true if fragment 'fragment_num' is present, false otherwise.
WEBP_EXTERN(int) WebPDemuxSelectFragment(WebPIterator* iter, int fragment_num);
// Releases any memory associated with 'iter'.
// Must be called before any subsequent calls to WebPDemuxGetChunk() on the same
// iter. Also, must be called before destroying the associated WebPDemuxer with
@@ -216,6 +213,143 @@ WEBP_EXTERN(int) WebPDemuxPrevChunk(WebPChunkIterator* iter);
WEBP_EXTERN(void) WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter);
//------------------------------------------------------------------------------
// WebPAnimDecoder API
//
// This API allows decoding (possibly) animated WebP images.
//
// Code Example:
/*
WebPAnimDecoderOptions dec_options;
WebPAnimDecoderOptionsInit(&dec_options);
// Tune 'dec_options' as needed.
WebPAnimDecoder* dec = WebPAnimDecoderNew(webp_data, &dec_options);
WebPAnimInfo anim_info;
WebPAnimDecoderGetInfo(dec, &anim_info);
for (uint32_t i = 0; i < anim_info.loop_count; ++i) {
while (WebPAnimDecoderHasMoreFrames(dec)) {
uint8_t* buf;
int timestamp;
WebPAnimDecoderGetNext(dec, &buf, &timestamp);
// ... (Render 'buf' based on 'timestamp').
// ... (Do NOT free 'buf', as it is owned by 'dec').
}
WebPAnimDecoderReset(dec);
}
const WebPDemuxer* demuxer = WebPAnimDecoderGetDemuxer(dec);
// ... (Do something using 'demuxer'; e.g. get EXIF/XMP/ICC data).
WebPAnimDecoderDelete(dec);
*/
typedef struct WebPAnimDecoder WebPAnimDecoder; // Main opaque object.
// Global options.
struct WebPAnimDecoderOptions {
// Output colorspace. Only the following modes are supported:
// MODE_RGBA, MODE_BGRA, MODE_rgbA and MODE_bgrA.
WEBP_CSP_MODE color_mode;
int use_threads; // If true, use multi-threaded decoding.
uint32_t padding[7]; // Padding for later use.
};
// Internal, version-checked, entry point.
WEBP_EXTERN(int) WebPAnimDecoderOptionsInitInternal(
WebPAnimDecoderOptions*, int);
// Should always be called, to initialize a fresh WebPAnimDecoderOptions
// structure before modification. Returns false in case of version mismatch.
// WebPAnimDecoderOptionsInit() must have succeeded before using the
// 'dec_options' object.
static WEBP_INLINE int WebPAnimDecoderOptionsInit(
WebPAnimDecoderOptions* dec_options) {
return WebPAnimDecoderOptionsInitInternal(dec_options,
WEBP_DEMUX_ABI_VERSION);
}
// Internal, version-checked, entry point.
WEBP_EXTERN(WebPAnimDecoder*) WebPAnimDecoderNewInternal(
const WebPData*, const WebPAnimDecoderOptions*, int);
// Creates and initializes a WebPAnimDecoder object.
// Parameters:
// webp_data - (in) WebP bitstream. This should remain unchanged during the
// lifetime of the output WebPAnimDecoder object.
// dec_options - (in) decoding options. Can be passed NULL to choose
// reasonable defaults (in particular, color mode MODE_RGBA
// will be picked).
// Returns:
// A pointer to the newly created WebPAnimDecoder object, or NULL in case of
// parsing error, invalid option or memory error.
static WEBP_INLINE WebPAnimDecoder* WebPAnimDecoderNew(
const WebPData* webp_data, const WebPAnimDecoderOptions* dec_options) {
return WebPAnimDecoderNewInternal(webp_data, dec_options,
WEBP_DEMUX_ABI_VERSION);
}
// Global information about the animation..
struct WebPAnimInfo {
uint32_t canvas_width;
uint32_t canvas_height;
uint32_t loop_count;
uint32_t bgcolor;
uint32_t frame_count;
uint32_t pad[4]; // padding for later use
};
// Get global information about the animation.
// Parameters:
// dec - (in) decoder instance to get information from.
// info - (out) global information fetched from the animation.
// Returns:
// True on success.
WEBP_EXTERN(int) WebPAnimDecoderGetInfo(const WebPAnimDecoder* dec,
WebPAnimInfo* info);
// Fetch the next frame from 'dec' based on options supplied to
// WebPAnimDecoderNew(). This will be a fully reconstructed canvas of size
// 'canvas_width * 4 * canvas_height', and not just the frame sub-rectangle. The
// returned buffer 'buf' is valid only until the next call to
// WebPAnimDecoderGetNext(), WebPAnimDecoderReset() or WebPAnimDecoderDelete().
// Parameters:
// dec - (in/out) decoder instance from which the next frame is to be fetched.
// buf - (out) decoded frame.
// timestamp - (out) timestamp of the frame in milliseconds.
// Returns:
// False if any of the arguments are NULL, or if there is a parsing or
// decoding error, or if there are no more frames. Otherwise, returns true.
WEBP_EXTERN(int) WebPAnimDecoderGetNext(WebPAnimDecoder* dec,
uint8_t** buf, int* timestamp);
// Check if there are more frames left to decode.
// Parameters:
// dec - (in) decoder instance to be checked.
// Returns:
// True if 'dec' is not NULL and some frames are yet to be decoded.
// Otherwise, returns false.
WEBP_EXTERN(int) WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder* dec);
// Resets the WebPAnimDecoder object, so that next call to
// WebPAnimDecoderGetNext() will restart decoding from 1st frame. This would be
// helpful when all frames need to be decoded multiple times (e.g.
// info.loop_count times) without destroying and recreating the 'dec' object.
// Parameters:
// dec - (in/out) decoder instance to be reset
WEBP_EXTERN(void) WebPAnimDecoderReset(WebPAnimDecoder* dec);
// Grab the internal demuxer object.
// Getting the demuxer object can be useful if one wants to use operations only
// available through demuxer; e.g. to get XMP/EXIF/ICC metadata. The returned
// demuxer object is owned by 'dec' and is valid only until the next call to
// WebPAnimDecoderDelete().
//
// Parameters:
// dec - (in) decoder instance from which the demuxer object is to be fetched.
WEBP_EXTERN(const WebPDemuxer*) WebPAnimDecoderGetDemuxer(
const WebPAnimDecoder* dec);
// Deletes the WebPAnimDecoder object.
// Parameters:
// dec - (in/out) decoder instance to be deleted
WEBP_EXTERN(void) WebPAnimDecoderDelete(WebPAnimDecoder* dec);
#ifdef __cplusplus
} // extern "C"
+23 -16
View File
@@ -20,7 +20,7 @@
extern "C" {
#endif
#define WEBP_ENCODER_ABI_VERSION 0x0202 // MAJOR(8b) + MINOR(8b)
#define WEBP_ENCODER_ABI_VERSION 0x0209 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
@@ -42,7 +42,7 @@ WEBP_EXTERN(int) WebPGetEncoderVersion(void);
// Returns the size of the compressed data (pointed to by *output), or 0 if
// an error occurred. The compressed data must be released by the caller
// using the call 'free(*output)'.
// using the call 'WebPFree(*output)'.
// These functions compress using the lossy format, and the quality_factor
// can go from 0 (smaller output, lower quality) to 100 (best quality,
// larger output).
@@ -75,6 +75,9 @@ WEBP_EXTERN(size_t) WebPEncodeLosslessBGRA(const uint8_t* bgra,
int width, int height, int stride,
uint8_t** output);
// Releases memory returned by the WebPEncode*() functions above.
WEBP_EXTERN(void) WebPFree(void* ptr);
//------------------------------------------------------------------------------
// Coding parameters
@@ -131,7 +134,19 @@ struct WebPConfig {
int thread_level; // If non-zero, try and use multi-threaded encoding.
int low_memory; // If set, reduce memory usage (but increase CPU use).
uint32_t pad[5]; // padding for later use
int near_lossless; // Near lossless encoding [0 = off(default) .. 100].
// This feature is experimental.
int exact; // if non-zero, preserve the exact RGB values under
// transparent area. Otherwise, discard this invisible
// RGB information for better compression. The default
// value is 0.
#ifdef WEBP_EXPERIMENTAL_FEATURES
int delta_palettization;
uint32_t pad[2]; // padding for later use
#else
uint32_t pad[3]; // padding for later use
#endif // WEBP_EXPERIMENTAL_FEATURES
};
// Enumerate some predefined settings for WebPConfig, depending on the type
@@ -167,7 +182,6 @@ static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
WEBP_ENCODER_ABI_VERSION);
}
#if WEBP_ENCODER_ABI_VERSION > 0x0202
// Activate the lossless compression mode with the desired efficiency level
// between 0 (fastest, lowest compression) and 9 (slower, best compression).
// A good default level is '6', providing a fair tradeoff between compression
@@ -175,7 +189,6 @@ static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
// This function will overwrite several fields from config: 'method', 'quality'
// and 'lossless'. Returns false in case of parameter error.
WEBP_EXTERN(int) WebPConfigLosslessPreset(WebPConfig* config, int level);
#endif
// Returns true if 'config' is non-NULL and all configuration parameters are
// within their valid ranges.
@@ -209,8 +222,10 @@ struct WebPAuxStats {
int cache_bits; // number of bits for color cache lookup
int palette_size; // number of color in palette, if used
int lossless_size; // final lossless size
int lossless_hdr_size; // lossless header (transform, huffman etc) size
int lossless_data_size; // lossless image data size
uint32_t pad[4]; // padding for later use
uint32_t pad[2]; // padding for later use
};
// Signature for output function. Should return true if writing was successful.
@@ -231,18 +246,12 @@ struct WebPMemoryWriter {
// The following must be called first before any use.
WEBP_EXTERN(void) WebPMemoryWriterInit(WebPMemoryWriter* writer);
#if WEBP_ENCODER_ABI_VERSION > 0x0203
// The following must be called to deallocate writer->mem memory. The 'writer'
// object itself is not deallocated.
WEBP_EXTERN(void) WebPMemoryWriterClear(WebPMemoryWriter* writer);
#endif
// The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon
// completion, writer.mem and writer.size will hold the coded data.
#if WEBP_ENCODER_ABI_VERSION > 0x0203
// writer.mem must be freed by calling WebPMemoryWriterClear.
#else
// writer.mem must be freed by calling 'free(writer.mem)'.
#endif
WEBP_EXTERN(int) WebPMemoryWrite(const uint8_t* data, size_t data_size,
const WebPPicture* picture);
@@ -379,8 +388,8 @@ WEBP_EXTERN(void) WebPPictureFree(WebPPicture* picture);
// Returns false in case of memory allocation error.
WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* src, WebPPicture* dst);
// Compute PSNR, SSIM or LSIM distortion metric between two pictures.
// Result is in dB, stores in result[] in the Y/U/V/Alpha/All order.
// Compute PSNR, SSIM or LSIM distortion metric between two pictures. Results
// are in dB, stored in result[] in the Y/U/V/Alpha/All or B/G/R/A/All order.
// Returns false in case of error (src and ref don't have same dimension, ...)
// Warning: this function is rather CPU-intensive.
WEBP_EXTERN(int) WebPPictureDistortion(
@@ -464,14 +473,12 @@ WEBP_EXTERN(int) WebPPictureARGBToYUVA(WebPPicture* picture,
WEBP_EXTERN(int) WebPPictureARGBToYUVADithered(
WebPPicture* picture, WebPEncCSP colorspace, float dithering);
#if WEBP_ENCODER_ABI_VERSION > 0x0204
// Performs 'smart' RGBA->YUVA420 downsampling and colorspace conversion.
// Downsampling is handled with extra care in case of color clipping. This
// method is roughly 2x slower than WebPPictureARGBToYUVA() but produces better
// YUV representation.
// Returns false in case of error.
WEBP_EXTERN(int) WebPPictureSmartARGBToYUVA(WebPPicture* picture);
#endif
// Converts picture->yuv to picture->argb and sets picture->use_argb to true.
// The input format must be YUV_420 or YUV_420A.
+51
View File
@@ -0,0 +1,51 @@
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
#ifndef WEBP_WEBP_EXTRAS_H_
#define WEBP_WEBP_EXTRAS_H_
#include "./types.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "./encode.h"
#define WEBP_EXTRAS_ABI_VERSION 0x0000 // MAJOR(8b) + MINOR(8b)
//------------------------------------------------------------------------------
// Returns the version number of the extras library, packed in hexadecimal using
// 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
WEBP_EXTERN(int) WebPGetExtrasVersion(void);
//------------------------------------------------------------------------------
// Ad-hoc colorspace importers.
// Import luma sample (gray scale image) into 'picture'. The 'picture'
// width and height must be set prior to calling this function.
WEBP_EXTERN(int) WebPImportGray(const uint8_t* gray, WebPPicture* picture);
// Import rgb sample in RGB565 packed format into 'picture'. The 'picture'
// width and height must be set prior to calling this function.
WEBP_EXTERN(int) WebPImportRGB565(const uint8_t* rgb565, WebPPicture* pic);
// Import rgb sample in RGB4444 packed format into 'picture'. The 'picture'
// width and height must be set prior to calling this function.
WEBP_EXTERN(int) WebPImportRGB4444(const uint8_t* rgb4444, WebPPicture* pic);
//------------------------------------------------------------------------------
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* WEBP_WEBP_EXTRAS_H_ */
+1 -1
View File
@@ -15,7 +15,7 @@
#define WEBP_WEBP_FORMAT_CONSTANTS_H_
// Create fourcc of the chunk from the chunk tag characters.
#define MKFOURCC(a, b, c, d) ((uint32_t)(a) | (b) << 8 | (c) << 16 | (d) << 24)
#define MKFOURCC(a, b, c, d) ((a) | (b) << 8 | (c) << 16 | (uint32_t)(d) << 24)
// VP8 related constants.
#define VP8_SIGNATURE 0x9d012a // Signature in VP8 data.
+145 -14
View File
@@ -7,11 +7,25 @@
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// RIFF container manipulation for WebP images.
// RIFF container manipulation and encoding for WebP images.
//
// Authors: Urvang (urvang@google.com)
// Vikas (vikasa@google.com)
#ifndef WEBP_WEBP_MUX_H_
#define WEBP_WEBP_MUX_H_
#include "./mux_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WEBP_MUX_ABI_VERSION 0x0106 // MAJOR(8b) + MINOR(8b)
//------------------------------------------------------------------------------
// Mux API
//
// This API allows manipulation of WebP container images containing features
// like color profile, metadata, animation and fragmented images.
//
@@ -46,17 +60,6 @@
free(data);
*/
#ifndef WEBP_WEBP_MUX_H_
#define WEBP_WEBP_MUX_H_
#include "./mux_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WEBP_MUX_ABI_VERSION 0x0101 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
// typedef enum WebPMuxError WebPMuxError;
@@ -64,6 +67,7 @@ extern "C" {
typedef struct WebPMux WebPMux; // main opaque object.
typedef struct WebPMuxFrameInfo WebPMuxFrameInfo;
typedef struct WebPMuxAnimParams WebPMuxAnimParams;
typedef struct WebPAnimEncoderOptions WebPAnimEncoderOptions;
// Error codes
typedef enum WebPMuxError {
@@ -310,7 +314,6 @@ WEBP_EXTERN(WebPMuxError) WebPMuxGetAnimationParams(
//------------------------------------------------------------------------------
// Misc Utilities.
#if WEBP_MUX_ABI_VERSION > 0x0101
// Sets the canvas size for the mux object. The width and height can be
// specified explicitly or left as zero (0, 0).
// * When width and height are specified explicitly, then this frame bound is
@@ -328,7 +331,6 @@ WEBP_EXTERN(WebPMuxError) WebPMuxGetAnimationParams(
// WEBP_MUX_OK - on success.
WEBP_EXTERN(WebPMuxError) WebPMuxSetCanvasSize(WebPMux* mux,
int width, int height);
#endif
// Gets the canvas size from the mux object.
// Note: This method assumes that the VP8X chunk, if present, is up-to-date.
@@ -390,6 +392,135 @@ WEBP_EXTERN(WebPMuxError) WebPMuxNumChunks(const WebPMux* mux,
WEBP_EXTERN(WebPMuxError) WebPMuxAssemble(WebPMux* mux,
WebPData* assembled_data);
//------------------------------------------------------------------------------
// WebPAnimEncoder API
//
// This API allows encoding (possibly) animated WebP images.
//
// Code Example:
/*
WebPAnimEncoderOptions enc_options;
WebPAnimEncoderOptionsInit(&enc_options);
// Tune 'enc_options' as needed.
WebPAnimEncoder* enc = WebPAnimEncoderNew(width, height, &enc_options);
while(<there are more frames>) {
WebPConfig config;
WebPConfigInit(&config);
// Tune 'config' as needed.
WebPAnimEncoderAdd(enc, frame, timestamp_ms, &config);
}
WebPAnimEncoderAdd(enc, NULL, timestamp_ms, NULL);
WebPAnimEncoderAssemble(enc, webp_data);
WebPAnimEncoderDelete(enc);
// Write the 'webp_data' to a file, or re-mux it further.
*/
typedef struct WebPAnimEncoder WebPAnimEncoder; // Main opaque object.
// Forward declarations. Defined in encode.h.
struct WebPPicture;
struct WebPConfig;
// Global options.
struct WebPAnimEncoderOptions {
WebPMuxAnimParams anim_params; // Animation parameters.
int minimize_size; // If true, minimize the output size (slow). Implicitly
// disables key-frame insertion.
int kmin;
int kmax; // Minimum and maximum distance between consecutive key
// frames in the output. The library may insert some key
// frames as needed to satisfy this criteria.
// Note that these conditions should hold: kmax > kmin
// and kmin >= kmax / 2 + 1. Also, if kmin == 0, then
// key-frame insertion is disabled; and if kmax == 0,
// then all frames will be key-frames.
int allow_mixed; // If true, use mixed compression mode; may choose
// either lossy and lossless for each frame.
int verbose; // If true, print info and warning messages to stderr.
uint32_t padding[4]; // Padding for later use.
};
// Internal, version-checked, entry point.
WEBP_EXTERN(int) WebPAnimEncoderOptionsInitInternal(
WebPAnimEncoderOptions*, int);
// Should always be called, to initialize a fresh WebPAnimEncoderOptions
// structure before modification. Returns false in case of version mismatch.
// WebPAnimEncoderOptionsInit() must have succeeded before using the
// 'enc_options' object.
static WEBP_INLINE int WebPAnimEncoderOptionsInit(
WebPAnimEncoderOptions* enc_options) {
return WebPAnimEncoderOptionsInitInternal(enc_options, WEBP_MUX_ABI_VERSION);
}
// Internal, version-checked, entry point.
WEBP_EXTERN(WebPAnimEncoder*) WebPAnimEncoderNewInternal(
int, int, const WebPAnimEncoderOptions*, int);
// Creates and initializes a WebPAnimEncoder object.
// Parameters:
// width/height - (in) canvas width and height of the animation.
// enc_options - (in) encoding options; can be passed NULL to pick
// reasonable defaults.
// Returns:
// A pointer to the newly created WebPAnimEncoder object.
// Or NULL in case of memory error.
static WEBP_INLINE WebPAnimEncoder* WebPAnimEncoderNew(
int width, int height, const WebPAnimEncoderOptions* enc_options) {
return WebPAnimEncoderNewInternal(width, height, enc_options,
WEBP_MUX_ABI_VERSION);
}
// Optimize the given frame for WebP, encode it and add it to the
// WebPAnimEncoder object.
// The last call to 'WebPAnimEncoderAdd' should be with frame = NULL, which
// indicates that no more frames are to be added. This call is also used to
// determine the duration of the last frame.
// Parameters:
// enc - (in/out) object to which the frame is to be added.
// frame - (in/out) frame data in ARGB or YUV(A) format. If it is in YUV(A)
// format, it will be converted to ARGB, which incurs a small loss.
// timestamp_ms - (in) timestamp of this frame in milliseconds.
// Duration of a frame would be calculated as
// "timestamp of next frame - timestamp of this frame".
// Hence, timestamps should be in non-decreasing order.
// config - (in) encoding options; can be passed NULL to pick
// reasonable defaults.
// Returns:
// On error, returns false and frame->error_code is set appropriately.
// Otherwise, returns true.
WEBP_EXTERN(int) WebPAnimEncoderAdd(
WebPAnimEncoder* enc, struct WebPPicture* frame, int timestamp_ms,
const struct WebPConfig* config);
// Assemble all frames added so far into a WebP bitstream.
// This call should be preceded by a call to 'WebPAnimEncoderAdd' with
// frame = NULL; if not, the duration of the last frame will be internally
// estimated.
// Parameters:
// enc - (in/out) object from which the frames are to be assembled.
// webp_data - (out) generated WebP bitstream.
// Returns:
// True on success.
WEBP_EXTERN(int) WebPAnimEncoderAssemble(WebPAnimEncoder* enc,
WebPData* webp_data);
// Get error string corresponding to the most recent call using 'enc'. The
// returned string is owned by 'enc' and is valid only until the next call to
// WebPAnimEncoderAdd() or WebPAnimEncoderAssemble() or WebPAnimEncoderDelete().
// Parameters:
// enc - (in/out) object from which the error string is to be fetched.
// Returns:
// NULL if 'enc' is NULL. Otherwise, returns the error string if the last call
// to 'enc' had an error, or an empty string if the last call was a success.
WEBP_EXTERN(const char*) WebPAnimEncoderGetError(WebPAnimEncoder* enc);
// Deletes the WebPAnimEncoder object.
// Parameters:
// enc - (in/out) object to be deleted
WEBP_EXTERN(void) WebPAnimEncoderDelete(WebPAnimEncoder* enc);
//------------------------------------------------------------------------------
#ifdef __cplusplus
+5 -1
View File
@@ -39,7 +39,11 @@ typedef long long int int64_t;
#ifndef WEBP_EXTERN
// This explicitly marks library functions and allows for changing the
// signature for e.g., Windows DLL builds.
#define WEBP_EXTERN(type) extern type
# if defined(__GNUC__) && __GNUC__ >= 4
# define WEBP_EXTERN(type) extern __attribute__ ((visibility ("default"))) type
# else
# define WEBP_EXTERN(type) extern type
# endif /* __GNUC__ >= 4 */
#endif /* WEBP_EXTERN */
// Macro to check ABI compatibility (same major revision number)
BIN
View File
Binary file not shown.
+12 -4
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = 'YYImage'
s.summary = 'Image framework for iOS to display/encode/decode animated WebP, APNG, GIF, and more.'
s.version = '0.9.2'
s.version = '0.9.4'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.authors = { 'ibireme' => 'ibireme@gmail.com' }
s.social_media_url = 'http://blog.ibireme.com'
@@ -11,11 +11,19 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/ibireme/YYImage.git', :tag => s.version.to_s }
s.requires_arc = true
s.source_files = 'YYImage/*.{h,m}'
s.public_header_files = 'YYImage/*.{h}'
s.default_subspec = 'Core'
s.libraries = 'z'
s.frameworks = 'UIKit', 'CoreFoundation', 'QuartzCore', 'AssetsLibrary', 'ImageIO', 'Accelerate', 'MobileCoreServices'
s.ios.vendored_frameworks = 'Vendor/WebP.framework'
s.subspec 'Core' do |core|
core.source_files = 'YYImage/*.{h,m}'
core.public_header_files = 'YYImage/*.{h}'
end
s.subspec 'WebP' do |webp|
webp.dependency 'YYImage/Core'
webp.ios.vendored_frameworks = 'Vendor/WebP.framework'
end
end
+8 -4
View File
@@ -11,6 +11,8 @@
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
An image view for displaying animated image.
@@ -38,7 +40,7 @@
The default value is `YES`.
*/
@property (nonatomic, assign) BOOL autoPlayAnimatedImage;
@property (nonatomic) BOOL autoPlayAnimatedImage;
/**
Index of the currently displayed frame (index from 0).
@@ -48,7 +50,7 @@
You can add an observer to this property to observe the playing status.
*/
@property (nonatomic, assign) NSUInteger currentAnimatedImageIndex;
@property (nonatomic) NSUInteger currentAnimatedImageIndex;
/**
Whether the image view is playing animation currently.
@@ -76,7 +78,7 @@
When receive memory warning or app enter background, the buffer will be released
immediately, and may grow back at the right time.
*/
@property (nonatomic, assign) NSUInteger maxBufferSize;
@property (nonatomic) NSUInteger maxBufferSize;
@end
@@ -107,7 +109,7 @@
/// Returns the frame image from a specified index.
/// This method may be called on background thread.
/// @param index Frame index (zero based).
- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index;
- (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index;
/// Returns the frames's duration from a specified index.
/// @param index Frame index (zero based).
@@ -119,3 +121,5 @@
/// It may used to display sprite animation with a single image (sprite sheet).
- (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index;
@end
NS_ASSUME_NONNULL_END
+61 -49
View File
@@ -12,19 +12,18 @@
#import "YYAnimatedImageView.h"
#import "YYImageCoder.h"
#import <pthread.h>
#import <libkern/OSAtomic.h>
#import <mach/mach.h>
#define BUFFER_SIZE (10 * 1024 * 1024) // 10MB (minimum memory buffer size)
#define LOCK(...) OSSpinLockLock(&self->_lock); \
#define LOCK(...) dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER); \
__VA_ARGS__; \
OSSpinLockUnlock(&self->_lock);
dispatch_semaphore_signal(self->_lock);
#define LOCK_VIEW(...) OSSpinLockLock(&view->_lock); \
#define LOCK_VIEW(...) dispatch_semaphore_wait(view->_lock, DISPATCH_TIME_FOREVER); \
__VA_ARGS__; \
OSSpinLockUnlock(&view->_lock);
dispatch_semaphore_signal(view->_lock);
static int64_t _YYDeviceMemoryTotal() {
@@ -113,12 +112,12 @@ static int64_t _YYDeviceMemoryFree() {
typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
YYAnimagedImageTypeNone = 0,
YYAnimagedImageTypeImage,
YYAnimagedImageTypeHighlightedImage,
YYAnimagedImageTypeImages,
YYAnimagedImageTypeHighlightedImages,
typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
YYAnimatedImageTypeNone = 0,
YYAnimatedImageTypeImage,
YYAnimatedImageTypeHighlightedImage,
YYAnimatedImageTypeImages,
YYAnimatedImageTypeHighlightedImages,
};
@interface YYAnimatedImageView() {
@@ -126,7 +125,7 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
UIImage <YYAnimatedImage> *_curAnimatedImage;
dispatch_once_t _onceToken;
OSSpinLock _lock; ///< lock for _buffer
dispatch_semaphore_t _lock; ///< lock for _buffer
NSOperationQueue *_requestQueue; ///< image request queue, serial
CADisplayLink *_link; ///< ticker for change frame
@@ -136,7 +135,7 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
NSUInteger _curIndex; ///< current frame index (from 0)
NSUInteger _totalFrameCount; ///< total frame count
BOOL _loopEnd; ///< weather the loop is end.
BOOL _loopEnd; ///< whether the loop is end.
NSUInteger _curLoop; ///< current loop count (from 0)
NSUInteger _totalLoop; ///< total loop count, 0 means infinity
@@ -166,22 +165,28 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
if ([self isCancelled]) return;
view->_incrBufferCount++;
if (view->_incrBufferCount == 0) [view calcMaxBufferCount];
if ((int)view->_incrBufferCount > (int)view->_maxBufferCount) {
if (view->_incrBufferCount > (NSInteger)view->_maxBufferCount) {
view->_incrBufferCount = view->_maxBufferCount;
}
NSUInteger idx = _nextIndex;
NSUInteger max = view->_incrBufferCount < 1 ? 1 : view->_incrBufferCount;
NSUInteger total = view->_totalFrameCount;
view = nil;
for (int i = 0; i < max; i++, idx++) {
@autoreleasepool {
if (idx >= total) idx = 0;
if ([self isCancelled]) break;
__strong YYAnimatedImageView *view = _view;
if (!view) break;
LOCK_VIEW(BOOL miss = (view->_buffer[@(idx)] == nil));
if (miss) {
UIImage *img = [_curImage animatedImageFrameAtIndex:idx];
img = [img yy_imageByDecoded];
img = img.yy_imageByDecoded;
if ([self isCancelled]) break;
LOCK_VIEW(view->_buffer[@(idx)] = img ? img : [NSNull null]);
view = nil;
}
}
}
@@ -227,7 +232,7 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
// init the animated params.
- (void)resetAnimated {
dispatch_once(&_onceToken, ^{
_lock = OS_SPINLOCK_INIT;
_lock = dispatch_semaphore_create(1);
_buffer = [NSMutableDictionary new];
_requestQueue = [[NSOperationQueue alloc] init];
_requestQueue.maxConcurrentOperationCount = 1;
@@ -272,22 +277,22 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
- (void)setImage:(UIImage *)image {
if (self.image == image) return;
[self setImage:image withType:YYAnimagedImageTypeImage];
[self setImage:image withType:YYAnimatedImageTypeImage];
}
- (void)setHighlightedImage:(UIImage *)highlightedImage {
if (self.highlightedImage == highlightedImage) return;
[self setImage:highlightedImage withType:YYAnimagedImageTypeHighlightedImage];
[self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage];
}
- (void)setAnimationImages:(NSArray *)animationImages {
if (self.animationImages == animationImages) return;
[self setImage:animationImages withType:YYAnimagedImageTypeImages];
[self setImage:animationImages withType:YYAnimatedImageTypeImages];
}
- (void)setHighlightedAnimationImages:(NSArray *)highlightedAnimationImages {
if (self.highlightedAnimationImages == highlightedAnimationImages) return;
[self setImage:highlightedAnimationImages withType:YYAnimagedImageTypeHighlightedImages];
[self setImage:highlightedAnimationImages withType:YYAnimatedImageTypeHighlightedImages];
}
- (void)setHighlighted:(BOOL)highlighted {
@@ -296,46 +301,46 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
[self imageChanged];
}
- (id)imageForType:(YYAnimagedImageType)type {
- (id)imageForType:(YYAnimatedImageType)type {
switch (type) {
case YYAnimagedImageTypeNone: return nil;
case YYAnimagedImageTypeImage: return self.image;
case YYAnimagedImageTypeHighlightedImage: return self.highlightedImage;
case YYAnimagedImageTypeImages: return self.animationImages;
case YYAnimagedImageTypeHighlightedImages: return self.highlightedAnimationImages;
case YYAnimatedImageTypeNone: return nil;
case YYAnimatedImageTypeImage: return self.image;
case YYAnimatedImageTypeHighlightedImage: return self.highlightedImage;
case YYAnimatedImageTypeImages: return self.animationImages;
case YYAnimatedImageTypeHighlightedImages: return self.highlightedAnimationImages;
}
return nil;
}
- (YYAnimagedImageType)currentImageType {
YYAnimagedImageType curType = YYAnimagedImageTypeNone;
- (YYAnimatedImageType)currentImageType {
YYAnimatedImageType curType = YYAnimatedImageTypeNone;
if (self.highlighted) {
if (self.highlightedAnimationImages.count) curType = YYAnimagedImageTypeHighlightedImages;
else if (self.highlightedImage) curType = YYAnimagedImageTypeHighlightedImage;
if (self.highlightedAnimationImages.count) curType = YYAnimatedImageTypeHighlightedImages;
else if (self.highlightedImage) curType = YYAnimatedImageTypeHighlightedImage;
}
if (curType == YYAnimagedImageTypeNone) {
if (self.animationImages.count) curType = YYAnimagedImageTypeImages;
else if (self.image) curType = YYAnimagedImageTypeImage;
if (curType == YYAnimatedImageTypeNone) {
if (self.animationImages.count) curType = YYAnimatedImageTypeImages;
else if (self.image) curType = YYAnimatedImageTypeImage;
}
return curType;
}
- (void)setImage:(id)image withType:(YYAnimagedImageType)type {
- (void)setImage:(id)image withType:(YYAnimatedImageType)type {
[self stopAnimating];
if (_link) [self resetAnimated];
_curFrame = nil;
switch (type) {
case YYAnimagedImageTypeNone: break;
case YYAnimagedImageTypeImage: super.image = image; break;
case YYAnimagedImageTypeHighlightedImage: super.highlightedImage = image; break;
case YYAnimagedImageTypeImages: super.animationImages = image; break;
case YYAnimagedImageTypeHighlightedImages: super.highlightedAnimationImages = image; break;
case YYAnimatedImageTypeNone: break;
case YYAnimatedImageTypeImage: super.image = image; break;
case YYAnimatedImageTypeHighlightedImage: super.highlightedImage = image; break;
case YYAnimatedImageTypeImages: super.animationImages = image; break;
case YYAnimatedImageTypeHighlightedImages: super.highlightedAnimationImages = image; break;
}
[self imageChanged];
}
- (void)imageChanged {
YYAnimagedImageType newType = [self currentImageType];
YYAnimatedImageType newType = [self currentImageType];
id newVisibleImage = [self imageForType:newType];
NSUInteger newImageFrameCount = 0;
BOOL hasContentsRect = NO;
@@ -374,16 +379,18 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
// dynamically adjust buffer size for current memory.
- (void)calcMaxBufferCount {
NSUInteger bytes = _curAnimatedImage.animatedImageBytesPerFrame;
if (bytes == 0) bytes = 1;
int64_t bytes = (int64_t)_curAnimatedImage.animatedImageBytesPerFrame;
if (bytes == 0) bytes = 1024;
int64_t total = _YYDeviceMemoryTotal();
int64_t free = _YYDeviceMemoryFree();
int64_t max = MIN(total * 0.2, free * 0.6);
max = MAX(max, BUFFER_SIZE);
if (_maxBufferSize) max = max > _maxBufferSize ? _maxBufferSize : max;
_maxBufferCount = (float)max / (float)bytes;
if (_maxBufferCount == 0) _maxBufferCount = 1;
double maxBufferCount = (double)max / (double)bytes;
if (maxBufferCount < 1) maxBufferCount = 1;
else if (maxBufferCount > 512) maxBufferCount = 512;
_maxBufferCount = maxBufferCount;
}
- (void)dealloc {
@@ -399,13 +406,14 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
- (void)stopAnimating {
[super stopAnimating];
[_requestQueue cancelAllOperations];
_link.paused = YES;
self.currentIsPlayingAnimation = NO;
}
- (void)startAnimating {
YYAnimagedImageType type = [self currentImageType];
if (type == YYAnimagedImageTypeImages || type == YYAnimagedImageTypeHighlightedImages) {
YYAnimatedImageType type = [self currentImageType];
if (type == YYAnimatedImageTypeImages || type == YYAnimatedImageTypeHighlightedImages) {
NSArray *images = [self imageForType:type];
if (images.count > 0) {
[super startAnimating];
@@ -627,17 +635,21 @@ typedef NS_ENUM(NSUInteger, YYAnimagedImageType) {
self = [super initWithCoder:aDecoder];
_runloopMode = [aDecoder decodeObjectForKey:@"runloopMode"];
if (_runloopMode.length == 0) _runloopMode = NSRunLoopCommonModes;
_autoPlayAnimatedImage = [aDecoder decodeBoolForKey:@"autoPlayAnimatedImage"];
if ([aDecoder containsValueForKey:@"autoPlayAnimatedImage"]) {
_autoPlayAnimatedImage = [aDecoder decodeBoolForKey:@"autoPlayAnimatedImage"];
} else {
_autoPlayAnimatedImage = YES;
}
UIImage *image = [aDecoder decodeObjectForKey:@"YYAnimatedImage"];
UIImage *highlightedImage = [aDecoder decodeObjectForKey:@"YYHighlightedAnimatedImage"];
if (image) {
self.image = image;
[self setImage:image withType:YYAnimagedImageTypeImage];
[self setImage:image withType:YYAnimatedImageTypeImage];
}
if (highlightedImage) {
self.highlightedImage = highlightedImage;
[self setImage:highlightedImage withType:YYAnimagedImageTypeHighlightedImage];
[self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage];
}
return self;
}
+16 -4
View File
@@ -19,6 +19,8 @@
#import "YYAnimatedImageView.h"
#endif
NS_ASSUME_NONNULL_BEGIN
/**
An image to display frame-based animation.
@@ -49,7 +51,9 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImagePaths:(NSArray *)paths oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths
oneFrameDuration:(NSTimeInterval)oneFrameDuration
loopCount:(NSUInteger)loopCount;
/**
Create a frame animated image from files.
@@ -65,7 +69,9 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImagePaths:(NSArray *)paths frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths
frameDurations:(NSArray<NSNumber *> *)frameDurations
loopCount:(NSUInteger)loopCount;
/**
Create a frame animated image from an array of data.
@@ -78,7 +84,9 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImageDataArray:(NSArray *)dataArray oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray
oneFrameDuration:(NSTimeInterval)oneFrameDuration
loopCount:(NSUInteger)loopCount;
/**
Create a frame animated image from an array of data.
@@ -92,6 +100,10 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImageDataArray:(NSArray *)dataArray frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray
frameDurations:(NSArray *)frameDurations
loopCount:(NSUInteger)loopCount;
@end
NS_ASSUME_NONNULL_END
+9 -7
View File
@@ -30,7 +30,7 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
#import "YYAnimatedImageView.h"
#endif
NS_ASSUME_NONNULL_BEGIN
/**
@@ -53,10 +53,10 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
*/
@interface YYImage : UIImage <YYAnimatedImage>
+ (YYImage *)imageNamed:(NSString *)name; // no cache!
+ (YYImage *)imageWithContentsOfFile:(NSString *)path;
+ (YYImage *)imageWithData:(NSData *)data;
+ (YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale;
+ (nullable YYImage *)imageNamed:(NSString *)name; // no cache!
+ (nullable YYImage *)imageWithContentsOfFile:(NSString *)path;
+ (nullable YYImage *)imageWithData:(NSData *)data;
+ (nullable YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale;
/**
If the image is created from data or file, then the value indicates the data type.
@@ -67,7 +67,7 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
If the image is created from animated image data (multi-frame GIF/APNG/WebP),
this property stores the original image data.
*/
@property (nonatomic, readonly) NSData *animatedImageData;
@property (nullable, nonatomic, readonly) NSData *animatedImageData;
/**
The total memory usage (in bytes) if all frame images was loaded into memory.
@@ -85,6 +85,8 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
See `animatedImageMemorySize` for memory cost.
*/
@property (nonatomic, assign) BOOL preloadAllAnimatedImageFrames;
@property (nonatomic) BOOL preloadAllAnimatedImageFrames;
@end
NS_ASSUME_NONNULL_END
+10 -11
View File
@@ -10,7 +10,6 @@
//
#import "YYImage.h"
#import <libkern/OSAtomic.h>
/**
An array of NSNumber objects, shows the best order for path scale search.
@@ -88,7 +87,7 @@ static CGFloat _NSStringPathScale(NSString *string) {
@implementation YYImage {
YYImageDecoder *_decoder;
NSArray *_preloadedFrames;
OSSpinLock _preloadedLock;
dispatch_semaphore_t _preloadedLock;
NSUInteger _bytesPerFrame;
}
@@ -101,12 +100,12 @@ static CGFloat _NSStringPathScale(NSString *string) {
NSString *path = nil;
CGFloat scale = 1;
// If no extension, guess by system supported (same as UIImage).
NSArray *exts = ext.length > 0 ? @[ext] : @[@"", @"png", @"jpeg", @"jpg", @"gif", @"webp", @"apng"];
NSArray *scales = _NSBundlePreferredScales();
for (int s = 0; s < scales.count; s++) {
scale = ((NSNumber *)scales[s]).floatValue;
NSString *scaledName = _NSStringByAppendingNameScale(res, scale);
// If no extension, guess by system supported (same as UIImage).
NSArray *exts = ext.length > 0 ? @[ext] : @[@"", @"png", @"jpeg", @"jpg", @"gif", @"webp"];
for (NSString *e in exts) {
path = [[NSBundle mainBundle] pathForResource:scaledName ofType:e];
if (path) break;
@@ -145,7 +144,7 @@ static CGFloat _NSStringPathScale(NSString *string) {
- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale {
if (data.length == 0) return nil;
if (scale <= 0) scale = [UIScreen mainScreen].scale;
_preloadedLock = OS_SPINLOCK_INIT;
_preloadedLock = dispatch_semaphore_create(1);
@autoreleasepool {
YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:scale];
YYImageFrame *frame = [decoder frameAtIndex:0 decodeForDisplay:YES];
@@ -180,13 +179,13 @@ static CGFloat _NSStringPathScale(NSString *string) {
[frames addObject:[NSNull null]];
}
}
OSSpinLockLock(&_preloadedLock);
dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER);
_preloadedFrames = frames;
OSSpinLockUnlock(&_preloadedLock);
dispatch_semaphore_signal(_preloadedLock);
} else {
OSSpinLockLock(&_preloadedLock);
dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER);
_preloadedFrames = nil;
OSSpinLockUnlock(&_preloadedLock);
dispatch_semaphore_signal(_preloadedLock);
}
}
}
@@ -229,9 +228,9 @@ static CGFloat _NSStringPathScale(NSString *string) {
- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
if (index >= _decoder.frameCount) return nil;
OSSpinLockLock(&_preloadedLock);
dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER);
UIImage *image = _preloadedFrames[index];
OSSpinLockUnlock(&_preloadedLock);
dispatch_semaphore_signal(_preloadedLock);
if (image) return image == (id)[NSNull null] ? nil : image;
return [_decoder frameAtIndex:index decodeForDisplay:YES].image;
}
+53 -50
View File
@@ -11,6 +11,8 @@
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Image file type.
*/
@@ -76,15 +78,15 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
An image frame object.
*/
@interface YYImageFrame : NSObject <NSCopying>
@property (nonatomic, assign) NSUInteger index; ///< Frame index (zero based)
@property (nonatomic, assign) NSUInteger width; ///< Frame width
@property (nonatomic, assign) NSUInteger height; ///< Frame height
@property (nonatomic, assign) NSUInteger offsetX; ///< Frame origin.x in canvas (left-bottom based)
@property (nonatomic, assign) NSUInteger offsetY; ///< Frame origin.y in canvas (left-bottom based)
@property (nonatomic, assign) NSTimeInterval duration; ///< Frame duration in seconds
@property (nonatomic, assign) YYImageDisposeMethod dispose; ///< Frame dispose method.
@property (nonatomic, assign) YYImageBlendOperation blend; ///< Frame blend operation.
@property (nonatomic, strong) UIImage *image; ///< The image.
@property (nonatomic) NSUInteger index; ///< Frame index (zero based)
@property (nonatomic) NSUInteger width; ///< Frame width
@property (nonatomic) NSUInteger height; ///< Frame height
@property (nonatomic) NSUInteger offsetX; ///< Frame origin.x in canvas (left-bottom based)
@property (nonatomic) NSUInteger offsetY; ///< Frame origin.y in canvas (left-bottom based)
@property (nonatomic) NSTimeInterval duration; ///< Frame duration in seconds
@property (nonatomic) YYImageDisposeMethod dispose; ///< Frame dispose method.
@property (nonatomic) YYImageBlendOperation blend; ///< Frame blend operation.
@property (nullable, nonatomic, strong) UIImage *image; ///< The image.
+ (instancetype)frameWithImage:(UIImage *)image;
@end
@@ -124,9 +126,9 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
*/
@interface YYImageDecoder : NSObject
@property (nonatomic, readonly) NSData *data; ///< Image data.
@property (nonatomic, readonly) YYImageType type; ///< Image data type.
@property (nonatomic, readonly) CGFloat scale; ///< Image scale.
@property (nullable, nonatomic, readonly) NSData *data; ///< Image data.
@property (nonatomic, readonly) YYImageType type; ///< Image data type.
@property (nonatomic, readonly) CGFloat scale; ///< Image scale.
@property (nonatomic, readonly) NSUInteger frameCount; ///< Image frame count.
@property (nonatomic, readonly) NSUInteger loopCount; ///< Image loop count, 0 means infinite.
@property (nonatomic, readonly) NSUInteger width; ///< Image canvas width.
@@ -158,7 +160,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@return Whether succeed.
*/
- (BOOL)updateData:(NSData *)data final:(BOOL)final;
- (BOOL)updateData:(nullable NSData *)data final:(BOOL)final;
/**
Convenience method to create a decoder with specified data.
@@ -166,7 +168,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param scale Image's scale.
@return A new decoder, or nil if an error occurs.
*/
+ (instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale;
+ (nullable instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale;
/**
Decodes and returns a frame from a specified index.
@@ -175,7 +177,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
If NO, it will try to returns the original frame data without blend.
@return A new frame with image, or nil if an error occurs.
*/
- (YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay;
- (nullable YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay;
/**
Returns the frame duration from a specified index.
@@ -191,13 +193,13 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param index Frame image index (zero-based).
@return The ImageIO frame property.
*/
- (NSDictionary *)framePropertiesAtIndex:(NSUInteger)index;
- (nullable NSDictionary *)framePropertiesAtIndex:(NSUInteger)index;
/**
Returns the image's properties. See "CGImageProperties.h" in ImageIO.framework
for more information.
*/
- (NSDictionary *)imageProperties;
- (nullable NSDictionary *)imageProperties;
@end
@@ -231,10 +233,10 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
*/
@interface YYImageEncoder : NSObject
@property (nonatomic, readonly) YYImageType type; ///< Image type.
@property (nonatomic, assign) NSUInteger loopCount; ///< Loop count, 0 means infinit, only available for GIF/APNG/WebP.
@property (nonatomic, assign) BOOL lossless; ///< Lossless, only available for WebP.
@property (nonatomic, assign) CGFloat quality; ///< Compress quality, 0.0~1.0, only available for JPG/JP2/WebP.
@property (nonatomic, readonly) YYImageType type; ///< Image type.
@property (nonatomic) NSUInteger loopCount; ///< Loop count, 0 means infinit, only available for GIF/APNG/WebP.
@property (nonatomic) BOOL lossless; ///< Lossless, only available for WebP.
@property (nonatomic) CGFloat quality; ///< Compress quality, 0.0~1.0, only available for JPG/JP2/WebP.
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;
@@ -244,7 +246,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param type Image type.
@return A new encoder, or nil if an error occurs.
*/
- (instancetype)initWithType:(YYImageType)type NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithType:(YYImageType)type NS_DESIGNATED_INITIALIZER;
/**
Add an image to encoder.
@@ -271,7 +273,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
Encodes the image and returns the image data.
@return The image data, or nil if an error occurs.
*/
- (NSData *)encode;
- (nullable NSData *)encode;
/**
Encodes the image to a file.
@@ -287,7 +289,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param quality Image quality, 0.0~1.0.
@return The image data, or nil if an error occurs.
*/
+ (NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality;
+ (nullable NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality;
/**
Convenience method to encode image from a decoder.
@@ -296,7 +298,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param quality Image quality, 0.0~1.0.
@return The image data, or nil if an error occurs.
*/
+ (NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality;
+ (nullable NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality;
@end
@@ -319,7 +321,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
Wherher the image can be display on screen without additional decoding.
@warning It just a hint for your code, change it has no other effect.
*/
@property (nonatomic, assign) BOOL yy_isDecodedForDisplay;
@property (nonatomic) BOOL yy_isDecodedForDisplay;
/**
Saves this image to iOS Photos Album.
@@ -332,7 +334,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
assetURL: An URL that identifies the saved image file. If the image is not saved, assetURL is nil.
error: If the image is not saved, an error object that describes the reason for failure, otherwise nil.
*/
- (void)yy_saveToAlbumWithCompletionBlock:(void(^)(NSURL *assetURL, NSError *error))completionBlock;
- (void)yy_saveToAlbumWithCompletionBlock:(nullable void(^)(NSURL * _Nullable assetURL, NSError * _Nullable error))completionBlock;
/**
Return a 'best' data representation for this image.
@@ -343,7 +345,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@return Image data, or nil if an error occurs.
*/
- (NSData *)yy_imageDataRepresentation;
- (nullable NSData *)yy_imageDataRepresentation;
@end
@@ -355,13 +357,13 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
CG_EXTERN YYImageType YYImageDetectType(CFDataRef data);
/// Convert YYImageType to UTI (such as kUTTypeJPEG).
CG_EXTERN CFStringRef YYImageTypeToUTType(YYImageType type);
CG_EXTERN CFStringRef _Nullable YYImageTypeToUTType(YYImageType type);
/// Convert UTI (such as kUTTypeJPEG) to YYImageType.
CG_EXTERN YYImageType YYImageTypeFromUTType(CFStringRef uti);
/// Get image type's file extension (such as @"jpg").
CG_EXTERN NSString *YYImageTypeGetExtension(YYImageType type);
CG_EXTERN NSString *_Nullable YYImageTypeGetExtension(YYImageType type);
@@ -402,7 +404,7 @@ CG_EXTERN NSInteger YYUIImageOrientationToEXIFValue(UIImageOrientation orientati
@return A decoded image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay);
/**
Create an image copy with an orientation.
@@ -412,9 +414,9 @@ CG_EXTERN CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decode
@param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
@return A new image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
UIImageOrientation orientation,
CGBitmapInfo destBitmapInfo);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
UIImageOrientation orientation,
CGBitmapInfo destBitmapInfo);
/**
Create an image copy with CGAffineTransform.
@@ -425,10 +427,10 @@ CG_EXTERN CGImageRef YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
@param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
@return A new image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
CGAffineTransform transform,
CGSize destSize,
CGBitmapInfo destBitmapInfo);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
CGAffineTransform transform,
CGSize destSize,
CGBitmapInfo destBitmapInfo);
/**
Encode an image to data with CGImageDestination.
@@ -438,7 +440,7 @@ CG_EXTERN CGImageRef YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
@param quality The quality (0.0~1.0)
@return A new image data, or nil if an error occurs.
*/
CG_EXTERN CFDataRef YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality);
CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality);
/**
@@ -468,12 +470,11 @@ CG_EXTERN NSUInteger YYImageGetWebPFrameCount(CFDataRef webpData);
(speed down, and may lose some details).
@return The decoded image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
BOOL decodeForDisplay,
BOOL useThreads,
BOOL bypassFiltering,
BOOL noFancyUpsampling);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateWithWebPData(CFDataRef webpData,
BOOL decodeForDisplay,
BOOL useThreads,
BOOL bypassFiltering,
BOOL noFancyUpsampling);
typedef NS_ENUM(NSUInteger, YYImagePreset) {
YYImagePresetDefault = 0, ///< default preset.
@@ -495,8 +496,10 @@ typedef NS_ENUM(NSUInteger, YYImagePreset) {
@param preset Preset for different image type, default is YYImagePresetDefault.
@return WebP data, or nil if an error occurs.
*/
CG_EXTERN CFDataRef YYCGImageCreateEncodedWebPData(CGImageRef imageRef,
BOOL lossless,
CGFloat quality,
int compressLevel,
YYImagePreset preset);
CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedWebPData(CGImageRef imageRef,
BOOL lossless,
CGFloat quality,
int compressLevel,
YYImagePreset preset);
NS_ASSUME_NONNULL_END
+52 -40
View File
@@ -19,7 +19,6 @@
#import <AssetsLibrary/AssetsLibrary.h>
#import <objc/runtime.h>
#import <pthread.h>
#import <libkern/OSAtomic.h>
#import <zlib.h>
@@ -924,7 +923,7 @@ CGImageRef YYCGImageCreateAffineTransformCopy(CGImageRef imageRef, CGAffineTrans
if (srcWidth == 0 || srcHeight == 0 || destWidth == 0 || destHeight == 0) return NULL;
CGDataProviderRef tmpProvider = NULL, destProvider = NULL;
CGImageRef tmpImage = NULL, destImage = NULL;;
CGImageRef tmpImage = NULL, destImage = NULL;
vImage_Buffer src = {0}, tmp = {0}, dest = {0};
if(!YYCGImageDecodeToBitmapBufferWith32BitFormat(imageRef, &src, kCGImageAlphaFirst | kCGBitmapByteOrderDefault)) return NULL;
@@ -1400,7 +1399,8 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
config.output.u.RGBA.stride = (int)bytesPerRow;
config.output.u.RGBA.size = destLength;
if (WebPDecode(payload, payloadSize, &config) != VP8_STATUS_OK) goto fail;
VP8StatusCode result = WebPDecode(payload, payloadSize, &config);
if ((result != VP8_STATUS_OK) && (result != VP8_STATUS_NOT_ENOUGH_DATA)) goto fail;
if (iter.x_offset != 0 || iter.y_offset != 0) {
void *tmp = calloc(1, destLength);
@@ -1506,7 +1506,7 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
@implementation YYImageDecoder {
pthread_mutex_t _lock;
pthread_mutex_t _lock; // recursive lock
BOOL _sourceTypeDetected;
CGImageSourceRef _source;
@@ -1516,7 +1516,7 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
#endif
UIImageOrientation _orientation;
OSSpinLock _framesLock;
dispatch_semaphore_t _framesLock;
NSArray *_frames; ///< Array<GGImageDecoderFrame>, without image
BOOL _needBlend;
NSUInteger _blendFrameIndex;
@@ -1548,7 +1548,7 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
self = [super init];
if (scale <= 0) scale = 1;
_scale = scale;
_framesLock = OS_SPINLOCK_INIT;
_framesLock = dispatch_semaphore_create(1);
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
@@ -1577,11 +1577,11 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
- (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index {
NSTimeInterval result = 0;
OSSpinLockLock(&_framesLock); // for better performance when play animation...
dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER);
if (index < _frames.count) {
result = ((_YYImageDecoderFrame *)_frames[index]).duration;
}
OSSpinLockUnlock(&_framesLock);
dispatch_semaphore_signal(_framesLock);
return result;
}
@@ -1746,9 +1746,9 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
_loopCount = 0;
if (_webpSource) WebPDemuxDelete(_webpSource);
_webpSource = NULL;
OSSpinLockLock(&_framesLock);
dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER);
_frames = nil;
OSSpinLockUnlock(&_framesLock);
dispatch_semaphore_signal(_framesLock);
/*
https://developers.google.com/speed/webp/docs/api
@@ -1832,9 +1832,9 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
_loopCount = webpLoopCount;
_needBlend = needBlend;
_webpSource = demuxer;
OSSpinLockLock(&_framesLock);
dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER);
_frames = frames;
OSSpinLockUnlock(&_framesLock);
dispatch_semaphore_signal(_framesLock);
#endif
}
@@ -1930,9 +1930,9 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
_loopCount = apng->apng_loop_num;
_needBlend = needBlend;
_apngSource = apng;
OSSpinLockLock(&_framesLock);
dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER);
_frames = frames;
OSSpinLockUnlock(&_framesLock);
dispatch_semaphore_signal(_framesLock);
}
- (void)_updateSourceImageIO {
@@ -1940,9 +1940,9 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
_height = 0;
_orientation = UIImageOrientationUp;
_loopCount = 0;
OSSpinLockLock(&_framesLock);
dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER);
_frames = nil;
OSSpinLockUnlock(&_framesLock);
dispatch_semaphore_signal(_framesLock);
if (!_source) {
if (_finalized) {
@@ -2026,9 +2026,9 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
CFRelease(properties);
}
}
OSSpinLockLock(&_framesLock);
dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER);
_frames = frames;
OSSpinLockUnlock(&_framesLock);
dispatch_semaphore_signal(_framesLock);
}
- (CGImageRef)_newUnblendedImageAtIndex:(NSUInteger)index
@@ -2151,7 +2151,8 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
config.output.u.RGBA.rgba = pixels;
config.output.u.RGBA.stride = (int)bytesPerRow;
config.output.u.RGBA.size = length;
if (WebPDecode(payload, payloadSize, &config) != VP8_STATUS_OK) { // decode
VP8StatusCode result = WebPDecode(payload, payloadSize, &config); // decode
if ((result != VP8_STATUS_OK) && (result != VP8_STATUS_NOT_ENOUGH_DATA)) {
WebPDemuxReleaseIterator(&iter);
free(pixels);
return NULL;
@@ -2416,27 +2417,38 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
}
for (int i = 0; i < count; i++) {
id imageSrc = _images[i];
NSDictionary *frameProperty = NULL;
if (_type == YYImageTypeGIF && count > 1) {
frameProperty = @{(NSString *)kCGImagePropertyGIFDictionary : @{(NSString *) kCGImagePropertyGIFDelayTime:_durations[i]}};
} else {
frameProperty = @{(id)kCGImageDestinationLossyCompressionQuality : @(_quality)};
}
if ([imageSrc isKindOfClass:[UIImage class]]) {
CGImageDestinationAddImage(destination, ((UIImage *)imageSrc).CGImage, (CFDictionaryRef)frameProperty);
} else if ([imageSrc isKindOfClass:[NSURL class]]) {
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, i, (CFDictionaryRef)frameProperty);
CFRelease(source);
@autoreleasepool {
id imageSrc = _images[i];
NSDictionary *frameProperty = NULL;
if (_type == YYImageTypeGIF && count > 1) {
frameProperty = @{(NSString *)kCGImagePropertyGIFDictionary : @{(NSString *) kCGImagePropertyGIFDelayTime:_durations[i]}};
} else {
frameProperty = @{(id)kCGImageDestinationLossyCompressionQuality : @(_quality)};
}
} else if ([imageSrc isKindOfClass:[NSData class]]) {
CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, i, (CFDictionaryRef)frameProperty);
CFRelease(source);
if ([imageSrc isKindOfClass:[UIImage class]]) {
UIImage *image = imageSrc;
if (image.imageOrientation != UIImageOrientationUp && image.CGImage) {
CGBitmapInfo info = CGImageGetBitmapInfo(image.CGImage) | CGImageGetAlphaInfo(image.CGImage);
CGImageRef rotated = YYCGImageCreateCopyWithOrientation(image.CGImage, image.imageOrientation, info);
if (rotated) {
image = [UIImage imageWithCGImage:rotated];
CFRelease(rotated);
}
}
if (image.CGImage) CGImageDestinationAddImage(destination, ((UIImage *)imageSrc).CGImage, (CFDictionaryRef)frameProperty);
} else if ([imageSrc isKindOfClass:[NSURL class]]) {
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, i, (CFDictionaryRef)frameProperty);
CFRelease(source);
}
} else if ([imageSrc isKindOfClass:[NSData class]]) {
CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, i, (CFDictionaryRef)frameProperty);
CFRelease(source);
}
}
}
}
@@ -2725,7 +2737,7 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
}
+ (NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality {
if (!decoder || !decoder.frameCount == 0) return nil;
if (!decoder || decoder.frameCount == 0) return nil;
YYImageEncoder *encoder = [[YYImageEncoder alloc] initWithType:type];
encoder.quality = quality;
for (int i = 0; i < decoder.frameCount; i++) {
+10 -6
View File
@@ -19,6 +19,8 @@
#import "YYAnimatedImageView.h"
#endif
NS_ASSUME_NONNULL_BEGIN
/**
An image to display sprite sheet animation.
@@ -79,13 +81,13 @@
@return An image object, or nil if an error occurs.
*/
- (instancetype)initWithSpriteSheetImage:(UIImage *)image
contentRects:(NSArray *)contentRects
frameDurations:(NSArray *)frameDurations
loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithSpriteSheetImage:(UIImage *)image
contentRects:(NSArray<NSValue *> *)contentRects
frameDurations:(NSArray<NSNumber *> *)frameDurations
loopCount:(NSUInteger)loopCount;
@property (nonatomic, readonly) NSArray *contentRects;
@property (nonatomic, readonly) NSArray *frameDurations;
@property (nonatomic, readonly) NSArray<NSValue *> *contentRects;
@property (nonatomic, readonly) NSArray<NSValue *> *frameDurations;
@property (nonatomic, readonly) NSUInteger loopCount;
/**
@@ -98,3 +100,5 @@
- (CGRect)contentsRectForCALayerAtIndex:(NSUInteger)index;
@end
NS_ASSUME_NONNULL_END