github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/image/webp/libwebp/src/mux/muxedit.c (about)

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