Coverage Report

Created: 2025-06-13 06:49

/src/libwebp/src/enc/syntax_enc.c
Line
Count
Source (jump to first uncovered line)
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
// Header syntax writing
11
//
12
// Author: Skal (pascal.massimino@gmail.com)
13
14
#include <assert.h>
15
#include <stddef.h>
16
17
#include "src/dec/common_dec.h"
18
#include "src/webp/types.h"
19
#include "src/enc/vp8i_enc.h"
20
#include "src/utils/bit_writer_utils.h"
21
#include "src/utils/utils.h"
22
#include "src/webp/encode.h"
23
#include "src/webp/format_constants.h"  // RIFF constants
24
#include "src/webp/mux_types.h"         // ALPHA_FLAG
25
26
//------------------------------------------------------------------------------
27
// Helper functions
28
29
0
static int IsVP8XNeeded(const VP8Encoder* const enc) {
30
0
  return !!enc->has_alpha;  // Currently the only case when VP8X is needed.
31
                            // This could change in the future.
32
0
}
33
34
0
static int PutPaddingByte(const WebPPicture* const pic) {
35
0
  const uint8_t pad_byte[1] = { 0 };
36
0
  return !!pic->writer(pad_byte, 1, pic);
37
0
}
38
39
//------------------------------------------------------------------------------
40
// Writers for header's various pieces (in order of appearance)
41
42
static WebPEncodingError PutRIFFHeader(const VP8Encoder* const enc,
43
0
                                       size_t riff_size) {
44
0
  const WebPPicture* const pic = enc->pic;
45
0
  uint8_t riff[RIFF_HEADER_SIZE] = {
46
0
    'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P'
47
0
  };
48
0
  assert(riff_size == (uint32_t)riff_size);
49
0
  PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);
50
0
  if (!pic->writer(riff, sizeof(riff), pic)) {
51
0
    return VP8_ENC_ERROR_BAD_WRITE;
52
0
  }
53
0
  return VP8_ENC_OK;
