anim_encode.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. // Copyright 2014 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. // AnimEncoder implementation.
  11. //
  12. #include <assert.h>
  13. #include <limits.h>
  14. #include <math.h> // for pow()
  15. #include <stdio.h>
  16. #include <stdlib.h> // for abs()
  17. #include "./animi.h"
  18. #include "../utils/utils.h"
  19. #include "../webp/decode.h"
  20. #include "../webp/encode.h"
  21. #include "../webp/format_constants.h"
  22. #include "../webp/mux.h"
  23. #if defined(_MSC_VER) && _MSC_VER < 1900
  24. #define snprintf _snprintf
  25. #endif
  26. #define ERROR_STR_MAX_LENGTH 100
  27. //------------------------------------------------------------------------------
  28. // Internal structs.
  29. // Stores frame rectangle dimensions.
  30. typedef struct {
  31. int x_offset_, y_offset_, width_, height_;
  32. } FrameRectangle;
  33. // Used to store two candidates of encoded data for an animation frame. One of
  34. // the two will be chosen later.
  35. typedef struct {
  36. WebPMuxFrameInfo sub_frame_; // Encoded frame rectangle.
  37. WebPMuxFrameInfo key_frame_; // Encoded frame if it is a key-frame.
  38. int is_key_frame_; // True if 'key_frame' has been chosen.
  39. } EncodedFrame;
  40. struct WebPAnimEncoder {
  41. const int canvas_width_; // Canvas width.
  42. const int canvas_height_; // Canvas height.
  43. const WebPAnimEncoderOptions options_; // Global encoding options.
  44. FrameRectangle prev_rect_; // Previous WebP frame rectangle.
  45. WebPConfig last_config_; // Cached in case a re-encode is needed.
  46. WebPConfig last_config_reversed_; // If 'last_config_' uses lossless, then
  47. // this config uses lossy and vice versa;
  48. // only valid if 'options_.allow_mixed'
  49. // is true.
  50. WebPPicture* curr_canvas_; // Only pointer; we don't own memory.
  51. // Canvas buffers.
  52. WebPPicture curr_canvas_copy_; // Possibly modified current canvas.
  53. int curr_canvas_copy_modified_; // True if pixels in 'curr_canvas_copy_'
  54. // differ from those in 'curr_canvas_'.
  55. WebPPicture prev_canvas_; // Previous canvas.
  56. WebPPicture prev_canvas_disposed_; // Previous canvas disposed to background.
  57. // Encoded data.
  58. EncodedFrame* encoded_frames_; // Array of encoded frames.
  59. size_t size_; // Number of allocated frames.
  60. size_t start_; // Frame start index.
  61. size_t count_; // Number of valid frames.
  62. size_t flush_count_; // If >0, 'flush_count' frames starting from
  63. // 'start' are ready to be added to mux.
  64. // key-frame related.
  65. int64_t best_delta_; // min(canvas size - frame size) over the frames.
  66. // Can be negative in certain cases due to
  67. // transparent pixels in a frame.
  68. int keyframe_; // Index of selected key-frame relative to 'start_'.
  69. int count_since_key_frame_; // Frames seen since the last key-frame.
  70. int first_timestamp_; // Timestamp of the first frame.
  71. int prev_timestamp_; // Timestamp of the last added frame.
  72. int prev_candidate_undecided_; // True if it's not yet decided if previous
  73. // frame would be a sub-frame or a key-frame.
  74. // Misc.
  75. int is_first_frame_; // True if first frame is yet to be added/being added.
  76. int got_null_frame_; // True if WebPAnimEncoderAdd() has already been called
  77. // with a NULL frame.
  78. size_t in_frame_count_; // Number of input frames processed so far.
  79. size_t out_frame_count_; // Number of frames added to mux so far. This may be
  80. // different from 'in_frame_count_' due to merging.
  81. WebPMux* mux_; // Muxer to assemble the WebP bitstream.
  82. char error_str_[ERROR_STR_MAX_LENGTH]; // Error string. Empty if no error.
  83. };
  84. // -----------------------------------------------------------------------------
  85. // Life of WebPAnimEncoder object.
  86. #define DELTA_INFINITY (1ULL << 32)
  87. #define KEYFRAME_NONE (-1)
  88. // Reset the counters in the WebPAnimEncoder.
  89. static void ResetCounters(WebPAnimEncoder* const enc) {
  90. enc->start_ = 0;
  91. enc->count_ = 0;
  92. enc->flush_count_ = 0;
  93. enc->best_delta_ = DELTA_INFINITY;
  94. enc->keyframe_ = KEYFRAME_NONE;
  95. }
  96. static void DisableKeyframes(WebPAnimEncoderOptions* const enc_options) {
  97. enc_options->kmax = INT_MAX;
  98. enc_options->kmin = enc_options->kmax - 1;
  99. }
  100. #define MAX_CACHED_FRAMES 30
  101. static void SanitizeEncoderOptions(WebPAnimEncoderOptions* const enc_options) {
  102. int print_warning = enc_options->verbose;
  103. if (enc_options->minimize_size) {
  104. DisableKeyframes(enc_options);
  105. }
  106. if (enc_options->kmax == 1) { // All frames will be key-frames.
  107. enc_options->kmin = 0;
  108. enc_options->kmax = 0;
  109. return;
  110. } else if (enc_options->kmax <= 0) {
  111. DisableKeyframes(enc_options);
  112. print_warning = 0;
  113. }
  114. if (enc_options->kmin >= enc_options->kmax) {
  115. enc_options->kmin = enc_options->kmax - 1;
  116. if (print_warning) {
  117. fprintf(stderr, "WARNING: Setting kmin = %d, so that kmin < kmax.\n",
  118. enc_options->kmin);
  119. }
  120. } else {
  121. const int kmin_limit = enc_options->kmax / 2 + 1;
  122. if (enc_options->kmin < kmin_limit && kmin_limit < enc_options->kmax) {
  123. // This ensures that enc.keyframe + kmin >= kmax is always true. So, we
  124. // can flush all the frames in the 'count_since_key_frame == kmax' case.
  125. enc_options->kmin = kmin_limit;
  126. if (print_warning) {
  127. fprintf(stderr,
  128. "WARNING: Setting kmin = %d, so that kmin >= kmax / 2 + 1.\n",
  129. enc_options->kmin);
  130. }
  131. }
  132. }
  133. // Limit the max number of frames that are allocated.
  134. if (enc_options->kmax - enc_options->kmin > MAX_CACHED_FRAMES) {
  135. enc_options->kmin = enc_options->kmax - MAX_CACHED_FRAMES;
  136. if (print_warning) {
  137. fprintf(stderr,
  138. "WARNING: Setting kmin = %d, so that kmax - kmin <= %d.\n",
  139. enc_options->kmin, MAX_CACHED_FRAMES);
  140. }
  141. }
  142. assert(enc_options->kmin < enc_options->kmax);
  143. }
  144. #undef MAX_CACHED_FRAMES
  145. static void DefaultEncoderOptions(WebPAnimEncoderOptions* const enc_options) {
  146. enc_options->anim_params.loop_count = 0;
  147. enc_options->anim_params.bgcolor = 0xffffffff; // White.
  148. enc_options->minimize_size = 0;
  149. DisableKeyframes(enc_options);
  150. enc_options->allow_mixed = 0;
  151. enc_options->verbose = 0;
  152. }
  153. int WebPAnimEncoderOptionsInitInternal(WebPAnimEncoderOptions* enc_options,
  154. int abi_version) {
  155. if (enc_options == NULL ||
  156. WEBP_ABI_IS_INCOMPATIBLE(abi_version, WEBP_MUX_ABI_VERSION)) {
  157. return 0;
  158. }
  159. DefaultEncoderOptions(enc_options);
  160. return 1;
  161. }
  162. // This starting value is more fit to WebPCleanupTransparentAreaLossless().
  163. #define TRANSPARENT_COLOR 0x00000000
  164. static void ClearRectangle(WebPPicture* const picture,
  165. int left, int top, int width, int height) {
  166. int j;
  167. for (j = top; j < top + height; ++j) {
  168. uint32_t* const dst = picture->argb + j * picture->argb_stride;
  169. int i;
  170. for (i = left; i < left + width; ++i) {
  171. dst[i] = TRANSPARENT_COLOR;
  172. }
  173. }
  174. }
  175. static void WebPUtilClearPic(WebPPicture* const picture,
  176. const FrameRectangle* const rect) {
  177. if (rect != NULL) {
  178. ClearRectangle(picture, rect->x_offset_, rect->y_offset_,
  179. rect->width_, rect->height_);
  180. } else {
  181. ClearRectangle(picture, 0, 0, picture->width, picture->height);
  182. }
  183. }
  184. static void MarkNoError(WebPAnimEncoder* const enc) {
  185. enc->error_str_[0] = '\0'; // Empty string.
  186. }
  187. static void MarkError(WebPAnimEncoder* const enc, const char* str) {
  188. if (snprintf(enc->error_str_, ERROR_STR_MAX_LENGTH, "%s.", str) < 0) {
  189. assert(0); // FIX ME!
  190. }
  191. }
  192. static void MarkError2(WebPAnimEncoder* const enc,
  193. const char* str, int error_code) {
  194. if (snprintf(enc->error_str_, ERROR_STR_MAX_LENGTH, "%s: %d.", str,
  195. error_code) < 0) {
  196. assert(0); // FIX ME!
  197. }
  198. }
  199. WebPAnimEncoder* WebPAnimEncoderNewInternal(
  200. int width, int height, const WebPAnimEncoderOptions* enc_options,
  201. int abi_version) {
  202. WebPAnimEncoder* enc;
  203. if (WEBP_ABI_IS_INCOMPATIBLE(abi_version, WEBP_MUX_ABI_VERSION)) {
  204. return NULL;
  205. }
  206. if (width <= 0 || height <= 0 ||
  207. (width * (uint64_t)height) >= MAX_IMAGE_AREA) {
  208. return NULL;
  209. }
  210. enc = (WebPAnimEncoder*)WebPSafeCalloc(1, sizeof(*enc));
  211. if (enc == NULL) return NULL;
  212. MarkNoError(enc);
  213. // Dimensions and options.
  214. *(int*)&enc->canvas_width_ = width;
  215. *(int*)&enc->canvas_height_ = height;
  216. if (enc_options != NULL) {
  217. *(WebPAnimEncoderOptions*)&enc->options_ = *enc_options;
  218. SanitizeEncoderOptions((WebPAnimEncoderOptions*)&enc->options_);
  219. } else {
  220. DefaultEncoderOptions((WebPAnimEncoderOptions*)&enc->options_);
  221. }
  222. // Canvas buffers.
  223. if (!WebPPictureInit(&enc->curr_canvas_copy_) ||
  224. !WebPPictureInit(&enc->prev_canvas_) ||
  225. !WebPPictureInit(&enc->prev_canvas_disposed_)) {
  226. goto Err;
  227. }
  228. enc->curr_canvas_copy_.width = width;
  229. enc->curr_canvas_copy_.height = height;
  230. enc->curr_canvas_copy_.use_argb = 1;
  231. if (!WebPPictureAlloc(&enc->curr_canvas_copy_) ||
  232. !WebPPictureCopy(&enc->curr_canvas_copy_, &enc->prev_canvas_) ||
  233. !WebPPictureCopy(&enc->curr_canvas_copy_, &enc->prev_canvas_disposed_)) {
  234. goto Err;
  235. }
  236. WebPUtilClearPic(&enc->prev_canvas_, NULL);
  237. enc->curr_canvas_copy_modified_ = 1;
  238. // Encoded frames.
  239. ResetCounters(enc);
  240. // Note: one extra storage is for the previous frame.
  241. enc->size_ = enc->options_.kmax - enc->options_.kmin + 1;
  242. // We need space for at least 2 frames. But when kmin, kmax are both zero,
  243. // enc->size_ will be 1. So we handle that special case below.
  244. if (enc->size_ < 2) enc->size_ = 2;
  245. enc->encoded_frames_ =
  246. (EncodedFrame*)WebPSafeCalloc(enc->size_, sizeof(*enc->encoded_frames_));
  247. if (enc->encoded_frames_ == NULL) goto Err;
  248. enc->mux_ = WebPMuxNew();
  249. if (enc->mux_ == NULL) goto Err;
  250. enc->count_since_key_frame_ = 0;
  251. enc->first_timestamp_ = 0;
  252. enc->prev_timestamp_ = 0;
  253. enc->prev_candidate_undecided_ = 0;
  254. enc->is_first_frame_ = 1;
  255. enc->got_null_frame_ = 0;
  256. return enc; // All OK.
  257. Err:
  258. WebPAnimEncoderDelete(enc);
  259. return NULL;
  260. }
  261. // Release the data contained by 'encoded_frame'.
  262. static void FrameRelease(EncodedFrame* const encoded_frame) {
  263. if (encoded_frame != NULL) {
  264. WebPDataClear(&encoded_frame->sub_frame_.bitstream);
  265. WebPDataClear(&encoded_frame->key_frame_.bitstream);
  266. memset(encoded_frame, 0, sizeof(*encoded_frame));
  267. }
  268. }
  269. void WebPAnimEncoderDelete(WebPAnimEncoder* enc) {
  270. if (enc != NULL) {
  271. WebPPictureFree(&enc->curr_canvas_copy_);
  272. WebPPictureFree(&enc->prev_canvas_);
  273. WebPPictureFree(&enc->prev_canvas_disposed_);
  274. if (enc->encoded_frames_ != NULL) {
  275. size_t i;
  276. for (i = 0; i < enc->size_; ++i) {
  277. FrameRelease(&enc->encoded_frames_[i]);
  278. }
  279. WebPSafeFree(enc->encoded_frames_);
  280. }
  281. WebPMuxDelete(enc->mux_);
  282. WebPSafeFree(enc);
  283. }
  284. }
  285. // -----------------------------------------------------------------------------
  286. // Frame addition.
  287. // Returns cached frame at the given 'position'.
  288. static EncodedFrame* GetFrame(const WebPAnimEncoder* const enc,
  289. size_t position) {
  290. assert(enc->start_ + position < enc->size_);
  291. return &enc->encoded_frames_[enc->start_ + position];
  292. }
  293. typedef int (*ComparePixelsFunc)(const uint32_t*, int, const uint32_t*, int,
  294. int, int);
  295. // Returns true if 'length' number of pixels in 'src' and 'dst' are equal,
  296. // assuming the given step sizes between pixels.
  297. // 'max_allowed_diff' is unused and only there to allow function pointer use.
  298. static WEBP_INLINE int ComparePixelsLossless(const uint32_t* src, int src_step,
  299. const uint32_t* dst, int dst_step,
  300. int length, int max_allowed_diff) {
  301. (void)max_allowed_diff;
  302. assert(length > 0);
  303. while (length-- > 0) {
  304. if (*src != *dst) {
  305. return 0;
  306. }
  307. src += src_step;
  308. dst += dst_step;
  309. }
  310. return 1;
  311. }
  312. // Helper to check if each channel in 'src' and 'dst' is at most off by
  313. // 'max_allowed_diff'.
  314. static WEBP_INLINE int PixelsAreSimilar(uint32_t src, uint32_t dst,
  315. int max_allowed_diff) {
  316. const int src_a = (src >> 24) & 0xff;
  317. const int src_r = (src >> 16) & 0xff;
  318. const int src_g = (src >> 8) & 0xff;
  319. const int src_b = (src >> 0) & 0xff;
  320. const int dst_a = (dst >> 24) & 0xff;
  321. const int dst_r = (dst >> 16) & 0xff;
  322. const int dst_g = (dst >> 8) & 0xff;
  323. const int dst_b = (dst >> 0) & 0xff;
  324. return (src_a == dst_a) &&
  325. (abs(src_r - dst_r) * dst_a <= (max_allowed_diff * 255)) &&
  326. (abs(src_g - dst_g) * dst_a <= (max_allowed_diff * 255)) &&
  327. (abs(src_b - dst_b) * dst_a <= (max_allowed_diff * 255));
  328. }
  329. // Returns true if 'length' number of pixels in 'src' and 'dst' are within an
  330. // error bound, assuming the given step sizes between pixels.
  331. static WEBP_INLINE int ComparePixelsLossy(const uint32_t* src, int src_step,
  332. const uint32_t* dst, int dst_step,
  333. int length, int max_allowed_diff) {
  334. assert(length > 0);
  335. while (length-- > 0) {
  336. if (!PixelsAreSimilar(*src, *dst, max_allowed_diff)) {
  337. return 0;
  338. }
  339. src += src_step;
  340. dst += dst_step;
  341. }
  342. return 1;
  343. }
  344. static int IsEmptyRect(const FrameRectangle* const rect) {
  345. return (rect->width_ == 0) || (rect->height_ == 0);
  346. }
  347. static int QualityToMaxDiff(float quality) {
  348. const double val = pow(quality / 100., 0.5);
  349. const double max_diff = 31 * (1 - val) + 1 * val;
  350. return (int)(max_diff + 0.5);
  351. }
  352. // Assumes that an initial valid guess of change rectangle 'rect' is passed.
  353. static void MinimizeChangeRectangle(const WebPPicture* const src,
  354. const WebPPicture* const dst,
  355. FrameRectangle* const rect,
  356. int is_lossless, float quality) {
  357. int i, j;
  358. const ComparePixelsFunc compare_pixels =
  359. is_lossless ? ComparePixelsLossless : ComparePixelsLossy;
  360. const int max_allowed_diff_lossy = QualityToMaxDiff(quality);
  361. const int max_allowed_diff = is_lossless ? 0 : max_allowed_diff_lossy;
  362. // Assumption/correctness checks.
  363. assert(src->width == dst->width && src->height == dst->height);
  364. assert(rect->x_offset_ + rect->width_ <= dst->width);
  365. assert(rect->y_offset_ + rect->height_ <= dst->height);
  366. // Left boundary.
  367. for (i = rect->x_offset_; i < rect->x_offset_ + rect->width_; ++i) {
  368. const uint32_t* const src_argb =
  369. &src->argb[rect->y_offset_ * src->argb_stride + i];
  370. const uint32_t* const dst_argb =
  371. &dst->argb[rect->y_offset_ * dst->argb_stride + i];
  372. if (compare_pixels(src_argb, src->argb_stride, dst_argb, dst->argb_stride,
  373. rect->height_, max_allowed_diff)) {
  374. --rect->width_; // Redundant column.
  375. ++rect->x_offset_;
  376. } else {
  377. break;
  378. }
  379. }
  380. if (rect->width_ == 0) goto NoChange;
  381. // Right boundary.
  382. for (i = rect->x_offset_ + rect->width_ - 1; i >= rect->x_offset_; --i) {
  383. const uint32_t* const src_argb =
  384. &src->argb[rect->y_offset_ * src->argb_stride + i];
  385. const uint32_t* const dst_argb =
  386. &dst->argb[rect->y_offset_ * dst->argb_stride + i];
  387. if (compare_pixels(src_argb, src->argb_stride, dst_argb, dst->argb_stride,
  388. rect->height_, max_allowed_diff)) {
  389. --rect->width_; // Redundant column.
  390. } else {
  391. break;
  392. }
  393. }
  394. if (rect->width_ == 0) goto NoChange;
  395. // Top boundary.
  396. for (j = rect->y_offset_; j < rect->y_offset_ + rect->height_; ++j) {
  397. const uint32_t* const src_argb =
  398. &src->argb[j * src->argb_stride + rect->x_offset_];
  399. const uint32_t* const dst_argb =
  400. &dst->argb[j * dst->argb_stride + rect->x_offset_];
  401. if (compare_pixels(src_argb, 1, dst_argb, 1, rect->width_,
  402. max_allowed_diff)) {
  403. --rect->height_; // Redundant row.
  404. ++rect->y_offset_;
  405. } else {
  406. break;
  407. }
  408. }
  409. if (rect->height_ == 0) goto NoChange;
  410. // Bottom boundary.
  411. for (j = rect->y_offset_ + rect->height_ - 1; j >= rect->y_offset_; --j) {
  412. const uint32_t* const src_argb =
  413. &src->argb[j * src->argb_stride + rect->x_offset_];
  414. const uint32_t* const dst_argb =
  415. &dst->argb[j * dst->argb_stride + rect->x_offset_];
  416. if (compare_pixels(src_argb, 1, dst_argb, 1, rect->width_,
  417. max_allowed_diff)) {
  418. --rect->height_; // Redundant row.
  419. } else {
  420. break;
  421. }
  422. }
  423. if (rect->height_ == 0) goto NoChange;
  424. if (IsEmptyRect(rect)) {
  425. NoChange:
  426. rect->x_offset_ = 0;
  427. rect->y_offset_ = 0;
  428. rect->width_ = 0;
  429. rect->height_ = 0;
  430. }
  431. }
  432. // Snap rectangle to even offsets (and adjust dimensions if needed).
  433. static WEBP_INLINE void SnapToEvenOffsets(FrameRectangle* const rect) {
  434. rect->width_ += (rect->x_offset_ & 1);
  435. rect->height_ += (rect->y_offset_ & 1);
  436. rect->x_offset_ &= ~1;
  437. rect->y_offset_ &= ~1;
  438. }
  439. typedef struct {
  440. int should_try_; // Should try this set of parameters.
  441. int empty_rect_allowed_; // Frame with empty rectangle can be skipped.
  442. FrameRectangle rect_ll_; // Frame rectangle for lossless compression.
  443. WebPPicture sub_frame_ll_; // Sub-frame pic for lossless compression.
  444. FrameRectangle rect_lossy_; // Frame rectangle for lossy compression.
  445. // Could be smaller than rect_ll_ as pixels
  446. // with small diffs can be ignored.
  447. WebPPicture sub_frame_lossy_; // Sub-frame pic for lossless compression.
  448. } SubFrameParams;
  449. static int SubFrameParamsInit(SubFrameParams* const params,
  450. int should_try, int empty_rect_allowed) {
  451. params->should_try_ = should_try;
  452. params->empty_rect_allowed_ = empty_rect_allowed;
  453. if (!WebPPictureInit(&params->sub_frame_ll_) ||
  454. !WebPPictureInit(&params->sub_frame_lossy_)) {
  455. return 0;
  456. }
  457. return 1;
  458. }
  459. static void SubFrameParamsFree(SubFrameParams* const params) {
  460. WebPPictureFree(&params->sub_frame_ll_);
  461. WebPPictureFree(&params->sub_frame_lossy_);
  462. }
  463. // Given previous and current canvas, picks the optimal rectangle for the
  464. // current frame based on 'is_lossless' and other parameters. Assumes that the
  465. // initial guess 'rect' is valid.
  466. static int GetSubRect(const WebPPicture* const prev_canvas,
  467. const WebPPicture* const curr_canvas, int is_key_frame,
  468. int is_first_frame, int empty_rect_allowed,
  469. int is_lossless, float quality,
  470. FrameRectangle* const rect,
  471. WebPPicture* const sub_frame) {
  472. if (!is_key_frame || is_first_frame) { // Optimize frame rectangle.
  473. // Note: This behaves as expected for first frame, as 'prev_canvas' is
  474. // initialized to a fully transparent canvas in the beginning.
  475. MinimizeChangeRectangle(prev_canvas, curr_canvas, rect,
  476. is_lossless, quality);
  477. }
  478. if (IsEmptyRect(rect)) {
  479. if (empty_rect_allowed) { // No need to get 'sub_frame'.
  480. return 1;
  481. } else { // Force a 1x1 rectangle.
  482. rect->width_ = 1;
  483. rect->height_ = 1;
  484. assert(rect->x_offset_ == 0);
  485. assert(rect->y_offset_ == 0);
  486. }
  487. }
  488. SnapToEvenOffsets(rect);
  489. return WebPPictureView(curr_canvas, rect->x_offset_, rect->y_offset_,
  490. rect->width_, rect->height_, sub_frame);
  491. }
  492. // Picks optimal frame rectangle for both lossless and lossy compression. The
  493. // initial guess for frame rectangles will be the full canvas.
  494. static int GetSubRects(const WebPPicture* const prev_canvas,
  495. const WebPPicture* const curr_canvas, int is_key_frame,
  496. int is_first_frame, float quality,
  497. SubFrameParams* const params) {
  498. // Lossless frame rectangle.
  499. params->rect_ll_.x_offset_ = 0;
  500. params->rect_ll_.y_offset_ = 0;
  501. params->rect_ll_.width_ = curr_canvas->width;
  502. params->rect_ll_.height_ = curr_canvas->height;
  503. if (!GetSubRect(prev_canvas, curr_canvas, is_key_frame, is_first_frame,
  504. params->empty_rect_allowed_, 1, quality,
  505. &params->rect_ll_, &params->sub_frame_ll_)) {
  506. return 0;
  507. }
  508. // Lossy frame rectangle.
  509. params->rect_lossy_ = params->rect_ll_; // seed with lossless rect.
  510. return GetSubRect(prev_canvas, curr_canvas, is_key_frame, is_first_frame,
  511. params->empty_rect_allowed_, 0, quality,
  512. &params->rect_lossy_, &params->sub_frame_lossy_);
  513. }
  514. static WEBP_INLINE int clip(int v, int min_v, int max_v) {
  515. return (v < min_v) ? min_v : (v > max_v) ? max_v : v;
  516. }
  517. int WebPAnimEncoderRefineRect(
  518. const WebPPicture* const prev_canvas, const WebPPicture* const curr_canvas,
  519. int is_lossless, float quality, int* const x_offset, int* const y_offset,
  520. int* const width, int* const height) {
  521. FrameRectangle rect;
  522. const int right = clip(*x_offset + *width, 0, curr_canvas->width);
  523. const int left = clip(*x_offset, 0, curr_canvas->width - 1);
  524. const int bottom = clip(*y_offset + *height, 0, curr_canvas->height);
  525. const int top = clip(*y_offset, 0, curr_canvas->height - 1);
  526. if (prev_canvas == NULL || curr_canvas == NULL ||
  527. prev_canvas->width != curr_canvas->width ||
  528. prev_canvas->height != curr_canvas->height ||
  529. !prev_canvas->use_argb || !curr_canvas->use_argb) {
  530. return 0;
  531. }
  532. rect.x_offset_ = left;
  533. rect.y_offset_ = top;
  534. rect.width_ = clip(right - left, 0, curr_canvas->width - rect.x_offset_);
  535. rect.height_ = clip(bottom - top, 0, curr_canvas->height - rect.y_offset_);
  536. MinimizeChangeRectangle(prev_canvas, curr_canvas, &rect, is_lossless,
  537. quality);
  538. SnapToEvenOffsets(&rect);
  539. *x_offset = rect.x_offset_;
  540. *y_offset = rect.y_offset_;
  541. *width = rect.width_;
  542. *height = rect.height_;
  543. return 1;
  544. }
  545. static void DisposeFrameRectangle(int dispose_method,
  546. const FrameRectangle* const rect,
  547. WebPPicture* const curr_canvas) {
  548. assert(rect != NULL);
  549. if (dispose_method == WEBP_MUX_DISPOSE_BACKGROUND) {
  550. WebPUtilClearPic(curr_canvas, rect);
  551. }
  552. }
  553. static uint32_t RectArea(const FrameRectangle* const rect) {
  554. return (uint32_t)rect->width_ * rect->height_;
  555. }
  556. static int IsLosslessBlendingPossible(const WebPPicture* const src,
  557. const WebPPicture* const dst,
  558. const FrameRectangle* const rect) {
  559. int i, j;
  560. assert(src->width == dst->width && src->height == dst->height);
  561. assert(rect->x_offset_ + rect->width_ <= dst->width);
  562. assert(rect->y_offset_ + rect->height_ <= dst->height);
  563. for (j = rect->y_offset_; j < rect->y_offset_ + rect->height_; ++j) {
  564. for (i = rect->x_offset_; i < rect->x_offset_ + rect->width_; ++i) {
  565. const uint32_t src_pixel = src->argb[j * src->argb_stride + i];
  566. const uint32_t dst_pixel = dst->argb[j * dst->argb_stride + i];
  567. const uint32_t dst_alpha = dst_pixel >> 24;
  568. if (dst_alpha != 0xff && src_pixel != dst_pixel) {
  569. // In this case, if we use blending, we can't attain the desired
  570. // 'dst_pixel' value for this pixel. So, blending is not possible.
  571. return 0;
  572. }
  573. }
  574. }
  575. return 1;
  576. }
  577. static int IsLossyBlendingPossible(const WebPPicture* const src,
  578. const WebPPicture* const dst,
  579. const FrameRectangle* const rect,
  580. float quality) {
  581. const int max_allowed_diff_lossy = QualityToMaxDiff(quality);
  582. int i, j;
  583. assert(src->width == dst->width && src->height == dst->height);
  584. assert(rect->x_offset_ + rect->width_ <= dst->width);
  585. assert(rect->y_offset_ + rect->height_ <= dst->height);
  586. for (j = rect->y_offset_; j < rect->y_offset_ + rect->height_; ++j) {
  587. for (i = rect->x_offset_; i < rect->x_offset_ + rect->width_; ++i) {
  588. const uint32_t src_pixel = src->argb[j * src->argb_stride + i];
  589. const uint32_t dst_pixel = dst->argb[j * dst->argb_stride + i];
  590. const uint32_t dst_alpha = dst_pixel >> 24;
  591. if (dst_alpha != 0xff &&
  592. !PixelsAreSimilar(src_pixel, dst_pixel, max_allowed_diff_lossy)) {
  593. // In this case, if we use blending, we can't attain the desired
  594. // 'dst_pixel' value for this pixel. So, blending is not possible.
  595. return 0;
  596. }
  597. }
  598. }
  599. return 1;
  600. }
  601. // For pixels in 'rect', replace those pixels in 'dst' that are same as 'src' by
  602. // transparent pixels.
  603. // Returns true if at least one pixel gets modified.
  604. static int IncreaseTransparency(const WebPPicture* const src,
  605. const FrameRectangle* const rect,
  606. WebPPicture* const dst) {
  607. int i, j;
  608. int modified = 0;
  609. assert(src != NULL && dst != NULL && rect != NULL);
  610. assert(src->width == dst->width && src->height == dst->height);
  611. for (j = rect->y_offset_; j < rect->y_offset_ + rect->height_; ++j) {
  612. const uint32_t* const psrc = src->argb + j * src->argb_stride;
  613. uint32_t* const pdst = dst->argb + j * dst->argb_stride;
  614. for (i = rect->x_offset_; i < rect->x_offset_ + rect->width_; ++i) {
  615. if (psrc[i] == pdst[i] && pdst[i] != TRANSPARENT_COLOR) {
  616. pdst[i] = TRANSPARENT_COLOR;
  617. modified = 1;
  618. }
  619. }
  620. }
  621. return modified;
  622. }
  623. #undef TRANSPARENT_COLOR
  624. // Replace similar blocks of pixels by a 'see-through' transparent block
  625. // with uniform average color.
  626. // Assumes lossy compression is being used.
  627. // Returns true if at least one pixel gets modified.
  628. static int FlattenSimilarBlocks(const WebPPicture* const src,
  629. const FrameRectangle* const rect,
  630. WebPPicture* const dst, float quality) {
  631. const int max_allowed_diff_lossy = QualityToMaxDiff(quality);
  632. int i, j;
  633. int modified = 0;
  634. const int block_size = 8;
  635. const int y_start = (rect->y_offset_ + block_size) & ~(block_size - 1);
  636. const int y_end = (rect->y_offset_ + rect->height_) & ~(block_size - 1);
  637. const int x_start = (rect->x_offset_ + block_size) & ~(block_size - 1);
  638. const int x_end = (rect->x_offset_ + rect->width_) & ~(block_size - 1);
  639. assert(src != NULL && dst != NULL && rect != NULL);
  640. assert(src->width == dst->width && src->height == dst->height);
  641. assert((block_size & (block_size - 1)) == 0); // must be a power of 2
  642. // Iterate over each block and count similar pixels.
  643. for (j = y_start; j < y_end; j += block_size) {
  644. for (i = x_start; i < x_end; i += block_size) {
  645. int cnt = 0;
  646. int avg_r = 0, avg_g = 0, avg_b = 0;
  647. int x, y;
  648. const uint32_t* const psrc = src->argb + j * src->argb_stride + i;
  649. uint32_t* const pdst = dst->argb + j * dst->argb_stride + i;
  650. for (y = 0; y < block_size; ++y) {
  651. for (x = 0; x < block_size; ++x) {
  652. const uint32_t src_pixel = psrc[x + y * src->argb_stride];
  653. const int alpha = src_pixel >> 24;
  654. if (alpha == 0xff &&
  655. PixelsAreSimilar(src_pixel, pdst[x + y * dst->argb_stride],
  656. max_allowed_diff_lossy)) {
  657. ++cnt;
  658. avg_r += (src_pixel >> 16) & 0xff;
  659. avg_g += (src_pixel >> 8) & 0xff;
  660. avg_b += (src_pixel >> 0) & 0xff;
  661. }
  662. }
  663. }
  664. // If we have a fully similar block, we replace it with an
  665. // average transparent block. This compresses better in lossy mode.
  666. if (cnt == block_size * block_size) {
  667. const uint32_t color = (0x00 << 24) |
  668. ((avg_r / cnt) << 16) |
  669. ((avg_g / cnt) << 8) |
  670. ((avg_b / cnt) << 0);
  671. for (y = 0; y < block_size; ++y) {
  672. for (x = 0; x < block_size; ++x) {
  673. pdst[x + y * dst->argb_stride] = color;
  674. }
  675. }
  676. modified = 1;
  677. }
  678. }
  679. }
  680. return modified;
  681. }
  682. static int EncodeFrame(const WebPConfig* const config, WebPPicture* const pic,
  683. WebPMemoryWriter* const memory) {
  684. pic->use_argb = 1;
  685. pic->writer = WebPMemoryWrite;
  686. pic->custom_ptr = memory;
  687. if (!WebPEncode(config, pic)) {
  688. return 0;
  689. }
  690. return 1;
  691. }
  692. // Struct representing a candidate encoded frame including its metadata.
  693. typedef struct {
  694. WebPMemoryWriter mem_;
  695. WebPMuxFrameInfo info_;
  696. FrameRectangle rect_;
  697. int evaluate_; // True if this candidate should be evaluated.
  698. } Candidate;
  699. // Generates a candidate encoded frame given a picture and metadata.
  700. static WebPEncodingError EncodeCandidate(WebPPicture* const sub_frame,
  701. const FrameRectangle* const rect,
  702. const WebPConfig* const encoder_config,
  703. int use_blending,
  704. Candidate* const candidate) {
  705. WebPConfig config = *encoder_config;
  706. WebPEncodingError error_code = VP8_ENC_OK;
  707. assert(candidate != NULL);
  708. memset(candidate, 0, sizeof(*candidate));
  709. // Set frame rect and info.
  710. candidate->rect_ = *rect;
  711. candidate->info_.id = WEBP_CHUNK_ANMF;
  712. candidate->info_.x_offset = rect->x_offset_;
  713. candidate->info_.y_offset = rect->y_offset_;
  714. candidate->info_.dispose_method = WEBP_MUX_DISPOSE_NONE; // Set later.
  715. candidate->info_.blend_method =
  716. use_blending ? WEBP_MUX_BLEND : WEBP_MUX_NO_BLEND;
  717. candidate->info_.duration = 0; // Set in next call to WebPAnimEncoderAdd().
  718. // Encode picture.
  719. WebPMemoryWriterInit(&candidate->mem_);
  720. if (!config.lossless && use_blending) {
  721. // Disable filtering to avoid blockiness in reconstructed frames at the
  722. // time of decoding.
  723. config.autofilter = 0;
  724. config.filter_strength = 0;
  725. }
  726. if (!EncodeFrame(&config, sub_frame, &candidate->mem_)) {
  727. error_code = sub_frame->error_code;
  728. goto Err;
  729. }
  730. candidate->evaluate_ = 1;
  731. return error_code;
  732. Err:
  733. WebPMemoryWriterClear(&candidate->mem_);
  734. return error_code;
  735. }
  736. static void CopyCurrentCanvas(WebPAnimEncoder* const enc) {
  737. if (enc->curr_canvas_copy_modified_) {
  738. WebPCopyPixels(enc->curr_canvas_, &enc->curr_canvas_copy_);
  739. enc->curr_canvas_copy_.progress_hook = enc->curr_canvas_->progress_hook;
  740. enc->curr_canvas_copy_.user_data = enc->curr_canvas_->user_data;
  741. enc->curr_canvas_copy_modified_ = 0;
  742. }
  743. }
  744. enum {
  745. LL_DISP_NONE = 0,
  746. LL_DISP_BG,
  747. LOSSY_DISP_NONE,
  748. LOSSY_DISP_BG,
  749. CANDIDATE_COUNT
  750. };
  751. #define MIN_COLORS_LOSSY 31 // Don't try lossy below this threshold.
  752. #define MAX_COLORS_LOSSLESS 194 // Don't try lossless above this threshold.
  753. // Generates candidates for a given dispose method given pre-filled sub-frame
  754. // 'params'.
  755. static WebPEncodingError GenerateCandidates(
  756. WebPAnimEncoder* const enc, Candidate candidates[CANDIDATE_COUNT],
  757. WebPMuxAnimDispose dispose_method, int is_lossless, int is_key_frame,
  758. SubFrameParams* const params,
  759. const WebPConfig* const config_ll, const WebPConfig* const config_lossy) {
  760. WebPEncodingError error_code = VP8_ENC_OK;
  761. const int is_dispose_none = (dispose_method == WEBP_MUX_DISPOSE_NONE);
  762. Candidate* const candidate_ll =
  763. is_dispose_none ? &candidates[LL_DISP_NONE] : &candidates[LL_DISP_BG];
  764. Candidate* const candidate_lossy = is_dispose_none
  765. ? &candidates[LOSSY_DISP_NONE]
  766. : &candidates[LOSSY_DISP_BG];
  767. WebPPicture* const curr_canvas = &enc->curr_canvas_copy_;
  768. const WebPPicture* const prev_canvas =
  769. is_dispose_none ? &enc->prev_canvas_ : &enc->prev_canvas_disposed_;
  770. int use_blending_ll, use_blending_lossy;
  771. int evaluate_ll, evaluate_lossy;
  772. CopyCurrentCanvas(enc);
  773. use_blending_ll =
  774. !is_key_frame &&
  775. IsLosslessBlendingPossible(prev_canvas, curr_canvas, &params->rect_ll_);
  776. use_blending_lossy =
  777. !is_key_frame &&
  778. IsLossyBlendingPossible(prev_canvas, curr_canvas, &params->rect_lossy_,
  779. config_lossy->quality);
  780. // Pick candidates to be tried.
  781. if (!enc->options_.allow_mixed) {
  782. evaluate_ll = is_lossless;
  783. evaluate_lossy = !is_lossless;
  784. } else if (enc->options_.minimize_size) {
  785. evaluate_ll = 1;
  786. evaluate_lossy = 1;
  787. } else { // Use a heuristic for trying lossless and/or lossy compression.
  788. const int num_colors = WebPGetColorPalette(&params->sub_frame_ll_, NULL);
  789. evaluate_ll = (num_colors < MAX_COLORS_LOSSLESS);
  790. evaluate_lossy = (num_colors >= MIN_COLORS_LOSSY);
  791. }
  792. // Generate candidates.
  793. if (evaluate_ll) {
  794. CopyCurrentCanvas(enc);
  795. if (use_blending_ll) {
  796. enc->curr_canvas_copy_modified_ =
  797. IncreaseTransparency(prev_canvas, &params->rect_ll_, curr_canvas);
  798. }
  799. error_code = EncodeCandidate(&params->sub_frame_ll_, &params->rect_ll_,
  800. config_ll, use_blending_ll, candidate_ll);
  801. if (error_code != VP8_ENC_OK) return error_code;
  802. }
  803. if (evaluate_lossy) {
  804. CopyCurrentCanvas(enc);
  805. if (use_blending_lossy) {
  806. enc->curr_canvas_copy_modified_ =
  807. FlattenSimilarBlocks(prev_canvas, &params->rect_lossy_, curr_canvas,
  808. config_lossy->quality);
  809. }
  810. error_code =
  811. EncodeCandidate(&params->sub_frame_lossy_, &params->rect_lossy_,
  812. config_lossy, use_blending_lossy, candidate_lossy);
  813. if (error_code != VP8_ENC_OK) return error_code;
  814. enc->curr_canvas_copy_modified_ = 1;
  815. }
  816. return error_code;
  817. }
  818. #undef MIN_COLORS_LOSSY
  819. #undef MAX_COLORS_LOSSLESS
  820. static void GetEncodedData(const WebPMemoryWriter* const memory,
  821. WebPData* const encoded_data) {
  822. encoded_data->bytes = memory->mem;
  823. encoded_data->size = memory->size;
  824. }
  825. // Sets dispose method of the previous frame to be 'dispose_method'.
  826. static void SetPreviousDisposeMethod(WebPAnimEncoder* const enc,
  827. WebPMuxAnimDispose dispose_method) {
  828. const size_t position = enc->count_ - 2;
  829. EncodedFrame* const prev_enc_frame = GetFrame(enc, position);
  830. assert(enc->count_ >= 2); // As current and previous frames are in enc.
  831. if (enc->prev_candidate_undecided_) {
  832. assert(dispose_method == WEBP_MUX_DISPOSE_NONE);
  833. prev_enc_frame->sub_frame_.dispose_method = dispose_method;
  834. prev_enc_frame->key_frame_.dispose_method = dispose_method;
  835. } else {
  836. WebPMuxFrameInfo* const prev_info = prev_enc_frame->is_key_frame_
  837. ? &prev_enc_frame->key_frame_
  838. : &prev_enc_frame->sub_frame_;
  839. prev_info->dispose_method = dispose_method;
  840. }
  841. }
  842. static int IncreasePreviousDuration(WebPAnimEncoder* const enc, int duration) {
  843. const size_t position = enc->count_ - 1;
  844. EncodedFrame* const prev_enc_frame = GetFrame(enc, position);
  845. int new_duration;
  846. assert(enc->count_ >= 1);
  847. assert(!prev_enc_frame->is_key_frame_ ||
  848. prev_enc_frame->sub_frame_.duration ==
  849. prev_enc_frame->key_frame_.duration);
  850. assert(prev_enc_frame->sub_frame_.duration ==
  851. (prev_enc_frame->sub_frame_.duration & (MAX_DURATION - 1)));
  852. assert(duration == (duration & (MAX_DURATION - 1)));
  853. new_duration = prev_enc_frame->sub_frame_.duration + duration;
  854. if (new_duration >= MAX_DURATION) { // Special case.
  855. // Separate out previous frame from earlier merged frames to avoid overflow.
  856. // We add a 1x1 transparent frame for the previous frame, with blending on.
  857. const FrameRectangle rect = { 0, 0, 1, 1 };
  858. const uint8_t lossless_1x1_bytes[] = {
  859. 0x52, 0x49, 0x46, 0x46, 0x14, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
  860. 0x56, 0x50, 0x38, 0x4c, 0x08, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00,
  861. 0x10, 0x88, 0x88, 0x08
  862. };
  863. const WebPData lossless_1x1 = {
  864. lossless_1x1_bytes, sizeof(lossless_1x1_bytes)
  865. };
  866. const uint8_t lossy_1x1_bytes[] = {
  867. 0x52, 0x49, 0x46, 0x46, 0x40, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
  868. 0x56, 0x50, 0x38, 0x58, 0x0a, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
  869. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x4c, 0x50, 0x48, 0x02, 0x00,
  870. 0x00, 0x00, 0x00, 0x00, 0x56, 0x50, 0x38, 0x20, 0x18, 0x00, 0x00, 0x00,
  871. 0x30, 0x01, 0x00, 0x9d, 0x01, 0x2a, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00,
  872. 0x34, 0x25, 0xa4, 0x00, 0x03, 0x70, 0x00, 0xfe, 0xfb, 0xfd, 0x50, 0x00
  873. };
  874. const WebPData lossy_1x1 = { lossy_1x1_bytes, sizeof(lossy_1x1_bytes) };
  875. const int can_use_lossless =
  876. (enc->last_config_.lossless || enc->options_.allow_mixed);
  877. EncodedFrame* const curr_enc_frame = GetFrame(enc, enc->count_);
  878. curr_enc_frame->is_key_frame_ = 0;
  879. curr_enc_frame->sub_frame_.id = WEBP_CHUNK_ANMF;
  880. curr_enc_frame->sub_frame_.x_offset = 0;
  881. curr_enc_frame->sub_frame_.y_offset = 0;
  882. curr_enc_frame->sub_frame_.dispose_method = WEBP_MUX_DISPOSE_NONE;
  883. curr_enc_frame->sub_frame_.blend_method = WEBP_MUX_BLEND;
  884. curr_enc_frame->sub_frame_.duration = duration;
  885. if (!WebPDataCopy(can_use_lossless ? &lossless_1x1 : &lossy_1x1,
  886. &curr_enc_frame->sub_frame_.bitstream)) {
  887. return 0;
  888. }
  889. ++enc->count_;
  890. ++enc->count_since_key_frame_;
  891. enc->flush_count_ = enc->count_ - 1;
  892. enc->prev_candidate_undecided_ = 0;
  893. enc->prev_rect_ = rect;
  894. } else { // Regular case.
  895. // Increase duration of the previous frame by 'duration'.
  896. prev_enc_frame->sub_frame_.duration = new_duration;
  897. prev_enc_frame->key_frame_.duration = new_duration;
  898. }
  899. return 1;
  900. }
  901. // Pick the candidate encoded frame with smallest size and release other
  902. // candidates.
  903. // TODO(later): Perhaps a rough SSIM/PSNR produced by the encoder should
  904. // also be a criteria, in addition to sizes.
  905. static void PickBestCandidate(WebPAnimEncoder* const enc,
  906. Candidate* const candidates, int is_key_frame,
  907. EncodedFrame* const encoded_frame) {
  908. int i;
  909. int best_idx = -1;
  910. size_t best_size = ~0;
  911. for (i = 0; i < CANDIDATE_COUNT; ++i) {
  912. if (candidates[i].evaluate_) {
  913. const size_t candidate_size = candidates[i].mem_.size;
  914. if (candidate_size < best_size) {
  915. best_idx = i;
  916. best_size = candidate_size;
  917. }
  918. }
  919. }
  920. assert(best_idx != -1);
  921. for (i = 0; i < CANDIDATE_COUNT; ++i) {
  922. if (candidates[i].evaluate_) {
  923. if (i == best_idx) {
  924. WebPMuxFrameInfo* const dst = is_key_frame
  925. ? &encoded_frame->key_frame_
  926. : &encoded_frame->sub_frame_;
  927. *dst = candidates[i].info_;
  928. GetEncodedData(&candidates[i].mem_, &dst->bitstream);
  929. if (!is_key_frame) {
  930. // Note: Previous dispose method only matters for non-keyframes.
  931. // Also, we don't want to modify previous dispose method that was
  932. // selected when a non key-frame was assumed.
  933. const WebPMuxAnimDispose prev_dispose_method =
  934. (best_idx == LL_DISP_NONE || best_idx == LOSSY_DISP_NONE)
  935. ? WEBP_MUX_DISPOSE_NONE
  936. : WEBP_MUX_DISPOSE_BACKGROUND;
  937. SetPreviousDisposeMethod(enc, prev_dispose_method);
  938. }
  939. enc->prev_rect_ = candidates[i].rect_; // save for next frame.
  940. } else {
  941. WebPMemoryWriterClear(&candidates[i].mem_);
  942. candidates[i].evaluate_ = 0;
  943. }
  944. }
  945. }
  946. }
  947. // Depending on the configuration, tries different compressions
  948. // (lossy/lossless), dispose methods, blending methods etc to encode the current
  949. // frame and outputs the best one in 'encoded_frame'.
  950. // 'frame_skipped' will be set to true if this frame should actually be skipped.
  951. static WebPEncodingError SetFrame(WebPAnimEncoder* const enc,
  952. const WebPConfig* const config,
  953. int is_key_frame,
  954. EncodedFrame* const encoded_frame,
  955. int* const frame_skipped) {
  956. int i;
  957. WebPEncodingError error_code = VP8_ENC_OK;
  958. const WebPPicture* const curr_canvas = &enc->curr_canvas_copy_;
  959. const WebPPicture* const prev_canvas = &enc->prev_canvas_;
  960. Candidate candidates[CANDIDATE_COUNT];
  961. const int is_lossless = config->lossless;
  962. const int consider_lossless = is_lossless || enc->options_.allow_mixed;
  963. const int consider_lossy = !is_lossless || enc->options_.allow_mixed;
  964. const int is_first_frame = enc->is_first_frame_;
  965. // First frame cannot be skipped as there is no 'previous frame' to merge it
  966. // to. So, empty rectangle is not allowed for the first frame.
  967. const int empty_rect_allowed_none = !is_first_frame;
  968. // Even if there is exact pixel match between 'disposed previous canvas' and
  969. // 'current canvas', we can't skip current frame, as there may not be exact
  970. // pixel match between 'previous canvas' and 'current canvas'. So, we don't
  971. // allow empty rectangle in this case.
  972. const int empty_rect_allowed_bg = 0;
  973. // If current frame is a key-frame, dispose method of previous frame doesn't
  974. // matter, so we don't try dispose to background.
  975. // Also, if key-frame insertion is on, and previous frame could be picked as
  976. // either a sub-frame or a key-frame, then we can't be sure about what frame
  977. // rectangle would be disposed. In that case too, we don't try dispose to
  978. // background.
  979. const int dispose_bg_possible =
  980. !is_key_frame && !enc->prev_candidate_undecided_;
  981. SubFrameParams dispose_none_params;
  982. SubFrameParams dispose_bg_params;
  983. WebPConfig config_ll = *config;
  984. WebPConfig config_lossy = *config;
  985. config_ll.lossless = 1;
  986. config_lossy.lossless = 0;
  987. enc->last_config_ = *config;
  988. enc->last_config_reversed_ = config->lossless ? config_lossy : config_ll;
  989. *frame_skipped = 0;
  990. if (!SubFrameParamsInit(&dispose_none_params, 1, empty_rect_allowed_none) ||
  991. !SubFrameParamsInit(&dispose_bg_params, 0, empty_rect_allowed_bg)) {
  992. return VP8_ENC_ERROR_INVALID_CONFIGURATION;
  993. }
  994. memset(candidates, 0, sizeof(candidates));
  995. // Change-rectangle assuming previous frame was DISPOSE_NONE.
  996. if (!GetSubRects(prev_canvas, curr_canvas, is_key_frame, is_first_frame,
  997. config_lossy.quality, &dispose_none_params)) {
  998. error_code = VP8_ENC_ERROR_INVALID_CONFIGURATION;
  999. goto Err;
  1000. }
  1001. if ((consider_lossless && IsEmptyRect(&dispose_none_params.rect_ll_)) ||
  1002. (consider_lossy && IsEmptyRect(&dispose_none_params.rect_lossy_))) {
  1003. // Don't encode the frame at all. Instead, the duration of the previous
  1004. // frame will be increased later.
  1005. assert(empty_rect_allowed_none);
  1006. *frame_skipped = 1;
  1007. goto End;
  1008. }
  1009. if (dispose_bg_possible) {
  1010. // Change-rectangle assuming previous frame was DISPOSE_BACKGROUND.
  1011. WebPPicture* const prev_canvas_disposed = &enc->prev_canvas_disposed_;
  1012. WebPCopyPixels(prev_canvas, prev_canvas_disposed);
  1013. DisposeFrameRectangle(WEBP_MUX_DISPOSE_BACKGROUND, &enc->prev_rect_,
  1014. prev_canvas_disposed);
  1015. if (!GetSubRects(prev_canvas_disposed, curr_canvas, is_key_frame,
  1016. is_first_frame, config_lossy.quality,
  1017. &dispose_bg_params)) {
  1018. error_code = VP8_ENC_ERROR_INVALID_CONFIGURATION;
  1019. goto Err;
  1020. }
  1021. assert(!IsEmptyRect(&dispose_bg_params.rect_ll_));
  1022. assert(!IsEmptyRect(&dispose_bg_params.rect_lossy_));
  1023. if (enc->options_.minimize_size) { // Try both dispose methods.
  1024. dispose_bg_params.should_try_ = 1;
  1025. dispose_none_params.should_try_ = 1;
  1026. } else if ((is_lossless &&
  1027. RectArea(&dispose_bg_params.rect_ll_) <
  1028. RectArea(&dispose_none_params.rect_ll_)) ||
  1029. (!is_lossless &&
  1030. RectArea(&dispose_bg_params.rect_lossy_) <
  1031. RectArea(&dispose_none_params.rect_lossy_))) {
  1032. dispose_bg_params.should_try_ = 1; // Pick DISPOSE_BACKGROUND.
  1033. dispose_none_params.should_try_ = 0;
  1034. }
  1035. }
  1036. if (dispose_none_params.should_try_) {
  1037. error_code = GenerateCandidates(
  1038. enc, candidates, WEBP_MUX_DISPOSE_NONE, is_lossless, is_key_frame,
  1039. &dispose_none_params, &config_ll, &config_lossy);
  1040. if (error_code != VP8_ENC_OK) goto Err;
  1041. }
  1042. if (dispose_bg_params.should_try_) {
  1043. assert(!enc->is_first_frame_);
  1044. assert(dispose_bg_possible);
  1045. error_code = GenerateCandidates(
  1046. enc, candidates, WEBP_MUX_DISPOSE_BACKGROUND, is_lossless, is_key_frame,
  1047. &dispose_bg_params, &config_ll, &config_lossy);
  1048. if (error_code != VP8_ENC_OK) goto Err;
  1049. }
  1050. PickBestCandidate(enc, candidates, is_key_frame, encoded_frame);
  1051. goto End;
  1052. Err:
  1053. for (i = 0; i < CANDIDATE_COUNT; ++i) {
  1054. if (candidates[i].evaluate_) {
  1055. WebPMemoryWriterClear(&candidates[i].mem_);
  1056. }
  1057. }
  1058. End:
  1059. SubFrameParamsFree(&dispose_none_params);
  1060. SubFrameParamsFree(&dispose_bg_params);
  1061. return error_code;
  1062. }
  1063. // Calculate the penalty incurred if we encode given frame as a key frame
  1064. // instead of a sub-frame.
  1065. static int64_t KeyFramePenalty(const EncodedFrame* const encoded_frame) {
  1066. return ((int64_t)encoded_frame->key_frame_.bitstream.size -
  1067. encoded_frame->sub_frame_.bitstream.size);
  1068. }
  1069. static int CacheFrame(WebPAnimEncoder* const enc,
  1070. const WebPConfig* const config) {
  1071. int ok = 0;
  1072. int frame_skipped = 0;
  1073. WebPEncodingError error_code = VP8_ENC_OK;
  1074. const size_t position = enc->count_;
  1075. EncodedFrame* const encoded_frame = GetFrame(enc, position);
  1076. ++enc->count_;
  1077. if (enc->is_first_frame_) { // Add this as a key-frame.
  1078. error_code = SetFrame(enc, config, 1, encoded_frame, &frame_skipped);
  1079. if (error_code != VP8_ENC_OK) goto End;
  1080. assert(frame_skipped == 0); // First frame can't be skipped, even if empty.
  1081. assert(position == 0 && enc->count_ == 1);
  1082. encoded_frame->is_key_frame_ = 1;
  1083. enc->flush_count_ = 0;
  1084. enc->count_since_key_frame_ = 0;
  1085. enc->prev_candidate_undecided_ = 0;
  1086. } else {
  1087. ++enc->count_since_key_frame_;
  1088. if (enc->count_since_key_frame_ <= enc->options_.kmin) {
  1089. // Add this as a frame rectangle.
  1090. error_code = SetFrame(enc, config, 0, encoded_frame, &frame_skipped);
  1091. if (error_code != VP8_ENC_OK) goto End;
  1092. if (frame_skipped) goto Skip;
  1093. encoded_frame->is_key_frame_ = 0;
  1094. enc->flush_count_ = enc->count_ - 1;
  1095. enc->prev_candidate_undecided_ = 0;
  1096. } else {
  1097. int64_t curr_delta;
  1098. FrameRectangle prev_rect_key, prev_rect_sub;
  1099. // Add this as a frame rectangle to enc.
  1100. error_code = SetFrame(enc, config, 0, encoded_frame, &frame_skipped);
  1101. if (error_code != VP8_ENC_OK) goto End;
  1102. if (frame_skipped) goto Skip;
  1103. prev_rect_sub = enc->prev_rect_;
  1104. // Add this as a key-frame to enc, too.
  1105. error_code = SetFrame(enc, config, 1, encoded_frame, &frame_skipped);
  1106. if (error_code != VP8_ENC_OK) goto End;
  1107. assert(frame_skipped == 0); // Key-frame cannot be an empty rectangle.
  1108. prev_rect_key = enc->prev_rect_;
  1109. // Analyze size difference of the two variants.
  1110. curr_delta = KeyFramePenalty(encoded_frame);
  1111. if (curr_delta <= enc->best_delta_) { // Pick this as the key-frame.
  1112. if (enc->keyframe_ != KEYFRAME_NONE) {
  1113. EncodedFrame* const old_keyframe = GetFrame(enc, enc->keyframe_);
  1114. assert(old_keyframe->is_key_frame_);
  1115. old_keyframe->is_key_frame_ = 0;
  1116. }
  1117. encoded_frame->is_key_frame_ = 1;
  1118. enc->prev_candidate_undecided_ = 1;
  1119. enc->keyframe_ = (int)position;
  1120. enc->best_delta_ = curr_delta;
  1121. enc->flush_count_ = enc->count_ - 1; // We can flush previous frames.
  1122. } else {
  1123. encoded_frame->is_key_frame_ = 0;
  1124. enc->prev_candidate_undecided_ = 0;
  1125. }
  1126. // Note: We need '>=' below because when kmin and kmax are both zero,
  1127. // count_since_key_frame will always be > kmax.
  1128. if (enc->count_since_key_frame_ >= enc->options_.kmax) {
  1129. enc->flush_count_ = enc->count_ - 1;
  1130. enc->count_since_key_frame_ = 0;
  1131. enc->keyframe_ = KEYFRAME_NONE;
  1132. enc->best_delta_ = DELTA_INFINITY;
  1133. }
  1134. if (!enc->prev_candidate_undecided_) {
  1135. enc->prev_rect_ =
  1136. encoded_frame->is_key_frame_ ? prev_rect_key : prev_rect_sub;
  1137. }
  1138. }
  1139. }
  1140. // Update previous to previous and previous canvases for next call.
  1141. WebPCopyPixels(enc->curr_canvas_, &enc->prev_canvas_);
  1142. enc->is_first_frame_ = 0;
  1143. Skip:
  1144. ok = 1;
  1145. ++enc->in_frame_count_;
  1146. End:
  1147. if (!ok || frame_skipped) {
  1148. FrameRelease(encoded_frame);
  1149. // We reset some counters, as the frame addition failed/was skipped.
  1150. --enc->count_;
  1151. if (!enc->is_first_frame_) --enc->count_since_key_frame_;
  1152. if (!ok) {
  1153. MarkError2(enc, "ERROR adding frame. WebPEncodingError", error_code);
  1154. }
  1155. }
  1156. enc->curr_canvas_->error_code = error_code; // report error_code
  1157. assert(ok || error_code != VP8_ENC_OK);
  1158. return ok;
  1159. }
  1160. static int FlushFrames(WebPAnimEncoder* const enc) {
  1161. while (enc->flush_count_ > 0) {
  1162. WebPMuxError err;
  1163. EncodedFrame* const curr = GetFrame(enc, 0);
  1164. const WebPMuxFrameInfo* const info =
  1165. curr->is_key_frame_ ? &curr->key_frame_ : &curr->sub_frame_;
  1166. assert(enc->mux_ != NULL);
  1167. err = WebPMuxPushFrame(enc->mux_, info, 1);
  1168. if (err != WEBP_MUX_OK) {
  1169. MarkError2(enc, "ERROR adding frame. WebPMuxError", err);
  1170. return 0;
  1171. }
  1172. if (enc->options_.verbose) {
  1173. fprintf(stderr, "INFO: Added frame. offset:%d,%d dispose:%d blend:%d\n",
  1174. info->x_offset, info->y_offset, info->dispose_method,
  1175. info->blend_method);
  1176. }
  1177. ++enc->out_frame_count_;
  1178. FrameRelease(curr);
  1179. ++enc->start_;
  1180. --enc->flush_count_;
  1181. --enc->count_;
  1182. if (enc->keyframe_ != KEYFRAME_NONE) --enc->keyframe_;
  1183. }
  1184. if (enc->count_ == 1 && enc->start_ != 0) {
  1185. // Move enc->start to index 0.
  1186. const int enc_start_tmp = (int)enc->start_;
  1187. EncodedFrame temp = enc->encoded_frames_[0];
  1188. enc->encoded_frames_[0] = enc->encoded_frames_[enc_start_tmp];
  1189. enc->encoded_frames_[enc_start_tmp] = temp;
  1190. FrameRelease(&enc->encoded_frames_[enc_start_tmp]);
  1191. enc->start_ = 0;
  1192. }
  1193. return 1;
  1194. }
  1195. #undef DELTA_INFINITY
  1196. #undef KEYFRAME_NONE
  1197. int WebPAnimEncoderAdd(WebPAnimEncoder* enc, WebPPicture* frame, int timestamp,
  1198. const WebPConfig* encoder_config) {
  1199. WebPConfig config;
  1200. int ok;
  1201. if (enc == NULL) {
  1202. return 0;
  1203. }
  1204. MarkNoError(enc);
  1205. if (!enc->is_first_frame_) {
  1206. // Make sure timestamps are non-decreasing (integer wrap-around is OK).
  1207. const uint32_t prev_frame_duration =
  1208. (uint32_t)timestamp - enc->prev_timestamp_;
  1209. if (prev_frame_duration >= MAX_DURATION) {
  1210. if (frame != NULL) {
  1211. frame->error_code = VP8_ENC_ERROR_INVALID_CONFIGURATION;
  1212. }
  1213. MarkError(enc, "ERROR adding frame: timestamps must be non-decreasing");
  1214. return 0;
  1215. }
  1216. if (!IncreasePreviousDuration(enc, (int)prev_frame_duration)) {
  1217. return 0;
  1218. }
  1219. // IncreasePreviousDuration() may add a frame to avoid exceeding
  1220. // MAX_DURATION which could cause CacheFrame() to over read encoded_frames_
  1221. // before the next flush.
  1222. if (enc->count_ == enc->size_ && !FlushFrames(enc)) {
  1223. return 0;
  1224. }
  1225. } else {
  1226. enc->first_timestamp_ = timestamp;
  1227. }
  1228. if (frame == NULL) { // Special: last call.
  1229. enc->got_null_frame_ = 1;
  1230. enc->prev_timestamp_ = timestamp;
  1231. return 1;
  1232. }
  1233. if (frame->width != enc->canvas_width_ ||
  1234. frame->height != enc->canvas_height_) {
  1235. frame->error_code = VP8_ENC_ERROR_INVALID_CONFIGURATION;
  1236. MarkError(enc, "ERROR adding frame: Invalid frame dimensions");
  1237. return 0;
  1238. }
  1239. if (!frame->use_argb) { // Convert frame from YUV(A) to ARGB.
  1240. if (enc->options_.verbose) {
  1241. fprintf(stderr, "WARNING: Converting frame from YUV(A) to ARGB format; "
  1242. "this incurs a small loss.\n");
  1243. }
  1244. if (!WebPPictureYUVAToARGB(frame)) {
  1245. MarkError(enc, "ERROR converting frame from YUV(A) to ARGB");
  1246. return 0;
  1247. }
  1248. }
  1249. if (encoder_config != NULL) {
  1250. if (!WebPValidateConfig(encoder_config)) {
  1251. MarkError(enc, "ERROR adding frame: Invalid WebPConfig");
  1252. return 0;
  1253. }
  1254. config = *encoder_config;
  1255. } else {
  1256. WebPConfigInit(&config);
  1257. config.lossless = 1;
  1258. }
  1259. assert(enc->curr_canvas_ == NULL);
  1260. enc->curr_canvas_ = frame; // Store reference.
  1261. assert(enc->curr_canvas_copy_modified_ == 1);
  1262. CopyCurrentCanvas(enc);
  1263. ok = CacheFrame(enc, &config) && FlushFrames(enc);
  1264. enc->curr_canvas_ = NULL;
  1265. enc->curr_canvas_copy_modified_ = 1;
  1266. if (ok) {
  1267. enc->prev_timestamp_ = timestamp;
  1268. }
  1269. return ok;
  1270. }
  1271. // -----------------------------------------------------------------------------
  1272. // Bitstream assembly.
  1273. static int DecodeFrameOntoCanvas(const WebPMuxFrameInfo* const frame,
  1274. WebPPicture* const canvas) {
  1275. const WebPData* const image = &frame->bitstream;
  1276. WebPPicture sub_image;
  1277. WebPDecoderConfig config;
  1278. WebPInitDecoderConfig(&config);
  1279. WebPUtilClearPic(canvas, NULL);
  1280. if (WebPGetFeatures(image->bytes, image->size, &config.input) !=
  1281. VP8_STATUS_OK) {
  1282. return 0;
  1283. }
  1284. if (!WebPPictureView(canvas, frame->x_offset, frame->y_offset,
  1285. config.input.width, config.input.height, &sub_image)) {
  1286. return 0;
  1287. }
  1288. config.output.is_external_memory = 1;
  1289. config.output.colorspace = MODE_BGRA;
  1290. config.output.u.RGBA.rgba = (uint8_t*)sub_image.argb;
  1291. config.output.u.RGBA.stride = sub_image.argb_stride * 4;
  1292. config.output.u.RGBA.size = config.output.u.RGBA.stride * sub_image.height;
  1293. if (WebPDecode(image->bytes, image->size, &config) != VP8_STATUS_OK) {
  1294. return 0;
  1295. }
  1296. return 1;
  1297. }
  1298. static int FrameToFullCanvas(WebPAnimEncoder* const enc,
  1299. const WebPMuxFrameInfo* const frame,
  1300. WebPData* const full_image) {
  1301. WebPPicture* const canvas_buf = &enc->curr_canvas_copy_;
  1302. WebPMemoryWriter mem1, mem2;
  1303. WebPMemoryWriterInit(&mem1);
  1304. WebPMemoryWriterInit(&mem2);
  1305. if (!DecodeFrameOntoCanvas(frame, canvas_buf)) goto Err;
  1306. if (!EncodeFrame(&enc->last_config_, canvas_buf, &mem1)) goto Err;
  1307. GetEncodedData(&mem1, full_image);
  1308. if (enc->options_.allow_mixed) {
  1309. if (!EncodeFrame(&enc->last_config_reversed_, canvas_buf, &mem2)) goto Err;
  1310. if (mem2.size < mem1.size) {
  1311. GetEncodedData(&mem2, full_image);
  1312. WebPMemoryWriterClear(&mem1);
  1313. } else {
  1314. WebPMemoryWriterClear(&mem2);
  1315. }
  1316. }
  1317. return 1;
  1318. Err:
  1319. WebPMemoryWriterClear(&mem1);
  1320. WebPMemoryWriterClear(&mem2);
  1321. return 0;
  1322. }
  1323. // Convert a single-frame animation to a non-animated image if appropriate.
  1324. // TODO(urvang): Can we pick one of the two heuristically (based on frame
  1325. // rectangle and/or presence of alpha)?
  1326. static WebPMuxError OptimizeSingleFrame(WebPAnimEncoder* const enc,
  1327. WebPData* const webp_data) {
  1328. WebPMuxError err = WEBP_MUX_OK;
  1329. int canvas_width, canvas_height;
  1330. WebPMuxFrameInfo frame;
  1331. WebPData full_image;
  1332. WebPData webp_data2;
  1333. WebPMux* const mux = WebPMuxCreate(webp_data, 0);
  1334. if (mux == NULL) return WEBP_MUX_BAD_DATA;
  1335. assert(enc->out_frame_count_ == 1);
  1336. WebPDataInit(&frame.bitstream);
  1337. WebPDataInit(&full_image);
  1338. WebPDataInit(&webp_data2);
  1339. err = WebPMuxGetFrame(mux, 1, &frame);
  1340. if (err != WEBP_MUX_OK) goto End;
  1341. if (frame.id != WEBP_CHUNK_ANMF) goto End; // Non-animation: nothing to do.
  1342. err = WebPMuxGetCanvasSize(mux, &canvas_width, &canvas_height);
  1343. if (err != WEBP_MUX_OK) goto End;
  1344. if (!FrameToFullCanvas(enc, &frame, &full_image)) {
  1345. err = WEBP_MUX_BAD_DATA;
  1346. goto End;
  1347. }
  1348. err = WebPMuxSetImage(mux, &full_image, 1);
  1349. if (err != WEBP_MUX_OK) goto End;
  1350. err = WebPMuxAssemble(mux, &webp_data2);
  1351. if (err != WEBP_MUX_OK) goto End;
  1352. if (webp_data2.size < webp_data->size) { // Pick 'webp_data2' if smaller.
  1353. WebPDataClear(webp_data);
  1354. *webp_data = webp_data2;
  1355. WebPDataInit(&webp_data2);
  1356. }
  1357. End:
  1358. WebPDataClear(&frame.bitstream);
  1359. WebPDataClear(&full_image);
  1360. WebPMuxDelete(mux);
  1361. WebPDataClear(&webp_data2);
  1362. return err;
  1363. }
  1364. int WebPAnimEncoderAssemble(WebPAnimEncoder* enc, WebPData* webp_data) {
  1365. WebPMux* mux;
  1366. WebPMuxError err;
  1367. if (enc == NULL) {
  1368. return 0;
  1369. }
  1370. MarkNoError(enc);
  1371. if (webp_data == NULL) {
  1372. MarkError(enc, "ERROR assembling: NULL input");
  1373. return 0;
  1374. }
  1375. if (enc->in_frame_count_ == 0) {
  1376. MarkError(enc, "ERROR: No frames to assemble");
  1377. return 0;
  1378. }
  1379. if (!enc->got_null_frame_ && enc->in_frame_count_ > 1 && enc->count_ > 0) {
  1380. // set duration of the last frame to be avg of durations of previous frames.
  1381. const double delta_time =
  1382. (uint32_t)enc->prev_timestamp_ - enc->first_timestamp_;
  1383. const int average_duration = (int)(delta_time / (enc->in_frame_count_ - 1));
  1384. if (!IncreasePreviousDuration(enc, average_duration)) {
  1385. return 0;
  1386. }
  1387. }
  1388. // Flush any remaining frames.
  1389. enc->flush_count_ = enc->count_;
  1390. if (!FlushFrames(enc)) {
  1391. return 0;
  1392. }
  1393. // Set definitive canvas size.
  1394. mux = enc->mux_;
  1395. err = WebPMuxSetCanvasSize(mux, enc->canvas_width_, enc->canvas_height_);
  1396. if (err != WEBP_MUX_OK) goto Err;
  1397. err = WebPMuxSetAnimationParams(mux, &enc->options_.anim_params);
  1398. if (err != WEBP_MUX_OK) goto Err;
  1399. // Assemble into a WebP bitstream.
  1400. err = WebPMuxAssemble(mux, webp_data);
  1401. if (err != WEBP_MUX_OK) goto Err;
  1402. if (enc->out_frame_count_ == 1) {
  1403. err = OptimizeSingleFrame(enc, webp_data);
  1404. if (err != WEBP_MUX_OK) goto Err;
  1405. }
  1406. return 1;
  1407. Err:
  1408. MarkError2(enc, "ERROR assembling WebP", err);
  1409. return 0;
  1410. }
  1411. const char* WebPAnimEncoderGetError(WebPAnimEncoder* enc) {
  1412. if (enc == NULL) return NULL;
  1413. return enc->error_str_;
  1414. }
  1415. // -----------------------------------------------------------------------------