Add missing comment markers to #endif directive.
[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,
670e47e1 128 int y2, int *stride, int size)
03e3e765
VS
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++)
670e47e1
VS
136 sse += bias*eval_sse(buf1[k] + (y1+i)*stride[k] + x1,
137 buf2[k] + (y2+i)*stride[k] + x2, size);
03e3e765
VS
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,
670e47e1 162 mx, my, enc->frame_to_enc->linesize, size);
03e3e765
VS
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;
03e3e765 264
670e47e1
VS
265 for (cp=0; cp<3; cp++) {
266 int stride = frame->linesize[cp];
03e3e765
VS
267 for (i=0; i<dim; i++)
268 for (j=0; j<dim; j++)
269 *mb++ = frame->data[cp][(y+i)*stride + x + j];
670e47e1 270 }
03e3e765
VS
271}
272
273/**
274 * Find the codebook with the lowest distortion from an image
275 */
276static int index_mb(uint8_t cluster[], uint8_t cb[], int numCB,
277 int *outIndex, int dim)
278{
279 int i, lDiff = INT_MAX, pick=0;
280
281 /* Diff against the others */
282 for (i=0; i<numCB; i++) {
283 int diff = squared_diff_macroblock(cluster, cb + i*dim*dim*3, dim);
284 if (diff < lDiff) {
285 lDiff = diff;
286 pick = i;
287 }
288 }
289
290 *outIndex = pick;
291 return lDiff;
292}
293
294#define EVAL_MOTION(MOTION) \
295 do { \
296 diff = eval_motion_dist(enc, j, i, MOTION, blocksize); \
297 \
298 if (diff < lowestdiff) { \
299 lowestdiff = diff; \
300 bestpick = MOTION; \
301 } \
302 } while(0)
303
304static void motion_search(RoqContext *enc, int blocksize)
305{
306 static const motion_vect offsets[8] = {
307 {{ 0,-1}},
308 {{ 0, 1}},
309 {{-1, 0}},
310 {{ 1, 0}},
311 {{-1, 1}},
312 {{ 1,-1}},
313 {{-1,-1}},
314 {{ 1, 1}},
315 };
316
317 int diff, lowestdiff, oldbest;
318 int off[3];
319 motion_vect bestpick = {{0,0}};
320 int i, j, k, offset;
321
322 motion_vect *last_motion;
323 motion_vect *this_motion;
324 motion_vect vect, vect2;
325
326 int max=(enc->width/blocksize)*enc->height/blocksize;
327
328 if (blocksize == 4) {
329 last_motion = enc->last_motion4;
330 this_motion = enc->this_motion4;
331 } else {
332 last_motion = enc->last_motion8;
333 this_motion = enc->this_motion8;
334 }
335
336 for (i=0; i<enc->height; i+=blocksize)
337 for (j=0; j<enc->width; j+=blocksize) {
338 lowestdiff = eval_motion_dist(enc, j, i, (motion_vect) {{0,0}},
339 blocksize);
340 bestpick.d[0] = 0;
341 bestpick.d[1] = 0;
342
343 if (blocksize == 4)
344 EVAL_MOTION(enc->this_motion8[(i/8)*(enc->width/8) + j/8]);
345
346 offset = (i/blocksize)*enc->width/blocksize + j/blocksize;
347 if (offset < max && offset >= 0)
348 EVAL_MOTION(last_motion[offset]);
349
350 offset++;
351 if (offset < max && offset >= 0)
352 EVAL_MOTION(last_motion[offset]);
353
354 offset = (i/blocksize + 1)*enc->width/blocksize + j/blocksize;
355 if (offset < max && offset >= 0)
356 EVAL_MOTION(last_motion[offset]);
357
358 off[0]= (i/blocksize)*enc->width/blocksize + j/blocksize - 1;
359 off[1]= off[0] - enc->width/blocksize + 1;
360 off[2]= off[1] + 1;
361
362 if (i) {
363
364 for(k=0; k<2; k++)
365 vect.d[k]= mid_pred(this_motion[off[0]].d[k],
366 this_motion[off[1]].d[k],
367 this_motion[off[2]].d[k]);
368
369 EVAL_MOTION(vect);
370 for(k=0; k<3; k++)
371 EVAL_MOTION(this_motion[off[k]]);
372 } else if(j)
373 EVAL_MOTION(this_motion[off[0]]);
374
375 vect = bestpick;
376
377 oldbest = -1;
378 while (oldbest != lowestdiff) {
379 oldbest = lowestdiff;
380 for (k=0; k<8; k++) {
381 vect2 = vect;
382 vect2.d[0] += offsets[k].d[0];
383 vect2.d[1] += offsets[k].d[1];
384 EVAL_MOTION(vect2);
385 }
386 vect = bestpick;
387 }
388 offset = (i/blocksize)*enc->width/blocksize + j/blocksize;
389 this_motion[offset] = bestpick;
390 }
391}
392
393/**
394 * Gets distortion for all options available to a subcel
395 */
396static void gather_data_for_subcel(subcel_evaluation_t *subcel, int x,
397 int y, RoqContext *enc, roq_tempdata_t *tempData)
398{
399 uint8_t mb4[4*4*3];
400 uint8_t mb2[2*2*3];
401 int cluster_index;
402 int i, best_dist;
403
404 static const int bitsUsed[4] = {2, 10, 10, 34};
405
406 if (enc->framesSinceKeyframe >= 1) {
407 subcel->motion = enc->this_motion4[y*enc->width/16 + x/4];
408
409 subcel->eval_dist[RoQ_ID_FCC] =
410 eval_motion_dist(enc, x, y,
411 enc->this_motion4[y*enc->width/16 + x/4], 4);
412 } else
413 subcel->eval_dist[RoQ_ID_FCC] = INT_MAX;
414
415 if (enc->framesSinceKeyframe >= 2)
416 subcel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
417 enc->current_frame->data, x,
670e47e1
VS
418 y, x, y,
419 enc->frame_to_enc->linesize,
420 4);
03e3e765
VS
421 else
422 subcel->eval_dist[RoQ_ID_MOT] = INT_MAX;
423
424 cluster_index = y*enc->width/16 + x/4;
425
426 get_frame_mb(enc->frame_to_enc, x, y, mb4, 4);
427
428 subcel->eval_dist[RoQ_ID_SLD] = index_mb(mb4,
429 tempData->codebooks.unpacked_cb4,
430 tempData->codebooks.numCB4,
431 &subcel->cbEntry, 4);
432
433 subcel->eval_dist[RoQ_ID_CCC] = 0;
434
435 for(i=0;i<4;i++) {
436 subcel->subCels[i] = tempData->closest_cb2[cluster_index*4+i];
437
438 get_frame_mb(enc->frame_to_enc, x+2*(i&1),
439 y+(i&2), mb2, 2);
440
441 subcel->eval_dist[RoQ_ID_CCC] +=
442 squared_diff_macroblock(tempData->codebooks.unpacked_cb2 + subcel->subCels[i]*2*2*3, mb2, 2);
443 }
444
445 best_dist = INT_MAX;
446 for (i=0; i<4; i++)
447 if (ROQ_LAMBDA_SCALE*subcel->eval_dist[i] + enc->lambda*bitsUsed[i] <
448 best_dist) {
449 subcel->best_coding = i;
450 subcel->best_bit_use = bitsUsed[i];
451 best_dist = ROQ_LAMBDA_SCALE*subcel->eval_dist[i] +
452 enc->lambda*bitsUsed[i];
453 }
454}
455
456/**
457 * Gets distortion for all options available to a cel
458 */
459static void gather_data_for_cel(cel_evaluation_t *cel, RoqContext *enc,
460 roq_tempdata_t *tempData)
461{
462 uint8_t mb8[8*8*3];
463 int index = cel->sourceY*enc->width/64 + cel->sourceX/8;
464 int i, j, best_dist, divide_bit_use;
465
466 int bitsUsed[4] = {2, 10, 10, 0};
467
468 if (enc->framesSinceKeyframe >= 1) {
469 cel->motion = enc->this_motion8[index];
470
471 cel->eval_dist[RoQ_ID_FCC] =
472 eval_motion_dist(enc, cel->sourceX, cel->sourceY,
473 enc->this_motion8[index], 8);
474 } else
475 cel->eval_dist[RoQ_ID_FCC] = INT_MAX;
476
477 if (enc->framesSinceKeyframe >= 2)
478 cel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
479 enc->current_frame->data,
480 cel->sourceX, cel->sourceY,
481 cel->sourceX, cel->sourceY,
670e47e1 482 enc->frame_to_enc->linesize, 8);
03e3e765
VS
483 else
484 cel->eval_dist[RoQ_ID_MOT] = INT_MAX;
485
486 get_frame_mb(enc->frame_to_enc, cel->sourceX, cel->sourceY, mb8, 8);
487
488 cel->eval_dist[RoQ_ID_SLD] =
489 index_mb(mb8, tempData->codebooks.unpacked_cb4_enlarged,
490 tempData->codebooks.numCB4, &cel->cbEntry, 8);
491
492 gather_data_for_subcel(cel->subCels + 0, cel->sourceX+0, cel->sourceY+0, enc, tempData);
493 gather_data_for_subcel(cel->subCels + 1, cel->sourceX+4, cel->sourceY+0, enc, tempData);
494 gather_data_for_subcel(cel->subCels + 2, cel->sourceX+0, cel->sourceY+4, enc, tempData);
495 gather_data_for_subcel(cel->subCels + 3, cel->sourceX+4, cel->sourceY+4, enc, tempData);
496
497 cel->eval_dist[RoQ_ID_CCC] = 0;
498 divide_bit_use = 0;
499 for (i=0; i<4; i++) {
500 cel->eval_dist[RoQ_ID_CCC] +=
501 cel->subCels[i].eval_dist[cel->subCels[i].best_coding];
502 divide_bit_use += cel->subCels[i].best_bit_use;
503 }
504
505 best_dist = INT_MAX;
506 bitsUsed[3] = 2 + divide_bit_use;
507
508 for (i=0; i<4; i++)
509 if (ROQ_LAMBDA_SCALE*cel->eval_dist[i] + enc->lambda*bitsUsed[i] <
510 best_dist) {
511 cel->best_coding = i;
512 best_dist = ROQ_LAMBDA_SCALE*cel->eval_dist[i] +
513 enc->lambda*bitsUsed[i];
514 }
515
516 tempData->used_option[cel->best_coding]++;
517 tempData->mainChunkSize += bitsUsed[cel->best_coding];
518
519 if (cel->best_coding == RoQ_ID_SLD)
520 tempData->codebooks.usedCB4[cel->cbEntry]++;
521
522 if (cel->best_coding == RoQ_ID_CCC)
523 for (i=0; i<4; i++) {
524 if (cel->subCels[i].best_coding == RoQ_ID_SLD)
525 tempData->codebooks.usedCB4[cel->subCels[i].cbEntry]++;
526 else if (cel->subCels[i].best_coding == RoQ_ID_CCC)
527 for (j=0; j<4; j++)
528 tempData->codebooks.usedCB2[cel->subCels[i].subCels[j]]++;
529 }
530}
531
532static void remap_codebooks(RoqContext *enc, roq_tempdata_t *tempData)
533{
534 int i, j, idx=0;
535
536 /* Make remaps for the final codebook usage */
537 for (i=0; i<MAX_CBS_4x4; i++) {
538 if (tempData->codebooks.usedCB4[i]) {
539 tempData->i2f4[i] = idx;
540 tempData->f2i4[idx] = i;
541 for (j=0; j<4; j++)
542 tempData->codebooks.usedCB2[enc->cb4x4[i].idx[j]]++;
543 idx++;
544 }
545 }
546
547 tempData->numCB4 = idx;
548
549 idx = 0;
550 for (i=0; i<MAX_CBS_2x2; i++) {
551 if (tempData->codebooks.usedCB2[i]) {
552 tempData->i2f2[i] = idx;
553 tempData->f2i2[idx] = i;
554 idx++;
555 }
556 }
557 tempData->numCB2 = idx;
558
559}
560
561/**
562 * Write codebook chunk
563 */
564static void write_codebooks(RoqContext *enc, roq_tempdata_t *tempData)
565{
566 int i, j;
567 uint8_t **outp= &enc->out_buf;
568
569 if (tempData->numCB2) {
570 bytestream_put_le16(outp, RoQ_QUAD_CODEBOOK);
571 bytestream_put_le32(outp, tempData->numCB2*6 + tempData->numCB4*4);
572 bytestream_put_byte(outp, tempData->numCB4);
573 bytestream_put_byte(outp, tempData->numCB2);
574
575 for (i=0; i<tempData->numCB2; i++) {
576 bytestream_put_buffer(outp, enc->cb2x2[tempData->f2i2[i]].y, 4);
577 bytestream_put_byte(outp, enc->cb2x2[tempData->f2i2[i]].u);
578 bytestream_put_byte(outp, enc->cb2x2[tempData->f2i2[i]].v);
579 }
580
581 for (i=0; i<tempData->numCB4; i++)
582 for (j=0; j<4; j++)
583 bytestream_put_byte(outp, tempData->i2f2[enc->cb4x4[tempData->f2i4[i]].idx[j]]);
584
585 }
586}
587
588static inline uint8_t motion_arg(motion_vect mot)
589{
590 uint8_t ax = 8 - ((uint8_t) mot.d[0]);
591 uint8_t ay = 8 - ((uint8_t) mot.d[1]);
592 return ((ax&15)<<4) | (ay&15);
593}
594
595typedef struct
596{
597 int typeSpool;
598 int typeSpoolLength;
599 uint8_t argumentSpool[64];
600 uint8_t *args;
601 uint8_t **pout;
602} CodingSpool;
603
604/* NOTE: Typecodes must be spooled AFTER arguments!! */
605static void write_typecode(CodingSpool *s, uint8_t type)
606{
607 s->typeSpool |= ((type) & 3) << (14 - s->typeSpoolLength);
608 s->typeSpoolLength += 2;
609 if (s->typeSpoolLength == 16) {
610 bytestream_put_le16(s->pout, s->typeSpool);
611 bytestream_put_buffer(s->pout, s->argumentSpool,
612 s->args - s->argumentSpool);
613 s->typeSpoolLength = 0;
614 s->typeSpool = 0;
615 s->args = s->argumentSpool;
616 }
617}
618
619static void reconstruct_and_encode_image(RoqContext *enc, roq_tempdata_t *tempData, int w, int h, int numBlocks)
620{
621 int i, j, k;
622 int x, y;
623 int subX, subY;
624 int dist=0;
625
626 roq_qcell *qcell;
627 cel_evaluation_t *eval;
628
629 CodingSpool spool;
630
631 spool.typeSpool=0;
632 spool.typeSpoolLength=0;
633 spool.args = spool.argumentSpool;
634 spool.pout = &enc->out_buf;
635
636 if (tempData->used_option[RoQ_ID_CCC]%2)
637 tempData->mainChunkSize+=8; //FIXME
638
639 /* Write the video chunk header */
640 bytestream_put_le16(&enc->out_buf, RoQ_QUAD_VQ);
641 bytestream_put_le32(&enc->out_buf, tempData->mainChunkSize/8);
642 bytestream_put_byte(&enc->out_buf, 0x0);
643 bytestream_put_byte(&enc->out_buf, 0x0);
644
645 for (i=0; i<numBlocks; i++) {
646 eval = tempData->cel_evals + i;
647
648 x = eval->sourceX;
649 y = eval->sourceY;
650 dist += eval->eval_dist[eval->best_coding];
651
652 switch (eval->best_coding) {
653 case RoQ_ID_MOT:
654 write_typecode(&spool, RoQ_ID_MOT);
655 break;
656
657 case RoQ_ID_FCC:
658 bytestream_put_byte(&spool.args, motion_arg(eval->motion));
659
660 write_typecode(&spool, RoQ_ID_FCC);
661 ff_apply_motion_8x8(enc, x, y,
662 eval->motion.d[0], eval->motion.d[1]);
663 break;
664
665 case RoQ_ID_SLD:
666 bytestream_put_byte(&spool.args, tempData->i2f4[eval->cbEntry]);
667 write_typecode(&spool, RoQ_ID_SLD);
668
669 qcell = enc->cb4x4 + eval->cbEntry;
670 ff_apply_vector_4x4(enc, x , y , enc->cb2x2 + qcell->idx[0]);
671 ff_apply_vector_4x4(enc, x+4, y , enc->cb2x2 + qcell->idx[1]);
672 ff_apply_vector_4x4(enc, x , y+4, enc->cb2x2 + qcell->idx[2]);
673 ff_apply_vector_4x4(enc, x+4, y+4, enc->cb2x2 + qcell->idx[3]);
674 break;
675
676 case RoQ_ID_CCC:
677 write_typecode(&spool, RoQ_ID_CCC);
678
679 for (j=0; j<4; j++) {
680 subX = x + 4*(j&1);
681 subY = y + 2*(j&2);
682
683 switch(eval->subCels[j].best_coding) {
684 case RoQ_ID_MOT:
685 break;
686
687 case RoQ_ID_FCC:
688 bytestream_put_byte(&spool.args,
689 motion_arg(eval->subCels[j].motion));
690
691 ff_apply_motion_4x4(enc, subX, subY,
692 eval->subCels[j].motion.d[0],
693 eval->subCels[j].motion.d[1]);
694 break;
695
696 case RoQ_ID_SLD:
697 bytestream_put_byte(&spool.args,
698 tempData->i2f4[eval->subCels[j].cbEntry]);
699
700 qcell = enc->cb4x4 + eval->subCels[j].cbEntry;
701
702 ff_apply_vector_2x2(enc, subX , subY ,
703 enc->cb2x2 + qcell->idx[0]);
704 ff_apply_vector_2x2(enc, subX+2, subY ,
705 enc->cb2x2 + qcell->idx[1]);
706 ff_apply_vector_2x2(enc, subX , subY+2,
707 enc->cb2x2 + qcell->idx[2]);
708 ff_apply_vector_2x2(enc, subX+2, subY+2,
709 enc->cb2x2 + qcell->idx[3]);
710 break;
711
712 case RoQ_ID_CCC:
713 for (k=0; k<4; k++) {
714 int cb_idx = eval->subCels[j].subCels[k];
715 bytestream_put_byte(&spool.args,
716 tempData->i2f2[cb_idx]);
717
718 ff_apply_vector_2x2(enc, subX + 2*(k&1), subY + (k&2),
719 enc->cb2x2 + cb_idx);
720 }
721 break;
722 }
723 write_typecode(&spool, eval->subCels[j].best_coding);
724 }
725 break;
726 }
727 }
728
729 /* Flush the remainder of the argument/type spool */
730 while (spool.typeSpoolLength)
731 write_typecode(&spool, 0x0);
732
733#if 0
734 uint8_t *fdata[3] = {enc->frame_to_enc->data[0],
735 enc->frame_to_enc->data[1],
736 enc->frame_to_enc->data[2]};
737 uint8_t *cdata[3] = {enc->current_frame->data[0],
738 enc->current_frame->data[1],
739 enc->current_frame->data[2]};
740 av_log(enc->avctx, AV_LOG_ERROR, "Expected distortion: %i Actual: %i\n",
741 dist,
742 block_sse(fdata, cdata, 0, 0, 0, 0,
670e47e1 743 enc->frame_to_enc->linesize, enc->width)); //WARNING: Square dimensions implied...
03e3e765
VS
744#endif
745}
746
747
748/**
749 * Create a single YUV cell from a 2x2 section of the image
750 */
751static inline void frame_block_to_cell(uint8_t *block, uint8_t **data,
752 int top, int left, int *stride)
753{
754 int i, j, u=0, v=0;
755
756 for (i=0; i<2; i++)
757 for (j=0; j<2; j++) {
758 int x = (top+i)*stride[0] + left + j;
759 *block++ = data[0][x];
670e47e1 760 x = (top+i)*stride[1] + left + j;
03e3e765
VS
761 u += data[1][x];
762 v += data[2][x];
763 }
764
765 *block++ = (u+2)/4;
766 *block++ = (v+2)/4;
767}
768
769/**
770 * Creates YUV clusters for the entire image
771 */
772static void create_clusters(AVFrame *frame, int w, int h, uint8_t *yuvClusters)
773{
774 int i, j, k, l;
775
776 for (i=0; i<h; i+=4)
777 for (j=0; j<w; j+=4) {
778 for (k=0; k < 2; k++)
779 for (l=0; l < 2; l++)
780 frame_block_to_cell(yuvClusters + (l + 2*k)*6, frame->data,
781 i+2*k, j+2*l, frame->linesize);
782 yuvClusters += 24;
783 }
784}
785
786static void generate_codebook(RoqContext *enc, roq_tempdata_t *tempdata,
787 int *points, int inputCount, roq_cell *results,
788 int size, int cbsize)
789{
790 int i, j, k;
791 int c_size = size*size/4;
792 int *buf = points;
793 int *codebook = av_malloc(6*c_size*cbsize*sizeof(int));
794 int *closest_cb;
795
796 if (size == 4)
797 closest_cb = av_malloc(6*c_size*inputCount*sizeof(int));
798 else
799 closest_cb = tempdata->closest_cb2;
800
801 ff_init_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);
802 ff_do_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);
803
804 if (size == 4)
805 av_free(closest_cb);
806
807 buf = codebook;
808 for (i=0; i<cbsize; i++)
809 for (k=0; k<c_size; k++) {
810 for(j=0; j<4; j++)
811 results->y[j] = *buf++;
812
813 results->u = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
814 results->v = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
815 results++;
816 }
817
818 av_free(codebook);
819}
820
821static void generate_new_codebooks(RoqContext *enc, roq_tempdata_t *tempData)
822{
823 int i,j;
824 roq_codebooks_t *codebooks = &tempData->codebooks;
825 int max = enc->width*enc->height/16;
826 uint8_t mb2[3*4];
827 roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);
828 uint8_t *yuvClusters=av_malloc(sizeof(int)*max*6*4);
829 int *points = av_malloc(max*6*4*sizeof(int));
830 int bias;
831
832 /* Subsample YUV data */
833 create_clusters(enc->frame_to_enc, enc->width, enc->height, yuvClusters);
834
835 /* Cast to integer and apply chroma bias */
836 for (i=0; i<max*24; i++) {
837 bias = ((i%6)<4) ? 1 : CHROMA_BIAS;
838 points[i] = bias*yuvClusters[i];
839 }
840
841 /* Create 4x4 codebooks */
842 generate_codebook(enc, tempData, points, max, results4, 4, MAX_CBS_4x4);
843
844 codebooks->numCB4 = MAX_CBS_4x4;
845
846 tempData->closest_cb2 = av_malloc(max*4*sizeof(int));
847
848 /* Create 2x2 codebooks */
849 generate_codebook(enc, tempData, points, max*4, enc->cb2x2, 2, MAX_CBS_2x2);
850
851 codebooks->numCB2 = MAX_CBS_2x2;
852
853 /* Unpack 2x2 codebook clusters */
854 for (i=0; i<codebooks->numCB2; i++)
855 unpack_roq_cell(enc->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
856
857 /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */
858 for (i=0; i<codebooks->numCB4; i++) {
859 for (j=0; j<4; j++) {
860 unpack_roq_cell(&results4[4*i + j], mb2);
861 index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
862 &enc->cb4x4[i].idx[j], 2);
863 }
864 unpack_roq_qcell(codebooks->unpacked_cb2, enc->cb4x4 + i,
865 codebooks->unpacked_cb4 + i*4*4*3);
866 enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
867 codebooks->unpacked_cb4_enlarged + i*8*8*3);
868 }
869
870 av_free(yuvClusters);
871 av_free(points);
872 av_free(results4);
873}
874
875static void roq_encode_video(RoqContext *enc)
876{
877 roq_tempdata_t tempData;
878 int i;
879
880 memset(&tempData, 0, sizeof(tempData));
881
882 create_cel_evals(enc, &tempData);
883
884 generate_new_codebooks(enc, &tempData);
885
886 if (enc->framesSinceKeyframe >= 1) {
887 motion_search(enc, 8);
888 motion_search(enc, 4);
889 }
890
891 retry_encode:
892 for (i=0; i<enc->width*enc->height/64; i++)
893 gather_data_for_cel(tempData.cel_evals + i, enc, &tempData);
894
895 /* Quake 3 can't handle chunks bigger than 65536 bytes */
896 if (tempData.mainChunkSize/8 > 65536) {
897 enc->lambda *= .8;
898 goto retry_encode;
899 }
900
901 remap_codebooks(enc, &tempData);
902
903 write_codebooks(enc, &tempData);
904
905 reconstruct_and_encode_image(enc, &tempData, enc->width, enc->height,
906 enc->width*enc->height/64);
907
908 /* Rotate frame history */
909 FFSWAP(AVFrame *, enc->current_frame, enc->last_frame);
910 FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);
911 FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);
912
913 av_free(tempData.cel_evals);
914 av_free(tempData.closest_cb2);
915
916 enc->framesSinceKeyframe++;
917}
918
919static int roq_encode_init(AVCodecContext *avctx)
920{
921 RoqContext *enc = avctx->priv_data;
922
923 av_init_random(1, &enc->randctx);
924
925 enc->framesSinceKeyframe = 0;
926 if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
927 av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
928 return -1;
929 }
930
931 if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
932 av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two\n");
933
934 if (avcodec_check_dimensions(avctx, avctx->width, avctx->height)) {
935 av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n",
936 avctx->width, avctx->height);
937 return -1;
938 }
939
940 enc->width = avctx->width;
941 enc->height = avctx->height;
942
943 enc->framesSinceKeyframe = 0;
944 enc->first_frame = 1;
945
946 enc->last_frame = &enc->frames[0];
947 enc->current_frame = &enc->frames[1];
948
949 enc->this_motion4 =
950 av_mallocz((enc->width*enc->height/16)*sizeof(motion_vect));
951
952 enc->last_motion4 =
953 av_malloc ((enc->width*enc->height/16)*sizeof(motion_vect));
954
955 enc->this_motion8 =
956 av_mallocz((enc->width*enc->height/64)*sizeof(motion_vect));
957
958 enc->last_motion8 =
959 av_malloc ((enc->width*enc->height/64)*sizeof(motion_vect));
960
961 return 0;
962}
963
964static void roq_write_video_info_chunk(RoqContext *enc)
965{
966 /* ROQ info chunk */
967 bytestream_put_le16(&enc->out_buf, RoQ_INFO);
968
969 /* Size: 8 bytes */
970 bytestream_put_le32(&enc->out_buf, 8);
971
972 /* Unused argument */
973 bytestream_put_byte(&enc->out_buf, 0x00);
974 bytestream_put_byte(&enc->out_buf, 0x00);
975
976 /* Width */
977 bytestream_put_le16(&enc->out_buf, enc->width);
978
979 /* Height */
980 bytestream_put_le16(&enc->out_buf, enc->height);
981
982 /* Unused in Quake 3, mimics the output of the real encoder */
983 bytestream_put_byte(&enc->out_buf, 0x08);
984 bytestream_put_byte(&enc->out_buf, 0x00);
985 bytestream_put_byte(&enc->out_buf, 0x04);
986 bytestream_put_byte(&enc->out_buf, 0x00);
987}
988
989static int roq_encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data)
990{
991 RoqContext *enc = avctx->priv_data;
992 AVFrame *frame= data;
993 uint8_t *buf_start = buf;
994
995 enc->out_buf = buf;
996 enc->y_stride = frame->linesize[0];
997 enc->c_stride = frame->linesize[1];
998 enc->avctx = avctx;
999
1000 enc->frame_to_enc = frame;
1001
1002 if (frame->quality)
1003 enc->lambda = frame->quality - 1;
1004 else
1005 enc->lambda = 2*ROQ_LAMBDA_SCALE;
1006
1007 /* 138 bits max per 8x8 block +
1008 * 256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */
1009 if (((enc->width*enc->height/64)*138+7)/8 + 256*(6+4) + 8 > buf_size) {
1010 av_log(avctx, AV_LOG_ERROR, " RoQ: Output buffer too small!\n");
1011 return -1;
1012 }
1013
1014 /* Check for I frame */
1015 if (enc->framesSinceKeyframe == avctx->gop_size)
1016 enc->framesSinceKeyframe = 0;
1017
1018 if (enc->first_frame) {
1019 /* Alloc memory for the reconstruction data (we must know the stride
1020 for that) */
1021 if (avctx->get_buffer(avctx, enc->current_frame) ||
1022 avctx->get_buffer(avctx, enc->last_frame)) {
1023 av_log(avctx, AV_LOG_ERROR, " RoQ: get_buffer() failed\n");
1024 return -1;
1025 }
1026
1027 /* Before the first video frame, write a "video info" chunk */
1028 roq_write_video_info_chunk(enc);
1029
1030 enc->first_frame = 0;
1031 }
1032
1033 /* Encode the actual frame */
1034 roq_encode_video(enc);
1035
1036 return enc->out_buf - buf_start;
1037}
1038
1039static int roq_encode_end(AVCodecContext *avctx)
1040{
1041 RoqContext *enc = avctx->priv_data;
1042
1043 avctx->release_buffer(avctx, enc->last_frame);
1044 avctx->release_buffer(avctx, enc->current_frame);
1045
1046 av_free(enc->this_motion4);
1047 av_free(enc->last_motion4);
1048 av_free(enc->this_motion8);
1049 av_free(enc->last_motion8);
1050
1051 return 0;
1052}
1053
1054AVCodec roq_encoder =
1055{
1056 "roqvideo",
1057 CODEC_TYPE_VIDEO,
1058 CODEC_ID_ROQ,
1059 sizeof(RoqContext),
1060 roq_encode_init,
1061 roq_encode_frame,
1062 roq_encode_end,
1063 .supported_framerates = (AVRational[]){{30,1}, {0,0}},
1064 .pix_fmts = (enum PixelFormat[]){PIX_FMT_YUV444P, -1},
1065};