54
0
}
55
56
0
static WebPEncodingError PutVP8XHeader(const VP8Encoder* const enc) {
57
0
  const WebPPicture* const pic = enc->pic;
58
0
  uint8_t vp8x[CHUNK_HEADER_SIZE + VP8X_CHUNK_SIZE] = {
59
0
    'V', 'P', '8', 'X'
60
0
  };
61
0
  uint32_t flags = 0;
62
63
0
  assert(IsVP8XNeeded(enc));
64
0
  assert(pic->width >= 1 && pic->height >= 1);
65
0
  assert(pic->width <= MAX_CANVAS_SIZE && pic->height <= MAX_CANVAS_SIZE);
66
67
0
  if (enc->has_alpha) {
68
0
    flags |= ALPHA_FLAG;
69
0
  }
70
71
0
  PutLE32(vp8x + TAG_SIZE,              VP8X_CHUNK_SIZE);
72
0
  PutLE32(vp8x + CHUNK_HEADER_SIZE,     flags);
73
0
  PutLE24(vp8x + CHUNK_HEADER_SIZE + 4, pic->width - 1);
74
0
  PutLE24(vp8x + CHUNK_HEADER_SIZE + 7, pic->height - 1);
75
0
  if (!pic->writer(vp8x, sizeof(vp8x), pic)) {
76
0
    return VP8_ENC_ERROR_BAD_WRITE;
77
0
  }
78
0
  return VP8_ENC_OK;
79
0
}
80
81
0
static WebPEncodingError PutAlphaChunk(const VP8Encoder* const enc) {
82
0
  const WebPPicture* const pic = enc->pic;
83
0
  uint8_t alpha_chunk_hdr[CHUNK_HEADER_SIZE] = {
84
0
    'A', 'L', 'P', 'H'
85
0
  };
86
87
0
  assert(enc->has_alpha);
88
89
  // Alpha chunk header.
90
0
  PutLE32(alpha_chunk_hdr + TAG_SIZE, enc->alpha_data_size);
91
0
  if (!pic->writer(alpha_chunk_hdr, sizeof(alpha_chunk_hdr), pic)) {
92
0
    return VP8_ENC_ERROR_BAD_WRITE;
93
0
  }
94
95
  // Alpha chunk data.
96
0
  if (!pic->writer(enc->alpha_data, enc->alpha_data_size, pic)) {
97
0
    return VP8_ENC_ERROR_BAD_WRITE;
98
0
  }
99
100
  // Padding.
101
0
  if ((enc->alpha_data_size & 1) && !PutPaddingByte(pic)) {
102
0
    return VP8_ENC_ERROR_BAD_WRITE;
103
0
  }
104
0
  return VP8_ENC_OK;
105
0
}
106
107
static WebPEncodingError PutVP8Header(const WebPPicture* const pic,
108
0
                                      size_t vp8_size) {
109
0
  uint8_t vp8_chunk_hdr[CHUNK_HEADER_SIZE] = {
110
0
    'V', 'P', '8', ' '
111
0
  };
112
0
  assert(vp8_size == (uint32_t)vp8_size);
113
0
  PutLE32(vp8_chunk_hdr + TAG_SIZE, (uint32_t)vp8_size);
114
0
  if (!pic->writer(vp8_chunk_hdr, sizeof(vp8_chunk_hdr), pic)) {
115
0
    return VP8_ENC_ERROR_BAD_WRITE;
116
0
  }
117
0
  return VP8_ENC_OK;
118
0
}
119
120
static WebPEncodingError PutVP8FrameHeader(const WebPPicture* const pic,
121
0
                                           int profile, size_t size0) {
122
0
  uint8_t vp8_frm_hdr[VP8_FRAME_HEADER_SIZE];
123
0
  uint32_t bits;
124
125
0
  if (size0 >= VP8_MAX_PARTITION0_SIZE) {  // partition #0 is too big to fit
126
0
    return VP8_ENC_ERROR_PARTITION0_OVERFLOW;
127
0
  }
128
129
  // Paragraph 9.1.
130
0
  bits = 0                         // keyframe (1b)
131
0
       | (profile << 1)            // profile (3b)
132
0
       | (1 << 4)                  // visible (1b)
133
0
       | ((uint32_t)size0 << 5);   // partition length (19b)
134
0
  vp8_frm_hdr[0] = (bits >>  0) & 0xff;
135
0
  vp8_frm_hdr[1] = (bits >>  8) & 0xff;
136
0
  vp8_frm_hdr[2] = (bits >> 16) & 0xff;
137
  // signature
138
0
  vp8_frm_hdr[3] = (VP8_SIGNATURE >> 16) & 0xff;
139
0
  vp8_frm_hdr[4] = (VP8_SIGNATURE >>  8) & 0xff;
140
0
  vp8_frm_hdr[5] = (VP8_SIGNATURE >>  0) & 0xff;
141
  // dimensions
142
0
  vp8_frm_hdr[6] = pic->width & 0xff;
143
0
  vp8_frm_hdr[7] = pic->width >> 8;
144
0
  vp8_frm_hdr[8] = pic->height & 0xff;
145
0
  vp8_frm_hdr[9] = pic->height >> 8;
146
147
0
  if (!pic->writer(vp8_frm_hdr, sizeof(vp8_frm_hdr), pic)) {
148
0
    return VP8_ENC_ERROR_BAD_WRITE;
149
0
  }
150
0
  return VP8_ENC_OK;
151
0
}
152
153
// WebP Headers.
154
static int PutWebPHeaders(const VP8Encoder* const enc, size_t size0,
155
0
                          size_t vp8_size, size_t riff_size) {
156
0
  WebPPicture* const pic = enc->pic;
157
0
  WebPEncodingError err = VP8_ENC_OK;
158
159
  // RIFF header.
160
0
  err = PutRIFFHeader(enc, riff_size);
161
0
  if (err != VP8_ENC_OK) goto Error;
162
163
  // VP8X.
164
0
  if (IsVP8XNeeded(enc)) {
165
0
    err = PutVP8XHeader(enc);
166
0
    if (err != VP8_ENC_OK) goto Error;
167
0
  }
168
169
  // Alpha.
170
0
  if (enc->has_alpha) {
171
0
    err = PutAlphaChunk(enc);
172
0
    if (err != VP8_ENC_OK) goto Error;
173
0
  }
174
175
  // VP8 header.
176
0
  err = PutVP8Header(pic, vp8_size);
177
0
  if (err != VP8_ENC_OK) goto Error;
178
179
  // VP8 frame header.
180
0
  err = PutVP8FrameHeader(pic, enc->profile, size0);
181
0
  if (err != VP8_ENC_OK) goto Error;
182
183
  // All OK.
184
0
  return 1;
185
186
  // Error.
187
0
 Error:
188
0
  return WebPEncodingSetError(pic, err);
189
0
}
190
191
// Segmentation header
192
static void PutSegmentHeader(VP8BitWriter* const bw,
193
0
                             const VP8Encoder* const enc) {
194
0
  const VP8EncSegmentHeader* const hdr = &enc->segment_hdr;
195
0
  const VP8EncProba* const proba = &enc->proba;
196
0
  if (VP8PutBitUniform(bw, (hdr->num_segments > 1))) {
197
    // We always 'update' the quant and filter strength values
198
0
    const int update_data = 1;
199
0
    int s;
200
0
    VP8PutBitUniform(bw, hdr->update_map);
201
0
    if (VP8PutBitUniform(bw, update_data)) {
202
      // we always use absolute values, not relative ones
203
0
      VP8PutBitUniform(bw, 1);   // (segment_feature_mode = 1. Paragraph 9.3.)
204
0
      for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
205
0
        VP8PutSignedBits(bw, enc->dqm[s].quant, 7);
206
0
      }
207
0
      for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
208
0
        VP8PutSignedBits(bw, enc->dqm[s].fstrength, 6);
209
0
      }
210
0
    }
