• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 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 // Set and delete APIs for mux.
11 //
12 // Authors: Urvang (urvang@google.com)
13 //          Vikas (vikasa@google.com)
14 
15 #include <assert.h>
16 #include "src/mux/muxi.h"
17 #include "src/utils/utils.h"
18 
19 //------------------------------------------------------------------------------
20 // Life of a mux object.
21 
MuxInit(WebPMux * const mux)22 static void MuxInit(WebPMux* const mux) {
23   assert(mux != NULL);
24   memset(mux, 0, sizeof(*mux));
25   mux->canvas_width_ = 0;     // just to be explicit
26   mux->canvas_height_ = 0;
27 }
28 
WebPNewInternal(int version)29 WebPMux* WebPNewInternal(int version) {
30   if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_MUX_ABI_VERSION)) {
31     return NULL;
32   } else {
33     WebPMux* const mux = (WebPMux*)WebPSafeMalloc(1ULL, sizeof(WebPMux));
34     if (mux != NULL) MuxInit(mux);
35     return mux;
36   }
37 }
38 
39 // Delete all images in 'wpi_list'.
DeleteAllImages(WebPMuxImage ** const wpi_list)40 static void DeleteAllImages(WebPMuxImage** const wpi_list) {
41   while (*wpi_list != NULL) {
42     *wpi_list = MuxImageDelete(*wpi_list);
43   }
44 }
45 
MuxRelease(WebPMux * const mux)46 static void MuxRelease(WebPMux* const mux) {
47   assert(mux != NULL);
48   DeleteAllImages(&mux->images_);
49   ChunkListDelete(&mux->vp8x_);
50   ChunkListDelete(&mux->iccp_);
51   ChunkListDelete(&mux->anim_);
52   ChunkListDelete(&mux->exif_);
53   ChunkListDelete(&mux->xmp_);
54   ChunkListDelete(&mux->unknown_);
55 }
56 
WebPMuxDelete(WebPMux * mux)57 void WebPMuxDelete(WebPMux* mux) {
58   if (mux != NULL) {
59     MuxRelease(mux);
60     WebPSafeFree(mux);
61   }
62 }
63 
64 //------------------------------------------------------------------------------
65 // Helper method(s).
66 
67 // Handy MACRO, makes MuxSet() very symmetric to MuxGet().
68 #define SWITCH_ID_LIST(INDEX, LIST)                                            \
69   if (idx == (INDEX)) {                                                        \
70     err = ChunkAssignData(&chunk, data, copy_data, tag);                       \
71     if (err == WEBP_MUX_OK) {                                                  \
72       err = ChunkSetHead(&chunk, (LIST));                                      \
73       if (err != WEBP_MUX_OK) ChunkRelease(&chunk);                            \
74     }                                                                          \
75     return err;                                                                \
76   }
77 
MuxSet(WebPMux * const mux,uint32_t tag,const WebPData * const data,int copy_data)78 static WebPMuxError MuxSet(WebPMux* const mux, uint32_t tag,
79                            const WebPData* const data, int copy_data) {
80   WebPChunk chunk;
81   WebPMuxError err = WEBP_MUX_NOT_FOUND;
82   const CHUNK_INDEX idx = ChunkGetIndexFromTag(tag);
83   assert(mux != NULL);
84   assert(!IsWPI(kChunks[idx].id));
85 
86   ChunkInit(&chunk);
87   SWITCH_ID_LIST(IDX_VP8X,    &mux->vp8x_);
88   SWITCH_ID_LIST(IDX_ICCP,    &mux->iccp_);
89   SWITCH_ID_LIST(IDX_ANIM,    &mux->anim_);
90   SWITCH_ID_LIST(IDX_EXIF,    &mux->exif_);
91   SWITCH_ID_LIST(IDX_XMP,     &mux->xmp_);
92   SWITCH_ID_LIST(IDX_UNKNOWN, &mux->unknown_);
93   return err;
94 }
95 #undef SWITCH_ID_LIST
96 
97 // Create data for frame given image data, offsets and duration.
CreateFrameData(int width,int height,const WebPMuxFrameInfo * const info,WebPData * const frame)98 static WebPMuxError CreateFrameData(
99     int width, int height, const WebPMuxFrameInfo* const info,
100     WebPData* const frame) {
101   uint8_t* frame_bytes;
102   const size_t frame_size = kChunks[IDX_ANMF].size;
103 
104   assert(width > 0 && height > 0 && info->duration >= 0);
105   assert(info->dispose_method == (info->dispose_method & 1));
106   // Note: assertion on upper bounds is done in PutLE24().
107 
108   frame_bytes = (uint8_t*)WebPSafeMalloc(1ULL, frame_size);
109   if (frame_bytes == NULL) return WEBP_MUX_MEMORY_ERROR;
110 
111   PutLE24(frame_bytes + 0, info->x_offset / 2);
112   PutLE24(frame_bytes + 3, info->y_offset / 2);
113 
114   PutLE24(frame_bytes + 6, width - 1);
115   PutLE24(frame_bytes + 9, height - 1);
116   PutLE24(frame_bytes + 12, info->duration);
117   frame_bytes[15] =
118       (info->blend_method == WEBP_MUX_NO_BLEND ? 2 : 0) |
119       (info->dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ? 1 : 0);
120 
121   frame->bytes = frame_bytes;
122   frame->size = frame_size;
123   return WEBP_MUX_OK;
124 }
125 
126 // Outputs image data given a bitstream. The bitstream can either be a
127 // single-image WebP file or raw VP8/VP8L data.
128 // Also outputs 'is_lossless' to be true if the given bitstream is lossless.
GetImageData(const WebPData * const bitstream,WebPData * const image,WebPData * const alpha,int * const is_lossless)129 static WebPMuxError GetImageData(const WebPData* const bitstream,
130                                  WebPData* const image, WebPData* const alpha,
131                                  int* const is_lossless) {
132   WebPDataInit(alpha);  // Default: no alpha.
133   if (bitstream->size < TAG_SIZE ||
134       memcmp(bitstream->bytes, "RIFF", TAG_SIZE)) {
135     // It is NOT webp file data. Return input data as is.
136     *image = *bitstream;
137   } else {
138     // It is webp file data. Extract image data from it.
139     const WebPMuxImage* wpi;
140     WebPMux* const mux = WebPMuxCreate(bitstream, 0);
141     if (mux == NULL) return WEBP_MUX_BAD_DATA;
142     wpi = mux->images_;
143     assert(wpi != NULL && wpi->img_ != NULL);
144     *image = wpi->img_->data_;
145     if (wpi->alpha_ != NULL) {
146       *alpha = wpi->alpha_->data_;
147     }
148     WebPMuxDelete(mux);
149   }
150   *is_lossless = VP8LCheckSignature(image->bytes, image->size);
151   return WEBP_MUX_OK;
152 }
153 
DeleteChunks(WebPChunk ** chunk_list,uint32_t tag)154 static WebPMuxError DeleteChunks(WebPChunk** chunk_list, uint32_t tag) {
155   WebPMuxError err = WEBP_MUX_NOT_FOUND;
156   assert(chunk_list);
157   while (*chunk_list) {
158     WebPChunk* const chunk = *chunk_list;
159     if (chunk->tag_ == tag) {
160       *chunk_list = ChunkDelete(chunk);
161       err = WEBP_MUX_OK;
162     } else {
163       chunk_list = &chunk->next_;
164     }
165   }
166   return err;
167 }
168 
MuxDeleteAllNamedData(WebPMux * const mux,uint32_t tag)169 static WebPMuxError MuxDeleteAllNamedData(WebPMux* const mux, uint32_t tag) {
170   const WebPChunkId id = ChunkGetIdFromTag(tag);
171   assert(mux != NULL);
172   if (IsWPI(id)) return WEBP_MUX_INVALID_ARGUMENT;
173   return DeleteChunks(MuxGetChunkListFromId(mux, id), tag);
174 }
175 
176 //------------------------------------------------------------------------------
177 // Set API(s).
178 
WebPMuxSetChunk(WebPMux * mux,const char fourcc[4],const WebPData * chunk_data,int copy_data)179 WebPMuxError WebPMuxSetChunk(WebPMux* mux, const char fourcc[4],
180                              const WebPData* chunk_data, int copy_data) {
181   uint32_t tag;
182   WebPMuxError err;
183   if (mux == NULL || fourcc == NULL || chunk_data == NULL ||
184       chunk_data->bytes == NULL || chunk_data->size > MAX_CHUNK_PAYLOAD) {
185     return WEBP_MUX_INVALID_ARGUMENT;
186   }
187   tag = ChunkGetTagFromFourCC(fourcc);
188 
189   // Delete existing chunk(s) with the same 'fourcc'.
190   err = MuxDeleteAllNamedData(mux, tag);
191   if (err != WEBP_MUX_OK && err != WEBP_MUX_NOT_FOUND) return err;
192 
193   // Add the given chunk.
194   return MuxSet(mux, tag, chunk_data, copy_data);
195 }
196 
197 // Creates a chunk from given 'data' and sets it as 1st chunk in 'chunk_list'.
AddDataToChunkList(const WebPData * const data,int copy_data,uint32_t tag,WebPChunk ** chunk_list)198 static WebPMuxError AddDataToChunkList(
199     const WebPData* const data, int copy_data, uint32_t tag,
200     WebPChunk** chunk_list) {
201   WebPChunk chunk;
202   WebPMuxError err;
203   ChunkInit(&chunk);
204   err = ChunkAssignData(&chunk, data, copy_data, tag);
205   if (err != WEBP_MUX_OK) goto Err;
206   err = ChunkSetHead(&chunk, chunk_list);
207   if (err != WEBP_MUX_OK) goto Err;
208   return WEBP_MUX_OK;
209  Err:
210   ChunkRelease(&chunk);
211   return err;
212 }
213 
214 // Extracts image & alpha data from the given bitstream and then sets wpi.alpha_
215 // and wpi.img_ appropriately.
SetAlphaAndImageChunks(const WebPData * const bitstream,int copy_data,WebPMuxImage * const wpi)216 static WebPMuxError SetAlphaAndImageChunks(
217     const WebPData* const bitstream, int copy_data, WebPMuxImage* const wpi) {
218   int is_lossless = 0;
219   WebPData image, alpha;
220   WebPMuxError err = GetImageData(bitstream, &image, &alpha, &is_lossless);
221   const int image_tag =
222       is_lossless ? kChunks[IDX_VP8L].tag : kChunks[IDX_VP8].tag;
223   if (err != WEBP_MUX_OK) return err;
224   if (alpha.bytes != NULL) {
225     err = AddDataToChunkList(&alpha, copy_data, kChunks[IDX_ALPHA].tag,
226                              &wpi->alpha_);
227     if (err != WEBP_MUX_OK) return err;
228   }
229   err = AddDataToChunkList(&image, copy_data, image_tag, &wpi->img_);
230   if (err != WEBP_MUX_OK) return err;
231   return MuxImageFinalize(wpi) ? WEBP_MUX_OK : WEBP_MUX_INVALID_ARGUMENT;
232 }
233 
WebPMuxSetImage(WebPMux * mux,const WebPData * bitstream,int copy_data)234 WebPMuxError WebPMuxSetImage(WebPMux* mux, const WebPData* bitstream,
235                              int copy_data) {
236   WebPMuxImage wpi;
237   WebPMuxError err;
238 
239   if (mux == NULL || bitstream == NULL || bitstream->bytes == NULL ||
240       bitstream->size > MAX_CHUNK_PAYLOAD) {
241     return WEBP_MUX_INVALID_ARGUMENT;
242   }
243 
244   if (mux->images_ != NULL) {
245     // Only one 'simple image' can be added in mux. So, remove present images.
246     DeleteAllImages(&mux->images_);
247   }
248 
249   MuxImageInit(&wpi);
250   err = SetAlphaAndImageChunks(bitstream, copy_data, &wpi);
251   if (err != WEBP_MUX_OK) goto Err;
252 
253   // Add this WebPMuxImage to mux.
254   err = MuxImagePush(&wpi, &mux->images_);
255   if (err != WEBP_MUX_OK) goto Err;
256 
257   // All is well.
258   return WEBP_MUX_OK;
259 
260  Err:  // Something bad happened.
261   MuxImageRelease(&wpi);
262   return err;
263 }
264 
WebPMuxPushFrame(WebPMux * mux,const WebPMuxFrameInfo * info,int copy_data)265 WebPMuxError WebPMuxPushFrame(WebPMux* mux, const WebPMuxFrameInfo* info,
266                               int copy_data) {
267   WebPMuxImage wpi;
268   WebPMuxError err;
269 
270   if (mux == NULL || info == NULL) return WEBP_MUX_INVALID_ARGUMENT;
271 
272   if (info->id != WEBP_CHUNK_ANMF) return WEBP_MUX_INVALID_ARGUMENT;
273 
274   if (info->bitstream.bytes == NULL ||
275       info->bitstream.size > MAX_CHUNK_PAYLOAD) {
276     return WEBP_MUX_INVALID_ARGUMENT;
277   }
278 
279   if (mux->images_ != NULL) {
280     const WebPMuxImage* const image = mux->images_;
281     const uint32_t image_id = (image->header_ != NULL) ?
282         ChunkGetIdFromTag(image->header_->tag_) : WEBP_CHUNK_IMAGE;
283     if (image_id != info->id) {
284       return WEBP_MUX_INVALID_ARGUMENT;  // Conflicting frame types.
285     }
286   }
287 
288   MuxImageInit(&wpi);
289   err = SetAlphaAndImageChunks(&info->bitstream, copy_data, &wpi);
290   if (err != WEBP_MUX_OK) goto Err;
291   assert(wpi.img_ != NULL);  // As SetAlphaAndImageChunks() was successful.
292 
293   {
294     WebPData frame;
295     const uint32_t tag = kChunks[IDX_ANMF].tag;
296     WebPMuxFrameInfo tmp = *info;
297     tmp.x_offset &= ~1;  // Snap offsets to even.
298     tmp.y_offset &= ~1;
299     if (tmp.x_offset < 0 || tmp.x_offset >= MAX_POSITION_OFFSET ||
300         tmp.y_offset < 0 || tmp.y_offset >= MAX_POSITION_OFFSET ||
301         (tmp.duration < 0 || tmp.duration >= MAX_DURATION) ||
302         tmp.dispose_method != (tmp.dispose_method & 1)) {
303       err = WEBP_MUX_INVALID_ARGUMENT;
304       goto Err;
305     }
306     err = CreateFrameData(wpi.width_, wpi.height_, &tmp, &frame);
307     if (err != WEBP_MUX_OK) goto Err;
308     // Add frame chunk (with copy_data = 1).
309     err = AddDataToChunkList(&frame, 1, tag, &wpi.header_);
310     WebPDataClear(&frame);  // frame owned by wpi.header_ now.
311     if (err != WEBP_MUX_OK) goto Err;
312   }
313 
314   // Add this WebPMuxImage to mux.
315   err = MuxImagePush(&wpi, &mux->images_);
316   if (err != WEBP_MUX_OK) goto Err;
317 
318   // All is well.
319   return WEBP_MUX_OK;
320 
321  Err:  // Something bad happened.
322   MuxImageRelease(&wpi);
323   return err;
324 }
325 
WebPMuxSetAnimationParams(WebPMux * mux,const WebPMuxAnimParams * params)326 WebPMuxError WebPMuxSetAnimationParams(WebPMux* mux,
327                                        const WebPMuxAnimParams* params) {
328   WebPMuxError err;
329   uint8_t data[ANIM_CHUNK_SIZE];
330   const WebPData anim = { data, ANIM_CHUNK_SIZE };
331 
332   if (mux == NULL || params == NULL) return WEBP_MUX_INVALID_ARGUMENT;
333   if (params->loop_count < 0 || params->loop_count >= MAX_LOOP_COUNT) {
334     return WEBP_MUX_INVALID_ARGUMENT;
335   }
336 
337   // Delete any existing ANIM chunk(s).
338   err = MuxDeleteAllNamedData(mux, kChunks[IDX_ANIM].tag);
339   if (err != WEBP_MUX_OK && err != WEBP_MUX_NOT_FOUND) return err;
340 
341   // Set the animation parameters.
342   PutLE32(data, params->bgcolor);
343   PutLE16(data + 4, params->loop_count);
344   return MuxSet(mux, kChunks[IDX_ANIM].tag, &anim, 1);
345 }
346 
WebPMuxSetCanvasSize(WebPMux * mux,int width,int height)347 WebPMuxError WebPMuxSetCanvasSize(WebPMux* mux,
348                                   int width, int height) {
349   WebPMuxError err;
350   if (mux == NULL) {
351     return WEBP_MUX_INVALID_ARGUMENT;
352   }
353   if (width < 0 || height < 0 ||
354       width > MAX_CANVAS_SIZE || height > MAX_CANVAS_SIZE) {
355     return WEBP_MUX_INVALID_ARGUMENT;
356   }
357   if (width * (uint64_t)height >= MAX_IMAGE_AREA) {
358     return WEBP_MUX_INVALID_ARGUMENT;
359   }
360   if ((width * height) == 0 && (width | height) != 0) {
361     // one of width / height is zero, but not both -> invalid!
362     return WEBP_MUX_INVALID_ARGUMENT;
363   }
364   // If we already assembled a VP8X chunk, invalidate it.
365   err = MuxDeleteAllNamedData(mux, kChunks[IDX_VP8X].tag);
366   if (err != WEBP_MUX_OK && err != WEBP_MUX_NOT_FOUND) return err;
367 
368   mux->canvas_width_ = width;
369   mux->canvas_height_ = height;
370   return WEBP_MUX_OK;
371 }
372 
373 //------------------------------------------------------------------------------
374 // Delete API(s).
375 
WebPMuxDeleteChunk(WebPMux * mux,const char fourcc[4])376 WebPMuxError WebPMuxDeleteChunk(WebPMux* mux, const char fourcc[4]) {
377   if (mux == NULL || fourcc == NULL) return WEBP_MUX_INVALID_ARGUMENT;
378   return MuxDeleteAllNamedData(mux, ChunkGetTagFromFourCC(fourcc));
379 }
380 
WebPMuxDeleteFrame(WebPMux * mux,uint32_t nth)381 WebPMuxError WebPMuxDeleteFrame(WebPMux* mux, uint32_t nth) {
382   if (mux == NULL) return WEBP_MUX_INVALID_ARGUMENT;
383   return MuxImageDeleteNth(&mux->images_, nth);
384 }
385 
386 //------------------------------------------------------------------------------
387 // Assembly of the WebP RIFF file.
388 
GetFrameInfo(const WebPChunk * const frame_chunk,int * const x_offset,int * const y_offset,int * const duration)389 static WebPMuxError GetFrameInfo(
390     const WebPChunk* const frame_chunk,
391     int* const x_offset, int* const y_offset, int* const duration) {
392   const WebPData* const data = &frame_chunk->data_;
393   const size_t expected_data_size = ANMF_CHUNK_SIZE;
394   assert(frame_chunk->tag_ == kChunks[IDX_ANMF].tag);
395   assert(frame_chunk != NULL);
396   if (data->size != expected_data_size) return WEBP_MUX_INVALID_ARGUMENT;
397 
398   *x_offset = 2 * GetLE24(data->bytes + 0);
399   *y_offset = 2 * GetLE24(data->bytes + 3);
400   *duration = GetLE24(data->bytes + 12);
401   return WEBP_MUX_OK;
402 }
403 
GetImageInfo(const WebPMuxImage * const wpi,int * const x_offset,int * const y_offset,int * const duration,int * const width,int * const height)404 static WebPMuxError GetImageInfo(const WebPMuxImage* const wpi,
405                                  int* const x_offset, int* const y_offset,
406                                  int* const duration,
407                                  int* const width, int* const height) {
408   const WebPChunk* const frame_chunk = wpi->header_;
409   WebPMuxError err;
410   assert(wpi != NULL);
411   assert(frame_chunk != NULL);
412 
413   // Get offsets and duration from ANMF chunk.
414   err = GetFrameInfo(frame_chunk, x_offset, y_offset, duration);
415   if (err != WEBP_MUX_OK) return err;
416 
417   // Get width and height from VP8/VP8L chunk.
418   if (width != NULL) *width = wpi->width_;
419   if (height != NULL) *height = wpi->height_;
420   return WEBP_MUX_OK;
421 }
422 
423 // Returns the tightest dimension for the canvas considering the image list.
GetAdjustedCanvasSize(const WebPMux * const mux,int * const width,int * const height)424 static WebPMuxError GetAdjustedCanvasSize(const WebPMux* const mux,
425                                           int* const width, int* const height) {
426   WebPMuxImage* wpi = NULL;
427   assert(mux != NULL);
428   assert(width != NULL && height != NULL);
429 
430   wpi = mux->images_;
431   assert(wpi != NULL);
432   assert(wpi->img_ != NULL);
433 
434   if (wpi->next_ != NULL) {
435     int max_x = 0, max_y = 0;
436     // if we have a chain of wpi's, header_ is necessarily set
437     assert(wpi->header_ != NULL);
438     // Aggregate the bounding box for animation frames.
439     for (; wpi != NULL; wpi = wpi->next_) {
440       int x_offset = 0, y_offset = 0, duration = 0, w = 0, h = 0;
441       const WebPMuxError err = GetImageInfo(wpi, &x_offset, &y_offset,
442                                             &duration, &w, &h);
443       const int max_x_pos = x_offset + w;
444       const int max_y_pos = y_offset + h;
445       if (err != WEBP_MUX_OK) return err;
446       assert(x_offset < MAX_POSITION_OFFSET);
447       assert(y_offset < MAX_POSITION_OFFSET);
448 
449       if (max_x_pos > max_x) max_x = max_x_pos;
450       if (max_y_pos > max_y) max_y = max_y_pos;
451     }
452     *width = max_x;
453     *height = max_y;
454   } else {
455     // For a single image, canvas dimensions are same as image dimensions.
456     *width = wpi->width_;
457     *height = wpi->height_;
458   }
459   return WEBP_MUX_OK;
460 }
461 
462 // VP8X format:
463 // Total Size : 10,
464 // Flags  : 4 bytes,
465 // Width  : 3 bytes,
466 // Height : 3 bytes.
CreateVP8XChunk(WebPMux * const mux)467 static WebPMuxError CreateVP8XChunk(WebPMux* const mux) {
468   WebPMuxError err = WEBP_MUX_OK;
469   uint32_t flags = 0;
470   int width = 0;
471   int height = 0;
472   uint8_t data[VP8X_CHUNK_SIZE];
473   const WebPData vp8x = { data, VP8X_CHUNK_SIZE };
474   const WebPMuxImage* images = NULL;
475 
476   assert(mux != NULL);
477   images = mux->images_;  // First image.
478   if (images == NULL || images->img_ == NULL ||
479       images->img_->data_.bytes == NULL) {
480     return WEBP_MUX_INVALID_ARGUMENT;
481   }
482 
483   // If VP8X chunk(s) is(are) already present, remove them (and later add new
484   // VP8X chunk with updated flags).
485   err = MuxDeleteAllNamedData(mux, kChunks[IDX_VP8X].tag);
486   if (err != WEBP_MUX_OK && err != WEBP_MUX_NOT_FOUND) return err;
487 
488   // Set flags.
489   if (mux->iccp_ != NULL && mux->iccp_->data_.bytes != NULL) {
490     flags |= ICCP_FLAG;
491   }
492   if (mux->exif_ != NULL && mux->exif_->data_.bytes != NULL) {
493     flags |= EXIF_FLAG;
494   }
495   if (mux->xmp_ != NULL && mux->xmp_->data_.bytes != NULL) {
496     flags |= XMP_FLAG;
497   }
498   if (images->header_ != NULL) {
499     if (images->header_->tag_ == kChunks[IDX_ANMF].tag) {
500       // This is an image with animation.
501       flags |= ANIMATION_FLAG;
502     }
503   }
504   if (MuxImageCount(images, WEBP_CHUNK_ALPHA) > 0) {
505     flags |= ALPHA_FLAG;  // Some images have an alpha channel.
506   }
507 
508   err = GetAdjustedCanvasSize(mux, &width, &height);
509   if (err != WEBP_MUX_OK) return err;
510 
511   if (width <= 0 || height <= 0) {
512     return WEBP_MUX_INVALID_ARGUMENT;
513   }
514   if (width > MAX_CANVAS_SIZE || height > MAX_CANVAS_SIZE) {
515     return WEBP_MUX_INVALID_ARGUMENT;
516   }
517 
518   if (mux->canvas_width_ != 0 || mux->canvas_height_ != 0) {
519     if (width > mux->canvas_width_ || height > mux->canvas_height_) {
520       return WEBP_MUX_INVALID_ARGUMENT;
521     }
522     width = mux->canvas_width_;
523     height = mux->canvas_height_;
524   }
525 
526   if (flags == 0 && mux->unknown_ == NULL) {
527     // For simple file format, VP8X chunk should not be added.
528     return WEBP_MUX_OK;
529   }
530 
531   if (MuxHasAlpha(images)) {
532     // This means some frames explicitly/implicitly contain alpha.
533     // Note: This 'flags' update must NOT be done for a lossless image
534     // without a VP8X chunk!
535     flags |= ALPHA_FLAG;
536   }
537 
538   PutLE32(data + 0, flags);   // VP8X chunk flags.
539   PutLE24(data + 4, width - 1);   // canvas width.
540   PutLE24(data + 7, height - 1);  // canvas height.
541 
542   return MuxSet(mux, kChunks[IDX_VP8X].tag, &vp8x, 1);
543 }
544 
545 // Cleans up 'mux' by removing any unnecessary chunks.
MuxCleanup(WebPMux * const mux)546 static WebPMuxError MuxCleanup(WebPMux* const mux) {
547   int num_frames;
548   int num_anim_chunks;
549 
550   // If we have an image with a single frame, and its rectangle
551   // covers the whole canvas, convert it to a non-animated image
552   // (to avoid writing ANMF chunk unnecessarily).
553   WebPMuxError err = WebPMuxNumChunks(mux, kChunks[IDX_ANMF].id, &num_frames);
554   if (err != WEBP_MUX_OK) return err;
555   if (num_frames == 1) {
556     WebPMuxImage* frame = NULL;
557     err = MuxImageGetNth((const WebPMuxImage**)&mux->images_, 1, &frame);
558     assert(err == WEBP_MUX_OK);  // We know that one frame does exist.
559     assert(frame != NULL);
560     if (frame->header_ != NULL &&
561         ((mux->canvas_width_ == 0 && mux->canvas_height_ == 0) ||
562          (frame->width_ == mux->canvas_width_ &&
563           frame->height_ == mux->canvas_height_))) {
564       assert(frame->header_->tag_ == kChunks[IDX_ANMF].tag);
565       ChunkDelete(frame->header_);  // Removes ANMF chunk.
566       frame->header_ = NULL;
567       num_frames = 0;
568     }
569   }
570   // Remove ANIM chunk if this is a non-animated image.
571   err = WebPMuxNumChunks(mux, kChunks[IDX_ANIM].id, &num_anim_chunks);
572   if (err != WEBP_MUX_OK) return err;
573   if (num_anim_chunks >= 1 && num_frames == 0) {
574     err = MuxDeleteAllNamedData(mux, kChunks[IDX_ANIM].tag);
575     if (err != WEBP_MUX_OK) return err;
576   }
577   return WEBP_MUX_OK;
578 }
579 
580 // Total size of a list of images.
ImageListDiskSize(const WebPMuxImage * wpi_list)581 static size_t ImageListDiskSize(const WebPMuxImage* wpi_list) {
582   size_t size = 0;
583   while (wpi_list != NULL) {
584     size += MuxImageDiskSize(wpi_list);
585     wpi_list = wpi_list->next_;
586   }
587   return size;
588 }
589 
590 // Write out the given list of images into 'dst'.
ImageListEmit(const WebPMuxImage * wpi_list,uint8_t * dst)591 static uint8_t* ImageListEmit(const WebPMuxImage* wpi_list, uint8_t* dst) {
592   while (wpi_list != NULL) {
593     dst = MuxImageEmit(wpi_list, dst);
594     wpi_list = wpi_list->next_;
595   }
596   return dst;
597 }
598 
WebPMuxAssemble(WebPMux * mux,WebPData * assembled_data)599 WebPMuxError WebPMuxAssemble(WebPMux* mux, WebPData* assembled_data) {
600   size_t size = 0;
601   uint8_t* data = NULL;
602   uint8_t* dst = NULL;
603   WebPMuxError err;
604 
605   if (assembled_data == NULL) {
606     return WEBP_MUX_INVALID_ARGUMENT;
607   }
608   // Clean up returned data, in case something goes wrong.
609   memset(assembled_data, 0, sizeof(*assembled_data));
610 
611   if (mux == NULL) {
612     return WEBP_MUX_INVALID_ARGUMENT;
613   }
614 
615   // Finalize mux.
616   err = MuxCleanup(mux);
617   if (err != WEBP_MUX_OK) return err;
618   err = CreateVP8XChunk(mux);
619   if (err != WEBP_MUX_OK) return err;
620 
621   // Allocate data.
622   size = ChunkListDiskSize(mux->vp8x_) + ChunkListDiskSize(mux->iccp_)
623        + ChunkListDiskSize(mux->anim_) + ImageListDiskSize(mux->images_)
624        + ChunkListDiskSize(mux->exif_) + ChunkListDiskSize(mux->xmp_)
625        + ChunkListDiskSize(mux->unknown_) + RIFF_HEADER_SIZE;
626 
627   data = (uint8_t*)WebPSafeMalloc(1ULL, size);
628   if (data == NULL) return WEBP_MUX_MEMORY_ERROR;
629 
630   // Emit header & chunks.
631   dst = MuxEmitRiffHeader(data, size);
632   dst = ChunkListEmit(mux->vp8x_, dst);
633   dst = ChunkListEmit(mux->iccp_, dst);
634   dst = ChunkListEmit(mux->anim_, dst);
635   dst = ImageListEmit(mux->images_, dst);
636   dst = ChunkListEmit(mux->exif_, dst);
637   dst = ChunkListEmit(mux->xmp_, dst);
638   dst = ChunkListEmit(mux->unknown_, dst);
639   assert(dst == data + size);
640 
641   // Validate mux.
642   err = MuxValidate(mux);
643   if (err != WEBP_MUX_OK) {
644     WebPSafeFree(data);
645     data = NULL;
646     size = 0;
647   }
648 
649   // Finalize data.
650   assembled_data->bytes = data;
651   assembled_data->size = size;
652 
653   return err;
654 }
655 
656 //------------------------------------------------------------------------------
657