xref: /aosp_15_r20/external/webp/src/demux/anim_decode.c (revision b2055c353e87c8814eb2b6b1b11112a1562253bd)
1 // Copyright 2015 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 //  AnimDecoder implementation.
11 //
12 
13 #ifdef HAVE_CONFIG_H
14 #include "src/webp/config.h"
15 #endif
16 
17 #include <assert.h>
18 #include <string.h>
19 
20 #include "src/utils/utils.h"
21 #include "src/webp/decode.h"
22 #include "src/webp/demux.h"
23 #include "src/webp/types.h"
24 
25 #define NUM_CHANNELS 4
26 
27 // Channel extraction from a uint32_t representation of a uint8_t RGBA/BGRA
28 // buffer.
29 #ifdef WORDS_BIGENDIAN
30 #define CHANNEL_SHIFT(i) (24 - (i) * 8)
31 #else
32 #define CHANNEL_SHIFT(i) ((i) * 8)
33 #endif
34 
35 typedef void (*BlendRowFunc)(uint32_t* const, const uint32_t* const, int);
36 static void BlendPixelRowNonPremult(uint32_t* const src,
37                                     const uint32_t* const dst, int num_pixels);
38 static void BlendPixelRowPremult(uint32_t* const src, const uint32_t* const dst,
39                                  int num_pixels);
40 
41 struct WebPAnimDecoder {
42   WebPDemuxer* demux_;             // Demuxer created from given WebP bitstream.
43   WebPDecoderConfig config_;       // Decoder config.
44   // Note: we use a pointer to a function blending multiple pixels at a time to
45   // allow possible inlining of per-pixel blending function.
46   BlendRowFunc blend_func_;        // Pointer to the chose blend row function.
47   WebPAnimInfo info_;              // Global info about the animation.
48   uint8_t* curr_frame_;            // Current canvas (not disposed).
49   uint8_t* prev_frame_disposed_;   // Previous canvas (properly disposed).
50   int prev_frame_timestamp_;       // Previous frame timestamp (milliseconds).
51   WebPIterator prev_iter_;         // Iterator object for previous frame.
52   int prev_frame_was_keyframe_;    // True if previous frame was a keyframe.
53   int next_frame_;                 // Index of the next frame to be decoded
54                                    // (starting from 1).
55 };
56 
DefaultDecoderOptions(WebPAnimDecoderOptions * const dec_options)57 static void DefaultDecoderOptions(WebPAnimDecoderOptions* const dec_options) {
58   dec_options->color_mode = MODE_RGBA;
59   dec_options->use_threads = 0;
60 }
61 
WebPAnimDecoderOptionsInitInternal(WebPAnimDecoderOptions * dec_options,int abi_version)62 int WebPAnimDecoderOptionsInitInternal(WebPAnimDecoderOptions* dec_options,
63                                        int abi_version) {
64   if (dec_options == NULL ||
65       WEBP_ABI_IS_INCOMPATIBLE(abi_version, WEBP_DEMUX_ABI_VERSION)) {
66     return 0;
67   }
68   DefaultDecoderOptions(dec_options);
69   return 1;
70 }
71 
ApplyDecoderOptions(const WebPAnimDecoderOptions * const dec_options,WebPAnimDecoder * const dec)72 WEBP_NODISCARD static int ApplyDecoderOptions(
73     const WebPAnimDecoderOptions* const dec_options,
74     WebPAnimDecoder* const dec) {
75   WEBP_CSP_MODE mode;
76   WebPDecoderConfig* config = &dec->config_;
77   assert(dec_options != NULL);
78 
79   mode = dec_options->color_mode;
80   if (mode != MODE_RGBA && mode != MODE_BGRA &&
81       mode != MODE_rgbA && mode != MODE_bgrA) {
82     return 0;
83   }
84   dec->blend_func_ = (mode == MODE_RGBA || mode == MODE_BGRA)
85                          ? &BlendPixelRowNonPremult
86                          : &BlendPixelRowPremult;
87   if (!WebPInitDecoderConfig(config)) {
88     return 0;
89   }
90   config->output.colorspace = mode;
91   config->output.is_external_memory = 1;
92   config->options.use_threads = dec_options->use_threads;
93   // Note: config->output.u.RGBA is set at the time of decoding each frame.
94   return 1;
95 }
96 
WebPAnimDecoderNewInternal(const WebPData * webp_data,const WebPAnimDecoderOptions * dec_options,int abi_version)97 WebPAnimDecoder* WebPAnimDecoderNewInternal(
98     const WebPData* webp_data, const WebPAnimDecoderOptions* dec_options,
99     int abi_version) {
100   WebPAnimDecoderOptions options;
101   WebPAnimDecoder* dec = NULL;
102   WebPBitstreamFeatures features;
103   if (webp_data == NULL ||
104       WEBP_ABI_IS_INCOMPATIBLE(abi_version, WEBP_DEMUX_ABI_VERSION)) {
105     return NULL;
106   }
107 
108   // Validate the bitstream before doing expensive allocations. The demuxer may
109   // be more tolerant than the decoder.
110   if (WebPGetFeatures(webp_data->bytes, webp_data->size, &features) !=
111       VP8_STATUS_OK) {
112     return NULL;
113   }
114 
115   // Note: calloc() so that the pointer members are initialized to NULL.
116   dec = (WebPAnimDecoder*)WebPSafeCalloc(1ULL, sizeof(*dec));
117   if (dec == NULL) goto Error;
118 
119   if (dec_options != NULL) {
120     options = *dec_options;
121   } else {
122     DefaultDecoderOptions(&options);
123   }
124   if (!ApplyDecoderOptions(&options, dec)) goto Error;
125 
126   dec->demux_ = WebPDemux(webp_data);
127   if (dec->demux_ == NULL) goto Error;
128 
129   dec->info_.canvas_width = WebPDemuxGetI(dec->demux_, WEBP_FF_CANVAS_WIDTH);
130   dec->info_.canvas_height = WebPDemuxGetI(dec->demux_, WEBP_FF_CANVAS_HEIGHT);
131   dec->info_.loop_count = WebPDemuxGetI(dec->demux_, WEBP_FF_LOOP_COUNT);
132   dec->info_.bgcolor = WebPDemuxGetI(dec->demux_, WEBP_FF_BACKGROUND_COLOR);
133   dec->info_.frame_count = WebPDemuxGetI(dec->demux_, WEBP_FF_FRAME_COUNT);
134 
135   // Note: calloc() because we fill frame with zeroes as well.
136   dec->curr_frame_ = (uint8_t*)WebPSafeCalloc(
137       dec->info_.canvas_width * NUM_CHANNELS, dec->info_.canvas_height);
138   if (dec->curr_frame_ == NULL) goto Error;
139   dec->prev_frame_disposed_ = (uint8_t*)WebPSafeCalloc(
140       dec->info_.canvas_width * NUM_CHANNELS, dec->info_.canvas_height);
141   if (dec->prev_frame_disposed_ == NULL) goto Error;
142 
143   WebPAnimDecoderReset(dec);
144   return dec;
145 
146  Error:
147   WebPAnimDecoderDelete(dec);
148   return NULL;
149 }
150 
WebPAnimDecoderGetInfo(const WebPAnimDecoder * dec,WebPAnimInfo * info)151 int WebPAnimDecoderGetInfo(const WebPAnimDecoder* dec, WebPAnimInfo* info) {
152   if (dec == NULL || info == NULL) return 0;
153   *info = dec->info_;
154   return 1;
155 }
156 
157 // Returns true if the frame covers the full canvas.
IsFullFrame(int width,int height,int canvas_width,int canvas_height)158 static int IsFullFrame(int width, int height, int canvas_width,
159                        int canvas_height) {
160   return (width == canvas_width && height == canvas_height);
161 }
162 
163 // Clear the canvas to transparent.
ZeroFillCanvas(uint8_t * buf,uint32_t canvas_width,uint32_t canvas_height)164 WEBP_NODISCARD static int ZeroFillCanvas(uint8_t* buf, uint32_t canvas_width,
165                                          uint32_t canvas_height) {
166   const uint64_t size =
167       (uint64_t)canvas_width * canvas_height * NUM_CHANNELS * sizeof(*buf);
168   if (!CheckSizeOverflow(size)) return 0;
169   memset(buf, 0, (size_t)size);
170   return 1;
171 }
172 
173 // Clear given frame rectangle to transparent.
ZeroFillFrameRect(uint8_t * buf,int buf_stride,int x_offset,int y_offset,int width,int height)174 static void ZeroFillFrameRect(uint8_t* buf, int buf_stride, int x_offset,
175                               int y_offset, int width, int height) {
176   int j;
177   assert(width * NUM_CHANNELS <= buf_stride);
178   buf += y_offset * buf_stride + x_offset * NUM_CHANNELS;
179   for (j = 0; j < height; ++j) {
180     memset(buf, 0, width * NUM_CHANNELS);
181     buf += buf_stride;
182   }
183 }
184 
185 // Copy width * height pixels from 'src' to 'dst'.
CopyCanvas(const uint8_t * src,uint8_t * dst,uint32_t width,uint32_t height)186 WEBP_NODISCARD static int CopyCanvas(const uint8_t* src, uint8_t* dst,
187                                      uint32_t width, uint32_t height) {
188   const uint64_t size = (uint64_t)width * height * NUM_CHANNELS;
189   if (!CheckSizeOverflow(size)) return 0;
190   assert(src != NULL && dst != NULL);
191   memcpy(dst, src, (size_t)size);
192   return 1;
193 }
194 
195 // Returns true if the current frame is a key-frame.
IsKeyFrame(const WebPIterator * const curr,const WebPIterator * const prev,int prev_frame_was_key_frame,int canvas_width,int canvas_height)196 static int IsKeyFrame(const WebPIterator* const curr,
197                       const WebPIterator* const prev,
198                       int prev_frame_was_key_frame,
199                       int canvas_width, int canvas_height) {
200   if (curr->frame_num == 1) {
201     return 1;
202   } else if ((!curr->has_alpha || curr->blend_method == WEBP_MUX_NO_BLEND) &&
203              IsFullFrame(curr->width, curr->height,
204                          canvas_width, canvas_height)) {
205     return 1;
206   } else {
207     return (prev->dispose_method == WEBP_MUX_DISPOSE_BACKGROUND) &&
208            (IsFullFrame(prev->width, prev->height, canvas_width,
209                         canvas_height) ||
210             prev_frame_was_key_frame);
211   }
212 }
213 
214 
215 // Blend a single channel of 'src' over 'dst', given their alpha channel values.
216 // 'src' and 'dst' are assumed to be NOT pre-multiplied by alpha.
BlendChannelNonPremult(uint32_t src,uint8_t src_a,uint32_t dst,uint8_t dst_a,uint32_t scale,int shift)217 static uint8_t BlendChannelNonPremult(uint32_t src, uint8_t src_a,
218                                       uint32_t dst, uint8_t dst_a,
219                                       uint32_t scale, int shift) {
220   const uint8_t src_channel = (src >> shift) & 0xff;
221   const uint8_t dst_channel = (dst >> shift) & 0xff;
222   const uint32_t blend_unscaled = src_channel * src_a + dst_channel * dst_a;
223   assert(blend_unscaled < (1ULL << 32) / scale);
224   return (blend_unscaled * scale) >> CHANNEL_SHIFT(3);
225 }
226 
227 // Blend 'src' over 'dst' assuming they are NOT pre-multiplied by alpha.
BlendPixelNonPremult(uint32_t src,uint32_t dst)228 static uint32_t BlendPixelNonPremult(uint32_t src, uint32_t dst) {
229   const uint8_t src_a = (src >> CHANNEL_SHIFT(3)) & 0xff;
230 
231   if (src_a == 0) {
232     return dst;
233   } else {
234     const uint8_t dst_a = (dst >> CHANNEL_SHIFT(3)) & 0xff;
235     // This is the approximate integer arithmetic for the actual formula:
236     // dst_factor_a = (dst_a * (255 - src_a)) / 255.
237     const uint8_t dst_factor_a = (dst_a * (256 - src_a)) >> 8;
238     const uint8_t blend_a = src_a + dst_factor_a;
239     const uint32_t scale = (1UL << 24) / blend_a;
240 
241     const uint8_t blend_r = BlendChannelNonPremult(
242         src, src_a, dst, dst_factor_a, scale, CHANNEL_SHIFT(0));
243     const uint8_t blend_g = BlendChannelNonPremult(
244         src, src_a, dst, dst_factor_a, scale, CHANNEL_SHIFT(1));
245     const uint8_t blend_b = BlendChannelNonPremult(
246         src, src_a, dst, dst_factor_a, scale, CHANNEL_SHIFT(2));
247     assert(src_a + dst_factor_a < 256);
248 
249     return ((uint32_t)blend_r << CHANNEL_SHIFT(0)) |
250            ((uint32_t)blend_g << CHANNEL_SHIFT(1)) |
251            ((uint32_t)blend_b << CHANNEL_SHIFT(2)) |
252            ((uint32_t)blend_a << CHANNEL_SHIFT(3));
253   }
254 }
255 
256 // Blend 'num_pixels' in 'src' over 'dst' assuming they are NOT pre-multiplied
257 // by alpha.
BlendPixelRowNonPremult(uint32_t * const src,const uint32_t * const dst,int num_pixels)258 static void BlendPixelRowNonPremult(uint32_t* const src,
259                                     const uint32_t* const dst, int num_pixels) {
260   int i;
261   for (i = 0; i < num_pixels; ++i) {
262     const uint8_t src_alpha = (src[i] >> CHANNEL_SHIFT(3)) & 0xff;
263     if (src_alpha != 0xff) {
264       src[i] = BlendPixelNonPremult(src[i], dst[i]);
265     }
266   }
267 }
268 
269 // Individually multiply each channel in 'pix' by 'scale'.
ChannelwiseMultiply(uint32_t pix,uint32_t scale)270 static WEBP_INLINE uint32_t ChannelwiseMultiply(uint32_t pix, uint32_t scale) {
271   uint32_t mask = 0x00FF00FF;
272   uint32_t rb = ((pix & mask) * scale) >> 8;
273   uint32_t ag = ((pix >> 8) & mask) * scale;
274   return (rb & mask) | (ag & ~mask);
275 }
276 
277 // Blend 'src' over 'dst' assuming they are pre-multiplied by alpha.
BlendPixelPremult(uint32_t src,uint32_t dst)278 static uint32_t BlendPixelPremult(uint32_t src, uint32_t dst) {
279   const uint8_t src_a = (src >> CHANNEL_SHIFT(3)) & 0xff;
280   return src + ChannelwiseMultiply(dst, 256 - src_a);
281 }
282 
283 // Blend 'num_pixels' in 'src' over 'dst' assuming they are pre-multiplied by
284 // alpha.
BlendPixelRowPremult(uint32_t * const src,const uint32_t * const dst,int num_pixels)285 static void BlendPixelRowPremult(uint32_t* const src, const uint32_t* const dst,
286                                  int num_pixels) {
287   int i;
288   for (i = 0; i < num_pixels; ++i) {
289     const uint8_t src_alpha = (src[i] >> CHANNEL_SHIFT(3)) & 0xff;
290     if (src_alpha != 0xff) {
291       src[i] = BlendPixelPremult(src[i], dst[i]);
292     }
293   }
294 }
295 
296 // Returns two ranges (<left, width> pairs) at row 'canvas_y', that belong to
297 // 'src' but not 'dst'. A point range is empty if the corresponding width is 0.
FindBlendRangeAtRow(const WebPIterator * const src,const WebPIterator * const dst,int canvas_y,int * const left1,int * const width1,int * const left2,int * const width2)298 static void FindBlendRangeAtRow(const WebPIterator* const src,
299                                 const WebPIterator* const dst, int canvas_y,
300                                 int* const left1, int* const width1,
301                                 int* const left2, int* const width2) {
302   const int src_max_x = src->x_offset + src->width;
303   const int dst_max_x = dst->x_offset + dst->width;
304   const int dst_max_y = dst->y_offset + dst->height;
305   assert(canvas_y >= src->y_offset && canvas_y < (src->y_offset + src->height));
306   *left1 = -1;
307   *width1 = 0;
308   *left2 = -1;
309   *width2 = 0;
310 
311   if (canvas_y < dst->y_offset || canvas_y >= dst_max_y ||
312       src->x_offset >= dst_max_x || src_max_x <= dst->x_offset) {
313     *left1 = src->x_offset;
314     *width1 = src->width;
315     return;
316   }
317 
318   if (src->x_offset < dst->x_offset) {
319     *left1 = src->x_offset;
320     *width1 = dst->x_offset - src->x_offset;
321   }
322 
323   if (src_max_x > dst_max_x) {
324     *left2 = dst_max_x;
325     *width2 = src_max_x - dst_max_x;
326   }
327 }
328 
WebPAnimDecoderGetNext(WebPAnimDecoder * dec,uint8_t ** buf_ptr,int * timestamp_ptr)329 int WebPAnimDecoderGetNext(WebPAnimDecoder* dec,
330                            uint8_t** buf_ptr, int* timestamp_ptr) {
331   WebPIterator iter;
332   uint32_t width;
333   uint32_t height;
334   int is_key_frame;
335   int timestamp;
336   BlendRowFunc blend_row;
337 
338   if (dec == NULL || buf_ptr == NULL || timestamp_ptr == NULL) return 0;
339   if (!WebPAnimDecoderHasMoreFrames(dec)) return 0;
340 
341   width = dec->info_.canvas_width;
342   height = dec->info_.canvas_height;
343   blend_row = dec->blend_func_;
344 
345   // Get compressed frame.
346   if (!WebPDemuxGetFrame(dec->demux_, dec->next_frame_, &iter)) {
347     return 0;
348   }
349   timestamp = dec->prev_frame_timestamp_ + iter.duration;
350 
351   // Initialize.
352   is_key_frame = IsKeyFrame(&iter, &dec->prev_iter_,
353                             dec->prev_frame_was_keyframe_, width, height);
354   if (is_key_frame) {
355     if (!ZeroFillCanvas(dec->curr_frame_, width, height)) {
356       goto Error;
357     }
358   } else {
359     if (!CopyCanvas(dec->prev_frame_disposed_, dec->curr_frame_,
360                     width, height)) {
361       goto Error;
362     }
363   }
364 
365   // Decode.
366   {
367     const uint8_t* in = iter.fragment.bytes;
368     const size_t in_size = iter.fragment.size;
369     const uint32_t stride = width * NUM_CHANNELS;  // at most 25 + 2 bits
370     const uint64_t out_offset = (uint64_t)iter.y_offset * stride +
371                                 (uint64_t)iter.x_offset * NUM_CHANNELS;  // 53b
372     const uint64_t size = (uint64_t)iter.height * stride;  // at most 25 + 27b
373     WebPDecoderConfig* const config = &dec->config_;
374     WebPRGBABuffer* const buf = &config->output.u.RGBA;
375     if ((size_t)size != size) goto Error;
376     buf->stride = (int)stride;
377     buf->size = (size_t)size;
378     buf->rgba = dec->curr_frame_ + out_offset;
379 
380     if (WebPDecode(in, in_size, config) != VP8_STATUS_OK) {
381       goto Error;
382     }
383   }
384 
385   // During the decoding of current frame, we may have set some pixels to be
386   // transparent (i.e. alpha < 255). However, the value of each of these
387   // pixels should have been determined by blending it against the value of
388   // that pixel in the previous frame if blending method of is WEBP_MUX_BLEND.
389   if (iter.frame_num > 1 && iter.blend_method == WEBP_MUX_BLEND &&
390       !is_key_frame) {
391     if (dec->prev_iter_.dispose_method == WEBP_MUX_DISPOSE_NONE) {
392       int y;
393       // Blend transparent pixels with pixels in previous canvas.
394       for (y = 0; y < iter.height; ++y) {
395         const size_t offset =
396             (iter.y_offset + y) * width + iter.x_offset;
397         blend_row((uint32_t*)dec->curr_frame_ + offset,
398                   (uint32_t*)dec->prev_frame_disposed_ + offset, iter.width);
399       }
400     } else {
401       int y;
402       assert(dec->prev_iter_.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND);
403       // We need to blend a transparent pixel with its value just after
404       // initialization. That is, blend it with:
405       // * Fully transparent pixel if it belongs to prevRect <-- No-op.
406       // * The pixel in the previous canvas otherwise <-- Need alpha-blending.
407       for (y = 0; y < iter.height; ++y) {
408         const int canvas_y = iter.y_offset + y;
409         int left1, width1, left2, width2;
410         FindBlendRangeAtRow(&iter, &dec->prev_iter_, canvas_y, &left1, &width1,
411                             &left2, &width2);
412         if (width1 > 0) {
413           const size_t offset1 = canvas_y * width + left1;
414           blend_row((uint32_t*)dec->curr_frame_ + offset1,
415                     (uint32_t*)dec->prev_frame_disposed_ + offset1, width1);
416         }
417         if (width2 > 0) {
418           const size_t offset2 = canvas_y * width + left2;
419           blend_row((uint32_t*)dec->curr_frame_ + offset2,
420                     (uint32_t*)dec->prev_frame_disposed_ + offset2, width2);
421         }
422       }
423     }
424   }
425 
426   // Update info of the previous frame and dispose it for the next iteration.
427   dec->prev_frame_timestamp_ = timestamp;
428   WebPDemuxReleaseIterator(&dec->prev_iter_);
429   dec->prev_iter_ = iter;
430   dec->prev_frame_was_keyframe_ = is_key_frame;
431   if (!CopyCanvas(dec->curr_frame_, dec->prev_frame_disposed_, width, height)) {
432     goto Error;
433   }
434   if (dec->prev_iter_.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND) {
435     ZeroFillFrameRect(dec->prev_frame_disposed_, width * NUM_CHANNELS,
436                       dec->prev_iter_.x_offset, dec->prev_iter_.y_offset,
437                       dec->prev_iter_.width, dec->prev_iter_.height);
438   }
439   ++dec->next_frame_;
440 
441   // All OK, fill in the values.
442   *buf_ptr = dec->curr_frame_;
443   *timestamp_ptr = timestamp;
444   return 1;
445 
446  Error:
447   WebPDemuxReleaseIterator(&iter);
448   return 0;
449 }
450 
WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder * dec)451 int WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder* dec) {
452   if (dec == NULL) return 0;
453   return (dec->next_frame_ <= (int)dec->info_.frame_count);
454 }
455 
WebPAnimDecoderReset(WebPAnimDecoder * dec)456 void WebPAnimDecoderReset(WebPAnimDecoder* dec) {
457   if (dec != NULL) {
458     dec->prev_frame_timestamp_ = 0;
459     WebPDemuxReleaseIterator(&dec->prev_iter_);
460     memset(&dec->prev_iter_, 0, sizeof(dec->prev_iter_));
461     dec->prev_frame_was_keyframe_ = 0;
462     dec->next_frame_ = 1;
463   }
464 }
465 
WebPAnimDecoderGetDemuxer(const WebPAnimDecoder * dec)466 const WebPDemuxer* WebPAnimDecoderGetDemuxer(const WebPAnimDecoder* dec) {
467   if (dec == NULL) return NULL;
468   return dec->demux_;
469 }
470 
WebPAnimDecoderDelete(WebPAnimDecoder * dec)471 void WebPAnimDecoderDelete(WebPAnimDecoder* dec) {
472   if (dec != NULL) {
473     WebPDemuxReleaseIterator(&dec->prev_iter_);
474     WebPDemuxDelete(dec->demux_);
475     WebPSafeFree(dec->curr_frame_);
476     WebPSafeFree(dec->prev_frame_disposed_);
477     WebPSafeFree(dec);
478   }
479 }
480