211
0
    if (hdr->update_map) {
212
0
      for (s = 0; s < 3; ++s) {
213
0
        if (VP8PutBitUniform(bw, (proba->segments[s] != 255u))) {
214
0
          VP8PutBits(bw, proba->segments[s], 8);
215
0
        }
216
0
      }
217
0
    }
218
0
  }
219
0
}
220
221
// Filtering parameters header
222
static void PutFilterHeader(VP8BitWriter* const bw,
223
0
                            const VP8EncFilterHeader* const hdr) {
224
0
  const int use_lf_delta = (hdr->i4x4_lf_delta != 0);
225
0
  VP8PutBitUniform(bw, hdr->simple);
226
0
  VP8PutBits(bw, hdr->level, 6);
227
0
  VP8PutBits(bw, hdr->sharpness, 3);
228
0
  if (VP8PutBitUniform(bw, use_lf_delta)) {
229
    // '0' is the default value for i4x4_lf_delta at frame #0.
230
0
    const int need_update = (hdr->i4x4_lf_delta != 0);
231
0
    if (VP8PutBitUniform(bw, need_update)) {
232
      // we don't use ref_lf_delta => emit four 0 bits
233
0
      VP8PutBits(bw, 0, 4);
234
      // we use mode_lf_delta for i4x4
235
0
      VP8PutSignedBits(bw, hdr->i4x4_lf_delta, 6);
236
0
      VP8PutBits(bw, 0, 3);    // all others unused
237
0
    }
238
0
  }
239
0
}
240
241
// Nominal quantization parameters
242
static void PutQuant(VP8BitWriter* const bw,
243
0
                     const VP8Encoder* const enc) {
244
0
  VP8PutBits(bw, enc->base_quant, 7);
245
0
  VP8PutSignedBits(bw, enc->dq_y1_dc, 4);
246
0
  VP8PutSignedBits(bw, enc->dq_y2_dc, 4);
247
0
  VP8PutSignedBits(bw, enc->dq_y2_ac, 4);
248
0
  VP8PutSignedBits(bw, enc->dq_uv_dc, 4);
249
0
  VP8PutSignedBits(bw, enc->dq_uv_ac, 4);
250
0
}
251
252
// Partition sizes
253
static int EmitPartitionsSize(const VP8Encoder* const enc,
254
0
                              WebPPicture* const pic) {
255
0
  uint8_t buf[3 * (MAX_NUM_PARTITIONS - 1)];
256
0
  int p;
257
0
  for (p = 0; p < enc->num_parts - 1; ++p) {
258
0
    const size_t part_size = VP8BitWriterSize(enc->parts + p);
259
0
    if (part_size >= VP8_MAX_PARTITION_SIZE) {
260
0
      return WebPEncodingSetError(pic, VP8_ENC_ERROR_PARTITION_OVERFLOW);
261
0
    }
262
0
    buf[3 * p + 0] = (part_size >>  0) & 0xff;
263
0
    buf[3 * p + 1] = (part_size >>  8) & 0xff;
264
0
    buf[3 * p + 2] = (part_size >> 16) & 0xff;
265
0
  }
266
0
  if (p && !pic->writer(buf, 3 * p, pic)) {
267
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_WRITE);
268
0
  }
