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