RoQ video encoder
[libav.git] / libavcodec / roqvideoenc.c
CommitLineData
03e3e765
VS
1/*
2 * RoQ Video Encoder.
3 *
4 * Copyright (C) 2007 Vitor <vitor1001@gmail.com>
5 * Copyright (C) 2004-2007 Eric Lasota
6 * Based on RoQ specs (C) 2001 Tim Ferguson
7 *
8 * This file is part of FFmpeg.
9 *
10 * FFmpeg is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * FFmpeg is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with FFmpeg; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 */
24
25/**
26 * @file roqvideoenc.c
27 * Id RoQ encoder by Vitor. Based on the Switchblade3 library and the
28 * Switchblade3 FFmpeg glue by Eric Lasota.
29 */
30
31/*
32 * COSTS:
33 * Level 1:
34 * SKIP - 2 bits
35 * MOTION - 2 + 8 bits
36 * CODEBOOK - 2 + 8 bits
37 * SUBDIVIDE - 2 + combined subcel cost
38 *
39 * Level 2:
40 * SKIP - 2 bits
41 * MOTION - 2 + 8 bits
42 * CODEBOOK - 2 + 8 bits
43 * SUBDIVIDE - 2 + 4*8 bits
44 *
45 * Maximum cost: 138 bits per cel
46 *
47 * Proper evaluation requires LCD fraction comparison, which requires
48 * Squared Error (SE) loss * savings increase
49 *
50 * Maximum savings increase: 136 bits
51 * Maximum SE loss without overflow: 31580641
52 * Components in 8x8 supercel: 192
53 * Maximum SE precision per component: 164482
54 * >65025, so no truncation is needed (phew)
55 */
56
57#include <string.h>
58#include <unistd.h>
59
60#include "roqvideo.h"
61#include "bytestream.h"
62#include "elbg.h"
63
64#define CHROMA_BIAS 1
65
66/**
67 * Maximum number of generated 4x4 codebooks. Can't be 256 to workaround a
68 * Quake 3 bug.
69 */
70#define MAX_CBS_4x4 255
71
72#define MAX_CBS_2x2 256 ///< Maximum number of 2x2 codebooks.
73
74/* The cast is useful when multiplying it by INT_MAX */
75#define ROQ_LAMBDA_SCALE ((uint64_t) FF_LAMBDA_SCALE)
76
77/* Macroblock support functions */
78static void unpack_roq_cell(roq_cell *cell, uint8_t u[4*3])
79{
80 memcpy(u , cell->y, 4);
81 memset(u+4, cell->u, 4);
82 memset(u+8, cell->v, 4);
83}
84
85static void unpack_roq_qcell(uint8_t cb2[], roq_qcell *qcell, uint8_t u[4*4*3])
86{
87 int i,cp;
88 static const int offsets[4] = {0, 2, 8, 10};
89
90 for (cp=0; cp<3; cp++)
91 for (i=0; i<4; i++) {
92 u[4*4*cp + offsets[i] ] = cb2[qcell->idx[i]*2*2*3 + 4*cp ];
93 u[4*4*cp + offsets[i]+1] = cb2[qcell->idx[i]*2*2*3 + 4*cp+1];
94 u[4*4*cp + offsets[i]+4] = cb2[qcell->idx[i]*2*2*3 + 4*cp+2];
95 u[4*4*cp + offsets[i]+5] = cb2[qcell->idx[i]*2*2*3 + 4*cp+3];
96 }
97}
98
99
100static void enlarge_roq_mb4(uint8_t base[3*16], uint8_t u[3*64])
101{
102 int x,y,cp;
103
104 for(cp=0; cp<3; cp++)
105 for(y=0; y<8; y++)
106 for(x=0; x<8; x++)
107 *u++ = base[(y/2)*4 + (x/2) + 16*cp];
108}
109
110static inline int square(int x)
111{
112 return x*x;
113}
114
115static inline int eval_sse(uint8_t *a, uint8_t *b, int count)
116{
117 int diff=0;
118
119 while(count--)
120 diff += square(*b++ - *a++);
121
122 return diff;
123}
124
125// FIXME Could use DSPContext.sse, but it is not so speed critical (used
126// just for motion estimation).
127static int block_sse(uint8_t **buf1, uint8_t **buf2, int x1, int y1, int x2,
128 int y2, int stride, int size)
129{
130 int i, k;
131 int sse=0;
132
133 for (k=0; k<3; k++) {
134 int bias = (k ? CHROMA_BIAS : 4);
135 for (i=0; i<size; i++)
136 sse += bias*eval_sse(buf1[k] + (y1+i)*stride + x1,
137 buf2[k] + (y2+i)*stride + x2, size);
138 }
139
140 return sse;
141}
142
143static int eval_motion_dist(RoqContext *enc, int x, int y, motion_vect vect,
144 int size)
145{
146 int mx=vect.d[0];
147 int my=vect.d[1];
148
149 if (mx < -7 || mx > 7)
150 return INT_MAX;
151
152 if (my < -7 || my > 7)
153 return INT_MAX;
154
155 mx += x;
156 my += y;
157
158 if ((unsigned) mx > enc->width-size || (unsigned) my > enc->height-size)
159 return INT_MAX;
160
161 return block_sse(enc->frame_to_enc->data, enc->last_frame->data, x, y,
162 mx, my, enc->y_stride, size);
163}
164
165/**
166 * Returns distortion between two macroblocks
167 */
168static inline int squared_diff_macroblock(uint8_t a[], uint8_t b[], int size)
169{
170 int cp, sdiff=0;
171
172 for(cp=0;cp<3;cp++) {
173 int bias = (cp ? CHROMA_BIAS : 4);
174 sdiff += bias*eval_sse(a, b, size*size);
175 a += size*size;
176 b += size*size;
177 }
178
179 return sdiff;
180}
181
182typedef struct
183{
184 int eval_dist[4];
185 int best_bit_use;
186 int best_coding;
187
188 int subCels[4];
189 motion_vect motion;
190 int cbEntry;
191} subcel_evaluation_t;
192
193typedef struct
194{
195 int eval_dist[4];
196 int best_coding;
197
198 subcel_evaluation_t subCels[4];
199
200 motion_vect motion;
201 int cbEntry;
202
203 int sourceX, sourceY;
204} cel_evaluation_t;
205
206typedef struct
207{
208 int numCB4;
209 int numCB2;
210 int usedCB2[MAX_CBS_2x2];
211 int usedCB4[MAX_CBS_4x4];
212 uint8_t unpacked_cb2[MAX_CBS_2x2*2*2*3];
213 uint8_t unpacked_cb4[MAX_CBS_4x4*4*4*3];
214 uint8_t unpacked_cb4_enlarged[MAX_CBS_4x4*8*8*3];
215} roq_codebooks_t;
216
217/**
218 * Temporary vars
219 */
220typedef struct
221{
222 cel_evaluation_t *cel_evals;
223
224 int f2i4[MAX_CBS_4x4];
225 int i2f4[MAX_CBS_4x4];
226 int f2i2[MAX_CBS_2x2];
227 int i2f2[MAX_CBS_2x2];
228
229 int mainChunkSize;
230
231 int numCB4;
232 int numCB2;
233
234 roq_codebooks_t codebooks;
235
236 int *closest_cb2;
237 int used_option[4];
238} roq_tempdata_t;
239
240/**
241 * Initializes cel evaluators and sets their source coordinates
242 */
243static void create_cel_evals(RoqContext *enc, roq_tempdata_t *tempData)
244{
245 int n=0, x, y, i;
246
247 tempData->cel_evals = av_malloc(enc->width*enc->height/64 * sizeof(cel_evaluation_t));
248
249 /* Map to the ROQ quadtree order */
250 for (y=0; y<enc->height; y+=16)
251 for (x=0; x<enc->width; x+=16)
252 for(i=0; i<4; i++) {
253 tempData->cel_evals[n ].sourceX = x + (i&1)*8;
254 tempData->cel_evals[n++].sourceY = y + (i&2)*4;
255 }
256}
257
258/**
259 * Get macroblocks from parts of the image
260 */
261static void get_frame_mb(AVFrame *frame, int x, int y, uint8_t mb[], int dim)
262{
263 int i, j, cp;
264 int stride = frame->linesize[0];
265
266 for (cp=0; cp<3; cp++)
267 for (i=0; i<dim; i++)
268 for (j=0; j<dim; j++)
269 *mb++ = frame->data[cp][(y+i)*stride + x + j];
270}
271
272/**
273 * Find the codebook with the lowest distortion from an image
274 */
275static int index_mb(uint8_t cluster[], uint8_t cb[], int numCB,
276 int *outIndex, int dim)
277{
278 int i, lDiff = INT_MAX, pick=0;
279
280 /* Diff against the others */
281 for (i=0; i<numCB; i++) {
282 int diff = squared_diff_macroblock(cluster, cb + i*dim*dim*3, dim);
283 if (diff < lDiff) {
284 lDiff = diff;
285 pick = i;
286 }
287 }
288
289 *outIndex = pick;
290 return lDiff;
291}
292
293#define EVAL_MOTION(MOTION) \
294 do { \
295 diff = eval_motion_dist(enc, j, i, MOTION, blocksize); \
296 \
297 if (diff < lowestdiff) { \
298 lowestdiff = diff; \
299 bestpick = MOTION; \
300 } \
301 } while(0)
302
303static void motion_search(RoqContext *enc, int blocksize)
304{
305 static const motion_vect offsets[8] = {
306 {{ 0,-1}},
307 {{ 0, 1}},
308 {{-1, 0}},
309 {{ 1, 0}},
310 {{-1, 1}},
311 {{ 1,-1}},
312 {{-1,-1}},
313 {{ 1, 1}},
314 };
315
316 int diff, lowestdiff, oldbest;
317 int off[3];
318 motion_vect bestpick = {{0,0}};
319 int i, j, k, offset;
320
321 motion_vect *last_motion;
322 motion_vect *this_motion;
323 motion_vect vect, vect2;
324
325 int max=(enc->width/blocksize)*enc->height/blocksize;
326
327 if (blocksize == 4) {
328 last_motion = enc->last_motion4;
329 this_motion = enc->this_motion4;
330 } else {
331 last_motion = enc->last_motion8;
332 this_motion = enc->this_motion8;
333 }
334
335 for (i=0; i<enc->height; i+=blocksize)
336 for (j=0; j<enc->width; j+=blocksize) {
337 lowestdiff = eval_motion_dist(enc, j, i, (motion_vect) {{0,0}},
338 blocksize);
339 bestpick.d[0] = 0;
340 bestpick.d[1] = 0;
341
342 if (blocksize == 4)
343 EVAL_MOTION(enc->this_motion8[(i/8)*(enc->width/8) + j/8]);
344
345 offset = (i/blocksize)*enc->width/blocksize + j/blocksize;
346 if (offset < max && offset >= 0)
347 EVAL_MOTION(last_motion[offset]);
348
349 offset++;
350 if (offset < max && offset >= 0)
351 EVAL_MOTION(last_motion[offset]);
352
353 offset = (i/blocksize + 1)*enc->width/blocksize + j/blocksize;
354 if (offset < max && offset >= 0)
355 EVAL_MOTION(last_motion[offset]);
356
357 off[0]= (i/blocksize)*enc->width/blocksize + j/blocksize - 1;
358 off[1]= off[0] - enc->width/blocksize + 1;
359 off[2]= off[1] + 1;
360
361 if (i) {
362
363 for(k=0; k<2; k++)
364 vect.d[k]= mid_pred(this_motion[off[0]].d[k],
365 this_motion[off[1]].d[k],
366 this_motion[off[2]].d[k]);
367
368 EVAL_MOTION(vect);
369 for(k=0; k<3; k++)
370 EVAL_MOTION(this_motion[off[k]]);
371 } else if(j)
372 EVAL_MOTION(this_motion[off[0]]);
373
374 vect = bestpick;
375
376 oldbest = -1;
377 while (oldbest != lowestdiff) {
378 oldbest = lowestdiff;
379 for (k=0; k<8; k++) {
380 vect2 = vect;
381 vect2.d[0] += offsets[k].d[0];
382 vect2.d[1] += offsets[k].d[1];
383 EVAL_MOTION(vect2);
384 }
385 vect = bestpick;
386 }
387 offset = (i/blocksize)*enc->width/blocksize + j/blocksize;
388 this_motion[offset] = bestpick;
389 }
390}
391
392/**
393 * Gets distortion for all options available to a subcel
394 */
395static void gather_data_for_subcel(subcel_evaluation_t *subcel, int x,
396 int y, RoqContext *enc, roq_tempdata_t *tempData)
397{
398 uint8_t mb4[4*4*3];
399 uint8_t mb2[2*2*3];
400 int cluster_index;
401 int i, best_dist;
402
403 static const int bitsUsed[4] = {2, 10, 10, 34};
404
405 if (enc->framesSinceKeyframe >= 1) {
406 subcel->motion = enc->this_motion4[y*enc->width/16 + x/4];
407
408 subcel->eval_dist[RoQ_ID_FCC] =
409 eval_motion_dist(enc, x, y,
410 enc->this_motion4[y*enc->width/16 + x/4], 4);
411 } else
412 subcel->eval_dist[RoQ_ID_FCC] = INT_MAX;
413
414 if (enc->framesSinceKeyframe >= 2)
415 subcel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
416 enc->current_frame->data, x,
417 y, x, y, enc->y_stride, 4);
418 else
419 subcel->eval_dist[RoQ_ID_MOT] = INT_MAX;
420
421 cluster_index = y*enc->width/16 + x/4;
422
423 get_frame_mb(enc->frame_to_enc, x, y, mb4, 4);
424
425 subcel->eval_dist[RoQ_ID_SLD] = index_mb(mb4,
426 tempData->codebooks.unpacked_cb4,
427 tempData->codebooks.numCB4,
428 &subcel->cbEntry, 4);
429
430 subcel->eval_dist[RoQ_ID_CCC] = 0;
431
432 for(i=0;i<4;i++) {
433 subcel->subCels[i] = tempData->closest_cb2[cluster_index*4+i];
434
435 get_frame_mb(enc->frame_to_enc, x+2*(i&1),
436 y+(i&2), mb2, 2);
437
438 subcel->eval_dist[RoQ_ID_CCC] +=
439 squared_diff_macroblock(tempData->codebooks.unpacked_cb2 + subcel->subCels[i]*2*2*3, mb2, 2);
440 }
441
442 best_dist = INT_MAX;
443 for (i=0; i<4; i++)
444 if (ROQ_LAMBDA_SCALE*subcel->eval_dist[i] + enc->lambda*bitsUsed[i] <
445 best_dist) {
446 subcel->best_coding = i;
447 subcel->best_bit_use = bitsUsed[i];
448 best_dist = ROQ_LAMBDA_SCALE*subcel->eval_dist[i] +
449 enc->lambda*bitsUsed[i];
450 }
451}
452
453/**
454 * Gets distortion for all options available to a cel
455 */
456static void gather_data_for_cel(cel_evaluation_t *cel, RoqContext *enc,
457 roq_tempdata_t *tempData)
458{
459 uint8_t mb8[8*8*3];
460 int index = cel->sourceY*enc->width/64 + cel->sourceX/8;
461 int i, j, best_dist, divide_bit_use;
462
463 int bitsUsed[4] = {2, 10, 10, 0};
464
465 if (enc->framesSinceKeyframe >= 1) {
466 cel->motion = enc->this_motion8[index];
467
468 cel->eval_dist[RoQ_ID_FCC] =
469 eval_motion_dist(enc, cel->sourceX, cel->sourceY,
470 enc->this_motion8[index], 8);
471 } else
472 cel->eval_dist[RoQ_ID_FCC] = INT_MAX;
473
474 if (enc->framesSinceKeyframe >= 2)
475 cel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
476 enc->current_frame->data,
477 cel->sourceX, cel->sourceY,
478 cel->sourceX, cel->sourceY,
479 enc->y_stride, 8);
480 else
481 cel->eval_dist[RoQ_ID_MOT] = INT_MAX;
482
483 get_frame_mb(enc->frame_to_enc, cel->sourceX, cel->sourceY, mb8, 8);
484
485 cel->eval_dist[RoQ_ID_SLD] =
486 index_mb(mb8, tempData->codebooks.unpacked_cb4_enlarged,
487 tempData->codebooks.numCB4, &cel->cbEntry, 8);
488
489 gather_data_for_subcel(cel->subCels + 0, cel->sourceX+0, cel->sourceY+0, enc, tempData);
490 gather_data_for_subcel(cel->subCels + 1, cel->sourceX+4, cel->sourceY+0, enc, tempData);
491 gather_data_for_subcel(cel->subCels + 2, cel->sourceX+0, cel->sourceY+4, enc, tempData);
492 gather_data_for_subcel(cel->subCels + 3, cel->sourceX+4, cel->sourceY+4, enc, tempData);
493
494 cel->eval_dist[RoQ_ID_CCC] = 0;
495 divide_bit_use = 0;
496 for (i=0; i<4; i++) {
497 cel->eval_dist[RoQ_ID_CCC] +=
498 cel->subCels[i].eval_dist[cel->subCels[i].best_coding];
499 divide_bit_use += cel->subCels[i].best_bit_use;
500 }
501
502 best_dist = INT_MAX;
503 bitsUsed[3] = 2 + divide_bit_use;
504
505 for (i=0; i<4; i++)
506 if (ROQ_LAMBDA_SCALE*cel->eval_dist[i] + enc->lambda*bitsUsed[i] <
507 best_dist) {
508 cel->best_coding = i;
509 best_dist = ROQ_LAMBDA_SCALE*cel->eval_dist[i] +
510 enc->lambda*bitsUsed[i];
511 }
512
513 tempData->used_option[cel->best_coding]++;
514 tempData->mainChunkSize += bitsUsed[cel->best_coding];
515
516 if (cel->best_coding == RoQ_ID_SLD)
517 tempData->codebooks.usedCB4[cel->cbEntry]++;
518
519 if (cel->best_coding == RoQ_ID_CCC)
520 for (i=0; i<4; i++) {
521 if (cel->subCels[i].best_coding == RoQ_ID_SLD)
522 tempData->codebooks.usedCB4[cel->subCels[i].cbEntry]++;
523 else if (cel->subCels[i].best_coding == RoQ_ID_CCC)
524 for (j=0; j<4; j++)
525 tempData->codebooks.usedCB2[cel->subCels[i].subCels[j]]++;
526 }
527}
528
529static void remap_codebooks(RoqContext *enc, roq_tempdata_t *tempData)
530{
531 int i, j, idx=0;
532
533 /* Make remaps for the final codebook usage */
534 for (i=0; i<MAX_CBS_4x4; i++) {
535 if (tempData->codebooks.usedCB4[i]) {
536 tempData->i2f4[i] = idx;
537 tempData->f2i4[idx] = i;
538 for (j=0; j<4; j++)
539 tempData->codebooks.usedCB2[enc->cb4x4[i].idx[j]]++;
540 idx++;
541 }
542 }
543
544 tempData->numCB4 = idx;
545
546 idx = 0;
547 for (i=0; i<MAX_CBS_2x2; i++) {
548 if (tempData->codebooks.usedCB2[i]) {
549 tempData->i2f2[i] = idx;
550 tempData->f2i2[idx] = i;
551 idx++;
552 }
553 }
554 tempData->numCB2 = idx;
555
556}
557
558/**
559 * Write codebook chunk
560 */
561static void write_codebooks(RoqContext *enc, roq_tempdata_t *tempData)
562{
563 int i, j;
564 uint8_t **outp= &enc->out_buf;
565
566 if (tempData->numCB2) {
567 bytestream_put_le16(outp, RoQ_QUAD_CODEBOOK);
568 bytestream_put_le32(outp, tempData->numCB2*6 + tempData->numCB4*4);
569 bytestream_put_byte(outp, tempData->numCB4);
570 bytestream_put_byte(outp, tempData->numCB2);
571
572 for (i=0; i<tempData->numCB2; i++) {
573 bytestream_put_buffer(outp, enc->cb2x2[tempData->f2i2[i]].y, 4);
574 bytestream_put_byte(outp, enc->cb2x2[tempData->f2i2[i]].u);
575 bytestream_put_byte(outp, enc->cb2x2[tempData->f2i2[i]].v);
576 }
577
578 for (i=0; i<tempData->numCB4; i++)
579 for (j=0; j<4; j++)
580 bytestream_put_byte(outp, tempData->i2f2[enc->cb4x4[tempData->f2i4[i]].idx[j]]);
581
582 }
583}
584
585static inline uint8_t motion_arg(motion_vect mot)
586{
587 uint8_t ax = 8 - ((uint8_t) mot.d[0]);
588 uint8_t ay = 8 - ((uint8_t) mot.d[1]);
589 return ((ax&15)<<4) | (ay&15);
590}
591
592typedef struct
593{
594 int typeSpool;
595 int typeSpoolLength;
596 uint8_t argumentSpool[64];
597 uint8_t *args;
598 uint8_t **pout;
599} CodingSpool;
600
601/* NOTE: Typecodes must be spooled AFTER arguments!! */
602static void write_typecode(CodingSpool *s, uint8_t type)
603{
604 s->typeSpool |= ((type) & 3) << (14 - s->typeSpoolLength);
605 s->typeSpoolLength += 2;
606 if (s->typeSpoolLength == 16) {
607 bytestream_put_le16(s->pout, s->typeSpool);
608 bytestream_put_buffer(s->pout, s->argumentSpool,
609 s->args - s->argumentSpool);
610 s->typeSpoolLength = 0;
611 s->typeSpool = 0;
612 s->args = s->argumentSpool;
613 }
614}
615
616static void reconstruct_and_encode_image(RoqContext *enc, roq_tempdata_t *tempData, int w, int h, int numBlocks)
617{
618 int i, j, k;
619 int x, y;
620 int subX, subY;
621 int dist=0;
622
623 roq_qcell *qcell;
624 cel_evaluation_t *eval;
625
626 CodingSpool spool;
627
628 spool.typeSpool=0;
629 spool.typeSpoolLength=0;
630 spool.args = spool.argumentSpool;
631 spool.pout = &enc->out_buf;
632
633 if (tempData->used_option[RoQ_ID_CCC]%2)
634 tempData->mainChunkSize+=8; //FIXME
635
636 /* Write the video chunk header */
637 bytestream_put_le16(&enc->out_buf, RoQ_QUAD_VQ);
638 bytestream_put_le32(&enc->out_buf, tempData->mainChunkSize/8);
639 bytestream_put_byte(&enc->out_buf, 0x0);
640 bytestream_put_byte(&enc->out_buf, 0x0);
641
642 for (i=0; i<numBlocks; i++) {
643 eval = tempData->cel_evals + i;
644
645 x = eval->sourceX;
646 y = eval->sourceY;
647 dist += eval->eval_dist[eval->best_coding];
648
649 switch (eval->best_coding) {
650 case RoQ_ID_MOT:
651 write_typecode(&spool, RoQ_ID_MOT);
652 break;
653
654 case RoQ_ID_FCC:
655 bytestream_put_byte(&spool.args, motion_arg(eval->motion));
656
657 write_typecode(&spool, RoQ_ID_FCC);
658 ff_apply_motion_8x8(enc, x, y,
659 eval->motion.d[0], eval->motion.d[1]);
660 break;
661
662 case RoQ_ID_SLD:
663 bytestream_put_byte(&spool.args, tempData->i2f4[eval->cbEntry]);
664 write_typecode(&spool, RoQ_ID_SLD);
665
666 qcell = enc->cb4x4 + eval->cbEntry;
667 ff_apply_vector_4x4(enc, x , y , enc->cb2x2 + qcell->idx[0]);
668 ff_apply_vector_4x4(enc, x+4, y , enc->cb2x2 + qcell->idx[1]);
669 ff_apply_vector_4x4(enc, x , y+4, enc->cb2x2 + qcell->idx[2]);
670 ff_apply_vector_4x4(enc, x+4, y+4, enc->cb2x2 + qcell->idx[3]);
671 break;
672
673 case RoQ_ID_CCC:
674 write_typecode(&spool, RoQ_ID_CCC);
675
676 for (j=0; j<4; j++) {
677 subX = x + 4*(j&1);
678 subY = y + 2*(j&2);
679
680 switch(eval->subCels[j].best_coding) {
681 case RoQ_ID_MOT:
682 break;
683
684 case RoQ_ID_FCC:
685 bytestream_put_byte(&spool.args,
686 motion_arg(eval->subCels[j].motion));
687
688 ff_apply_motion_4x4(enc, subX, subY,
689 eval->subCels[j].motion.d[0],
690 eval->subCels[j].motion.d[1]);
691 break;
692
693 case RoQ_ID_SLD:
694 bytestream_put_byte(&spool.args,
695 tempData->i2f4[eval->subCels[j].cbEntry]);
696
697 qcell = enc->cb4x4 + eval->subCels[j].cbEntry;
698
699 ff_apply_vector_2x2(enc, subX , subY ,
700 enc->cb2x2 + qcell->idx[0]);
701 ff_apply_vector_2x2(enc, subX+2, subY ,
702 enc->cb2x2 + qcell->idx[1]);
703 ff_apply_vector_2x2(enc, subX , subY+2,
704 enc->cb2x2 + qcell->idx[2]);
705 ff_apply_vector_2x2(enc, subX+2, subY+2,
706 enc->cb2x2 + qcell->idx[3]);
707 break;
708
709 case RoQ_ID_CCC:
710 for (k=0; k<4; k++) {
711 int cb_idx = eval->subCels[j].subCels[k];
712 bytestream_put_byte(&spool.args,
713 tempData->i2f2[cb_idx]);
714
715 ff_apply_vector_2x2(enc, subX + 2*(k&1), subY + (k&2),
716 enc->cb2x2 + cb_idx);
717 }
718 break;
719 }
720 write_typecode(&spool, eval->subCels[j].best_coding);
721 }
722 break;
723 }
724 }
725
726 /* Flush the remainder of the argument/type spool */
727 while (spool.typeSpoolLength)
728 write_typecode(&spool, 0x0);
729
730#if 0
731 uint8_t *fdata[3] = {enc->frame_to_enc->data[0],
732 enc->frame_to_enc->data[1],
733 enc->frame_to_enc->data[2]};
734 uint8_t *cdata[3] = {enc->current_frame->data[0],
735 enc->current_frame->data[1],
736 enc->current_frame->data[2]};
737 av_log(enc->avctx, AV_LOG_ERROR, "Expected distortion: %i Actual: %i\n",
738 dist,
739 block_sse(fdata, cdata, 0, 0, 0, 0,
740 enc->y_stride, enc->width)); //WARNING: Square dimensions implied...
741#endif
742}
743
744
745/**
746 * Create a single YUV cell from a 2x2 section of the image
747 */
748static inline void frame_block_to_cell(uint8_t *block, uint8_t **data,
749 int top, int left, int *stride)
750{
751 int i, j, u=0, v=0;
752
753 for (i=0; i<2; i++)
754 for (j=0; j<2; j++) {
755 int x = (top+i)*stride[0] + left + j;
756 *block++ = data[0][x];
757 u += data[1][x];
758 v += data[2][x];
759 }
760
761 *block++ = (u+2)/4;
762 *block++ = (v+2)/4;
763}
764
765/**
766 * Creates YUV clusters for the entire image
767 */
768static void create_clusters(AVFrame *frame, int w, int h, uint8_t *yuvClusters)
769{
770 int i, j, k, l;
771
772 for (i=0; i<h; i+=4)
773 for (j=0; j<w; j+=4) {
774 for (k=0; k < 2; k++)
775 for (l=0; l < 2; l++)
776 frame_block_to_cell(yuvClusters + (l + 2*k)*6, frame->data,
777 i+2*k, j+2*l, frame->linesize);
778 yuvClusters += 24;
779 }
780}
781
782static void generate_codebook(RoqContext *enc, roq_tempdata_t *tempdata,
783 int *points, int inputCount, roq_cell *results,
784 int size, int cbsize)
785{
786 int i, j, k;
787 int c_size = size*size/4;
788 int *buf = points;
789 int *codebook = av_malloc(6*c_size*cbsize*sizeof(int));
790 int *closest_cb;
791
792 if (size == 4)
793 closest_cb = av_malloc(6*c_size*inputCount*sizeof(int));
794 else
795 closest_cb = tempdata->closest_cb2;
796
797 ff_init_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);
798 ff_do_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);
799
800 if (size == 4)
801 av_free(closest_cb);
802
803 buf = codebook;
804 for (i=0; i<cbsize; i++)
805 for (k=0; k<c_size; k++) {
806 for(j=0; j<4; j++)
807 results->y[j] = *buf++;
808
809 results->u = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
810 results->v = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
811 results++;
812 }
813
814 av_free(codebook);
815}
816
817static void generate_new_codebooks(RoqContext *enc, roq_tempdata_t *tempData)
818{
819 int i,j;
820 roq_codebooks_t *codebooks = &tempData->codebooks;
821 int max = enc->width*enc->height/16;
822 uint8_t mb2[3*4];
823 roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);
824 uint8_t *yuvClusters=av_malloc(sizeof(int)*max*6*4);
825 int *points = av_malloc(max*6*4*sizeof(int));
826 int bias;
827
828 /* Subsample YUV data */
829 create_clusters(enc->frame_to_enc, enc->width, enc->height, yuvClusters);
830
831 /* Cast to integer and apply chroma bias */
832 for (i=0; i<max*24; i++) {
833 bias = ((i%6)<4) ? 1 : CHROMA_BIAS;
834 points[i] = bias*yuvClusters[i];
835 }
836
837 /* Create 4x4 codebooks */
838 generate_codebook(enc, tempData, points, max, results4, 4, MAX_CBS_4x4);
839
840 codebooks->numCB4 = MAX_CBS_4x4;
841
842 tempData->closest_cb2 = av_malloc(max*4*sizeof(int));
843
844 /* Create 2x2 codebooks */
845 generate_codebook(enc, tempData, points, max*4, enc->cb2x2, 2, MAX_CBS_2x2);
846
847 codebooks->numCB2 = MAX_CBS_2x2;
848
849 /* Unpack 2x2 codebook clusters */
850 for (i=0; i<codebooks->numCB2; i++)
851 unpack_roq_cell(enc->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
852
853 /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */
854 for (i=0; i<codebooks->numCB4; i++) {
855 for (j=0; j<4; j++) {
856 unpack_roq_cell(&results4[4*i + j], mb2);
857 index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
858 &enc->cb4x4[i].idx[j], 2);
859 }
860 unpack_roq_qcell(codebooks->unpacked_cb2, enc->cb4x4 + i,
861 codebooks->unpacked_cb4 + i*4*4*3);
862 enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
863 codebooks->unpacked_cb4_enlarged + i*8*8*3);
864 }
865
866 av_free(yuvClusters);
867 av_free(points);
868 av_free(results4);
869}
870
871static void roq_encode_video(RoqContext *enc)
872{
873 roq_tempdata_t tempData;
874 int i;
875
876 memset(&tempData, 0, sizeof(tempData));
877
878 create_cel_evals(enc, &tempData);
879
880 generate_new_codebooks(enc, &tempData);
881
882 if (enc->framesSinceKeyframe >= 1) {
883 motion_search(enc, 8);
884 motion_search(enc, 4);
885 }
886
887 retry_encode:
888 for (i=0; i<enc->width*enc->height/64; i++)
889 gather_data_for_cel(tempData.cel_evals + i, enc, &tempData);
890
891 /* Quake 3 can't handle chunks bigger than 65536 bytes */
892 if (tempData.mainChunkSize/8 > 65536) {
893 enc->lambda *= .8;
894 goto retry_encode;
895 }
896
897 remap_codebooks(enc, &tempData);
898
899 write_codebooks(enc, &tempData);
900
901 reconstruct_and_encode_image(enc, &tempData, enc->width, enc->height,
902 enc->width*enc->height/64);
903
904 /* Rotate frame history */
905 FFSWAP(AVFrame *, enc->current_frame, enc->last_frame);
906 FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);
907 FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);
908
909 av_free(tempData.cel_evals);
910 av_free(tempData.closest_cb2);
911
912 enc->framesSinceKeyframe++;
913}
914
915static int roq_encode_init(AVCodecContext *avctx)
916{
917 RoqContext *enc = avctx->priv_data;
918
919 av_init_random(1, &enc->randctx);
920
921 enc->framesSinceKeyframe = 0;
922 if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
923 av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
924 return -1;
925 }
926
927 if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
928 av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two\n");
929
930 if (avcodec_check_dimensions(avctx, avctx->width, avctx->height)) {
931 av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n",
932 avctx->width, avctx->height);
933 return -1;
934 }
935
936 enc->width = avctx->width;
937 enc->height = avctx->height;
938
939 enc->framesSinceKeyframe = 0;
940 enc->first_frame = 1;
941
942 enc->last_frame = &enc->frames[0];
943 enc->current_frame = &enc->frames[1];
944
945 enc->this_motion4 =
946 av_mallocz((enc->width*enc->height/16)*sizeof(motion_vect));
947
948 enc->last_motion4 =
949 av_malloc ((enc->width*enc->height/16)*sizeof(motion_vect));
950
951 enc->this_motion8 =
952 av_mallocz((enc->width*enc->height/64)*sizeof(motion_vect));
953
954 enc->last_motion8 =
955 av_malloc ((enc->width*enc->height/64)*sizeof(motion_vect));
956
957 return 0;
958}
959
960static void roq_write_video_info_chunk(RoqContext *enc)
961{
962 /* ROQ info chunk */
963 bytestream_put_le16(&enc->out_buf, RoQ_INFO);
964
965 /* Size: 8 bytes */
966 bytestream_put_le32(&enc->out_buf, 8);
967
968 /* Unused argument */
969 bytestream_put_byte(&enc->out_buf, 0x00);
970 bytestream_put_byte(&enc->out_buf, 0x00);
971
972 /* Width */
973 bytestream_put_le16(&enc->out_buf, enc->width);
974
975 /* Height */
976 bytestream_put_le16(&enc->out_buf, enc->height);
977
978 /* Unused in Quake 3, mimics the output of the real encoder */
979 bytestream_put_byte(&enc->out_buf, 0x08);
980 bytestream_put_byte(&enc->out_buf, 0x00);
981 bytestream_put_byte(&enc->out_buf, 0x04);
982 bytestream_put_byte(&enc->out_buf, 0x00);
983}
984
985static int roq_encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data)
986{
987 RoqContext *enc = avctx->priv_data;
988 AVFrame *frame= data;
989 uint8_t *buf_start = buf;
990
991 enc->out_buf = buf;
992 enc->y_stride = frame->linesize[0];
993 enc->c_stride = frame->linesize[1];
994 enc->avctx = avctx;
995
996 enc->frame_to_enc = frame;
997
998 if (frame->quality)
999 enc->lambda = frame->quality - 1;
1000 else
1001 enc->lambda = 2*ROQ_LAMBDA_SCALE;
1002
1003 /* 138 bits max per 8x8 block +
1004 * 256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */
1005 if (((enc->width*enc->height/64)*138+7)/8 + 256*(6+4) + 8 > buf_size) {
1006 av_log(avctx, AV_LOG_ERROR, " RoQ: Output buffer too small!\n");
1007 return -1;
1008 }
1009
1010 /* Check for I frame */
1011 if (enc->framesSinceKeyframe == avctx->gop_size)
1012 enc->framesSinceKeyframe = 0;
1013
1014 if (enc->first_frame) {
1015 /* Alloc memory for the reconstruction data (we must know the stride
1016 for that) */
1017 if (avctx->get_buffer(avctx, enc->current_frame) ||
1018 avctx->get_buffer(avctx, enc->last_frame)) {
1019 av_log(avctx, AV_LOG_ERROR, " RoQ: get_buffer() failed\n");
1020 return -1;
1021 }
1022
1023 /* Before the first video frame, write a "video info" chunk */
1024 roq_write_video_info_chunk(enc);
1025
1026 enc->first_frame = 0;
1027 }
1028
1029 /* Encode the actual frame */
1030 roq_encode_video(enc);
1031
1032 return enc->out_buf - buf_start;
1033}
1034
1035static int roq_encode_end(AVCodecContext *avctx)
1036{
1037 RoqContext *enc = avctx->priv_data;
1038
1039 avctx->release_buffer(avctx, enc->last_frame);
1040 avctx->release_buffer(avctx, enc->current_frame);
1041
1042 av_free(enc->this_motion4);
1043 av_free(enc->last_motion4);
1044 av_free(enc->this_motion8);
1045 av_free(enc->last_motion8);
1046
1047 return 0;
1048}
1049
1050AVCodec roq_encoder =
1051{
1052 "roqvideo",
1053 CODEC_TYPE_VIDEO,
1054 CODEC_ID_ROQ,
1055 sizeof(RoqContext),
1056 roq_encode_init,
1057 roq_encode_frame,
1058 roq_encode_end,
1059 .supported_framerates = (AVRational[]){{30,1}, {0,0}},
1060 .pix_fmts = (enum PixelFormat[]){PIX_FMT_YUV444P, -1},
1061};