269
0
  return 1;
270
0
}
271
272
//------------------------------------------------------------------------------
273
274
0
static int GeneratePartition0(VP8Encoder* const enc) {
275
0
  VP8BitWriter* const bw = &enc->bw;
276
0
  const int mb_size = enc->mb_w * enc->mb_h;
277
0
  uint64_t pos1, pos2, pos3;
278
279
0
  pos1 = VP8BitWriterPos(bw);
280
0
  if (!VP8BitWriterInit(bw, mb_size * 7 / 8)) {        // ~7 bits per macroblock
281
0
    return WebPEncodingSetError(enc->pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
282
0
  }
283
0
  VP8PutBitUniform(bw, 0);   // colorspace
284
0
  VP8PutBitUniform(bw, 0);   // clamp type
285
286
0
  PutSegmentHeader(bw, enc);
287
0
  PutFilterHeader(bw, &enc->filter_hdr);
288
0
  VP8PutBits(bw, enc->num_parts == 8 ? 3 :
289
0
                 enc->num_parts == 4 ? 2 :
290
0
                 enc->num_parts == 2 ? 1 : 0, 2);
291
0
  PutQuant(bw, enc);
292
0
  VP8PutBitUniform(bw, 0);   // no proba update
293
0
  VP8WriteProbas(bw, &enc->proba);
294
0
  pos2 = VP8BitWriterPos(bw);
295
0
  VP8CodeIntraModes(enc);
296
0
  VP8BitWriterFinish(bw);
297
298
0
  pos3 = VP8BitWriterPos(bw);
299
300
0
#if !defined(WEBP_DISABLE_STATS)
301
0
  if (enc->pic->stats) {
302
0
    enc->pic->stats->header_bytes[0] = (int)((pos2 - pos1 + 7) >> 3);
303
0
    enc->pic->stats->header_bytes[1] = (int)((pos3 - pos2 + 7) >> 3);
304
0
    enc->pic->stats->alpha_data_size = (int)enc->alpha_data_size;
305
0
  }
306
#else
307
  (void)pos1;
308
  (void)pos2;
309
  (void)pos3;
310
#endif
311
0
  if (bw->error) {
312
0
    return WebPEncodingSetError(enc->pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
313
0
  }
314
0
  return 1;
315
0
}
316
317
0
void VP8EncFreeBitWriters(VP8Encoder* const enc) {
318
0
  int p;
319
0
  VP8BitWriterWipeOut(&enc->bw);
320
0
  for (p = 0; p < enc->num_parts; ++p) {
321
0
    VP8BitWriterWipeOut(enc->parts + p);
322
0
  }
323
0
}
324
325
0
int VP8EncWrite(VP8Encoder* const enc) {
326
0
  WebPPicture* const pic = enc->pic;
327
0
  VP8BitWriter* const bw = &enc->bw;
328
0
  const int task_percent = 19;
329
0
  const int percent_per_part = task_percent / enc->num_parts;
330
0
  const int final_percent = enc->percent + task_percent;
331
0
  int ok = 0;
332
0
  size_t vp8_size, pad, riff_size;
333
0
  int p;
334
335
  // Partition #0 with header and partition sizes
336
0
  ok = GeneratePartition0(enc);
337
0
  if (!ok) return 0;
338
339
  // Compute VP8 size
340
0
  vp8_size = VP8_FRAME_HEADER_SIZE +
341
0
             VP8BitWriterSize(bw) +
342
0
             3 * (enc->num_parts - 1);
343
0
  for (p = 0; p < enc->num_parts; ++p) {
344
0
    vp8_size += VP8BitWriterSize(enc->parts + p);
345
0
  }
346
0
  pad = vp8_size & 1;
347
0
  vp8_size += pad;
348
349
  // Compute RIFF size
350
  // At the minimum it is: "WEBPVP8 nnnn" + VP8 data size.
351
0
  riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8_size;
352
0
  if (IsVP8XNeeded(enc)) {  // Add size for: VP8X header + data.
353
0
    riff_size += CHUNK_HEADER_SIZE + VP8X_CHUNK_SIZE;
354
0
  }
355
0
  if (enc->has_alpha) {  // Add size for: ALPH header + data.
356
0
    const uint32_t padded_alpha_size = enc->alpha_data_size +
357
0
                                       (enc->alpha_data_size & 1);
358
0
    riff_size += CHUNK_HEADER_SIZE + padded_alpha_size;
359
0
  }
360
  // RIFF size should fit in 32-bits.
361
0
  if (riff_size > 0xfffffffeU) {
362
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_FILE_TOO_BIG);
363
0
  }
364
365
  // Emit headers and partition #0
366
0
  {
367
0
    const uint8_t* const part0 = VP8BitWriterBuf(bw);
368
0
    const size_t size0 = VP8BitWriterSize(bw);
369
0
    ok = ok && PutWebPHeaders(enc, size0, vp8_size, riff_size)
370
0
            && pic->writer(part0, size0, pic)
371
0
            && EmitPartitionsSize(enc, pic);
372
0
    VP8BitWriterWipeOut(bw);    // will free the internal buffer.
373
0
  }
374
375
  // Token partitions
376
0
  for (p = 0; p < enc->num_parts; ++p) {
377
0
    const uint8_t* const buf = VP8BitWriterBuf(enc->parts + p);
378
0
    const size_t size = VP8BitWriterSize(enc->parts + p);
379
0
    if (size) ok = ok && pic->writer(buf, size, pic);
380
0
    VP8BitWriterWipeOut(enc->parts + p);    // will free the internal buffer.
381
0
    ok = ok && WebPReportProgress(pic, enc->percent + percent_per_part,
382
0
                                  &enc->percent);
383
0
  }
384
385
  // Padding byte
386
0
  if (ok && pad) {
387
0
    ok = PutPaddingByte(pic);
388
0
  }
389
390
0
  enc->coded_size = (int)(CHUNK_HEADER_SIZE + riff_size);
391
0
  ok = ok && WebPReportProgress(pic, final_percent, &enc->percent);
392
0
  if (!ok) WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_WRITE);
393
0
  return ok;
394
0
}
395
396
//------------------------------------------------------------------------------