Coverage Report

Created: 2024-06-18 06:05

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