4 * Copyright (C) 2007 Vitor Sessak <vitor1001@gmail.com>
5 * Copyright (C) 2004-2007 Eric Lasota
6 * Based on RoQ specs (C) 2001 Tim Ferguson
8 * This file is part of FFmpeg.
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.
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.
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
27 * id RoQ encoder by Vitor. Based on the Switchblade3 library and the
28 * Switchblade3 FFmpeg glue by Eric Lasota.
36 * CODEBOOK - 2 + 8 bits
37 * SUBDIVIDE - 2 + combined subcel cost
42 * CODEBOOK - 2 + 8 bits
43 * SUBDIVIDE - 2 + 4*8 bits
45 * Maximum cost: 138 bits per cel
47 * Proper evaluation requires LCD fraction comparison, which requires
48 * Squared Error (SE) loss * savings increase
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)
59 #include "libavutil/attributes.h"
60 #include "libavutil/lfg.h"
61 #include "libavutil/opt.h"
63 #include "bytestream.h"
71 * Maximum number of generated 4x4 codebooks. Can't be 256 to workaround a
74 #define MAX_CBS_4x4 256
76 #define MAX_CBS_2x2 256 ///< Maximum number of 2x2 codebooks.
78 /* The cast is useful when multiplying it by INT_MAX */
79 #define ROQ_LAMBDA_SCALE ((uint64_t) FF_LAMBDA_SCALE)
81 typedef struct RoqEncContext {
86 motion_vect *this_motion4;
87 motion_vect *last_motion4;
89 motion_vect *this_motion8;
90 motion_vect *last_motion8;
92 unsigned int framesSinceKeyframe;
94 const AVFrame *frame_to_enc;
96 struct RoqTempData *tmpData;
99 int quake3_compat; // Quake 3 compatibility option
102 /* Macroblock support functions */
103 static void unpack_roq_cell(roq_cell *cell, uint8_t u[4*3])
105 memcpy(u , cell->y, 4);
106 memset(u+4, cell->u, 4);
107 memset(u+8, cell->v, 4);
110 static void unpack_roq_qcell(uint8_t cb2[], roq_qcell *qcell, uint8_t u[4*4*3])
113 static const int offsets[4] = {0, 2, 8, 10};
115 for (cp=0; cp<3; cp++)
116 for (i=0; i<4; i++) {
117 u[4*4*cp + offsets[i] ] = cb2[qcell->idx[i]*2*2*3 + 4*cp ];
118 u[4*4*cp + offsets[i]+1] = cb2[qcell->idx[i]*2*2*3 + 4*cp+1];
119 u[4*4*cp + offsets[i]+4] = cb2[qcell->idx[i]*2*2*3 + 4*cp+2];
120 u[4*4*cp + offsets[i]+5] = cb2[qcell->idx[i]*2*2*3 + 4*cp+3];
125 static void enlarge_roq_mb4(uint8_t base[3*16], uint8_t u[3*64])
129 for(cp=0; cp<3; cp++)
132 *u++ = base[(y/2)*4 + (x/2) + 16*cp];
135 static inline int square(int x)
140 static inline int eval_sse(const uint8_t *a, const uint8_t *b, int count)
145 diff += square(*b++ - *a++);
150 // FIXME Could use DSPContext.sse, but it is not so speed critical (used
151 // just for motion estimation).
152 static int block_sse(uint8_t * const *buf1, uint8_t * const *buf2, int x1, int y1,
153 int x2, int y2, const int *stride1, const int *stride2, int size)
158 for (k=0; k<3; k++) {
159 int bias = (k ? CHROMA_BIAS : 4);
160 for (i=0; i<size; i++)
161 sse += bias*eval_sse(buf1[k] + (y1+i)*stride1[k] + x1,
162 buf2[k] + (y2+i)*stride2[k] + x2, size);
168 static int eval_motion_dist(RoqEncContext *enc, int x, int y, motion_vect vect,
171 RoqContext *const roq = &enc->common;
175 if (mx < -7 || mx > 7)
178 if (my < -7 || my > 7)
184 if ((unsigned) mx > roq->width-size || (unsigned) my > roq->height-size)
187 return block_sse(enc->frame_to_enc->data, roq->last_frame->data, x, y,
189 enc->frame_to_enc->linesize, roq->last_frame->linesize,
194 * @return distortion between two macroblocks
196 static inline int squared_diff_macroblock(uint8_t a[], uint8_t b[], int size)
200 for(cp=0;cp<3;cp++) {
201 int bias = (cp ? CHROMA_BIAS : 4);
202 sdiff += bias*eval_sse(a, b, size*size);
210 typedef struct SubcelEvaluation {
220 typedef struct CelEvaluation {
224 SubcelEvaluation subCels[4];
229 int sourceX, sourceY;
232 typedef struct RoqCodebooks {
235 int usedCB2[MAX_CBS_2x2];
236 int usedCB4[MAX_CBS_4x4];
237 uint8_t unpacked_cb2[MAX_CBS_2x2*2*2*3];
238 uint8_t unpacked_cb4[MAX_CBS_4x4*4*4*3];
239 uint8_t unpacked_cb4_enlarged[MAX_CBS_4x4*8*8*3];
245 typedef struct RoqTempData
247 CelEvaluation *cel_evals;
249 int f2i4[MAX_CBS_4x4];
250 int i2f4[MAX_CBS_4x4];
251 int f2i2[MAX_CBS_2x2];
252 int i2f2[MAX_CBS_2x2];
259 RoqCodebooks codebooks;
266 * Initialize cel evaluators and set their source coordinates
268 static int create_cel_evals(RoqContext *enc, RoqTempdata *tempData)
272 tempData->cel_evals = av_malloc_array(enc->width*enc->height/64, sizeof(CelEvaluation));
273 if (!tempData->cel_evals)
274 return AVERROR(ENOMEM);
276 /* Map to the ROQ quadtree order */
277 for (y=0; y<enc->height; y+=16)
278 for (x=0; x<enc->width; x+=16)
280 tempData->cel_evals[n ].sourceX = x + (i&1)*8;
281 tempData->cel_evals[n++].sourceY = y + (i&2)*4;
288 * Get macroblocks from parts of the image
290 static void get_frame_mb(const AVFrame *frame, int x, int y, uint8_t mb[], int dim)
294 for (cp=0; cp<3; cp++) {
295 int stride = frame->linesize[cp];
296 for (i=0; i<dim; i++)
297 for (j=0; j<dim; j++)
298 *mb++ = frame->data[cp][(y+i)*stride + x + j];
303 * Find the codebook with the lowest distortion from an image
305 static int index_mb(uint8_t cluster[], uint8_t cb[], int numCB,
306 int *outIndex, int dim)
308 int i, lDiff = INT_MAX, pick=0;
310 /* Diff against the others */
311 for (i=0; i<numCB; i++) {
312 int diff = squared_diff_macroblock(cluster, cb + i*dim*dim*3, dim);
323 #define EVAL_MOTION(MOTION) \
325 diff = eval_motion_dist(enc, j, i, MOTION, blocksize); \
327 if (diff < lowestdiff) { \
333 static void motion_search(RoqEncContext *enc, int blocksize)
335 static const motion_vect offsets[8] = {
346 RoqContext *const roq = &enc->common;
347 int diff, lowestdiff, oldbest;
349 motion_vect bestpick = {{0,0}};
352 motion_vect *last_motion;
353 motion_vect *this_motion;
354 motion_vect vect, vect2;
355 const int max = (roq->width / blocksize) * roq->height / blocksize;
357 if (blocksize == 4) {
358 last_motion = enc->last_motion4;
359 this_motion = enc->this_motion4;
361 last_motion = enc->last_motion8;
362 this_motion = enc->this_motion8;
365 for (i = 0; i< roq->height; i += blocksize)
366 for (j = 0; j < roq->width; j += blocksize) {
367 lowestdiff = eval_motion_dist(enc, j, i, (motion_vect) {{0,0}},
373 EVAL_MOTION(enc->this_motion8[(i/8) * (roq->width/8) + j/8]);
375 offset = (i/blocksize) * roq->width / blocksize + j / blocksize;
376 if (offset < max && offset >= 0)
377 EVAL_MOTION(last_motion[offset]);
380 if (offset < max && offset >= 0)
381 EVAL_MOTION(last_motion[offset]);
383 offset = (i/blocksize + 1) * roq->width / blocksize + j / blocksize;
384 if (offset < max && offset >= 0)
385 EVAL_MOTION(last_motion[offset]);
387 off[0]= (i/blocksize) * roq->width / blocksize + j/blocksize - 1;
388 off[1]= off[0] - roq->width / blocksize + 1;
394 vect.d[k]= mid_pred(this_motion[off[0]].d[k],
395 this_motion[off[1]].d[k],
396 this_motion[off[2]].d[k]);
400 EVAL_MOTION(this_motion[off[k]]);
402 EVAL_MOTION(this_motion[off[0]]);
407 while (oldbest != lowestdiff) {
408 oldbest = lowestdiff;
409 for (k=0; k<8; k++) {
411 vect2.d[0] += offsets[k].d[0];
412 vect2.d[1] += offsets[k].d[1];
417 offset = (i/blocksize) * roq->width / blocksize + j/blocksize;
418 this_motion[offset] = bestpick;
423 * Get distortion for all options available to a subcel
425 static void gather_data_for_subcel(SubcelEvaluation *subcel, int x,
426 int y, RoqEncContext *enc, RoqTempdata *tempData)
428 RoqContext *const roq = &enc->common;
434 static const int bitsUsed[4] = {2, 10, 10, 34};
436 if (enc->framesSinceKeyframe >= 1) {
437 subcel->motion = enc->this_motion4[y * roq->width / 16 + x / 4];
439 subcel->eval_dist[RoQ_ID_FCC] =
440 eval_motion_dist(enc, x, y,
441 enc->this_motion4[y * roq->width / 16 + x / 4], 4);
443 subcel->eval_dist[RoQ_ID_FCC] = INT_MAX;
445 if (enc->framesSinceKeyframe >= 2)
446 subcel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
447 roq->current_frame->data, x,
449 enc->frame_to_enc->linesize,
450 roq->current_frame->linesize,
453 subcel->eval_dist[RoQ_ID_MOT] = INT_MAX;
455 cluster_index = y * roq->width / 16 + x / 4;
457 get_frame_mb(enc->frame_to_enc, x, y, mb4, 4);
459 subcel->eval_dist[RoQ_ID_SLD] = index_mb(mb4,
460 tempData->codebooks.unpacked_cb4,
461 tempData->codebooks.numCB4,
462 &subcel->cbEntry, 4);
464 subcel->eval_dist[RoQ_ID_CCC] = 0;
467 subcel->subCels[i] = tempData->closest_cb2[cluster_index*4+i];
469 get_frame_mb(enc->frame_to_enc, x+2*(i&1),
472 subcel->eval_dist[RoQ_ID_CCC] +=
473 squared_diff_macroblock(tempData->codebooks.unpacked_cb2 + subcel->subCels[i]*2*2*3, mb2, 2);
478 if (ROQ_LAMBDA_SCALE*subcel->eval_dist[i] + enc->lambda*bitsUsed[i] <
480 subcel->best_coding = i;
481 subcel->best_bit_use = bitsUsed[i];
482 best_dist = ROQ_LAMBDA_SCALE*subcel->eval_dist[i] +
483 enc->lambda*bitsUsed[i];
488 * Get distortion for all options available to a cel
490 static void gather_data_for_cel(CelEvaluation *cel, RoqEncContext *enc,
491 RoqTempdata *tempData)
493 RoqContext *const roq = &enc->common;
495 int index = cel->sourceY * roq->width / 64 + cel->sourceX/8;
496 int i, j, best_dist, divide_bit_use;
498 int bitsUsed[4] = {2, 10, 10, 0};
500 if (enc->framesSinceKeyframe >= 1) {
501 cel->motion = enc->this_motion8[index];
503 cel->eval_dist[RoQ_ID_FCC] =
504 eval_motion_dist(enc, cel->sourceX, cel->sourceY,
505 enc->this_motion8[index], 8);
507 cel->eval_dist[RoQ_ID_FCC] = INT_MAX;
509 if (enc->framesSinceKeyframe >= 2)
510 cel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
511 roq->current_frame->data,
512 cel->sourceX, cel->sourceY,
513 cel->sourceX, cel->sourceY,
514 enc->frame_to_enc->linesize,
515 roq->current_frame->linesize,8);
517 cel->eval_dist[RoQ_ID_MOT] = INT_MAX;
519 get_frame_mb(enc->frame_to_enc, cel->sourceX, cel->sourceY, mb8, 8);
521 cel->eval_dist[RoQ_ID_SLD] =
522 index_mb(mb8, tempData->codebooks.unpacked_cb4_enlarged,
523 tempData->codebooks.numCB4, &cel->cbEntry, 8);
525 gather_data_for_subcel(cel->subCels + 0, cel->sourceX+0, cel->sourceY+0, enc, tempData);
526 gather_data_for_subcel(cel->subCels + 1, cel->sourceX+4, cel->sourceY+0, enc, tempData);
527 gather_data_for_subcel(cel->subCels + 2, cel->sourceX+0, cel->sourceY+4, enc, tempData);
528 gather_data_for_subcel(cel->subCels + 3, cel->sourceX+4, cel->sourceY+4, enc, tempData);
530 cel->eval_dist[RoQ_ID_CCC] = 0;
532 for (i=0; i<4; i++) {
533 cel->eval_dist[RoQ_ID_CCC] +=
534 cel->subCels[i].eval_dist[cel->subCels[i].best_coding];
535 divide_bit_use += cel->subCels[i].best_bit_use;
539 bitsUsed[3] = 2 + divide_bit_use;
542 if (ROQ_LAMBDA_SCALE*cel->eval_dist[i] + enc->lambda*bitsUsed[i] <
544 cel->best_coding = i;
545 best_dist = ROQ_LAMBDA_SCALE*cel->eval_dist[i] +
546 enc->lambda*bitsUsed[i];
549 tempData->used_option[cel->best_coding]++;
550 tempData->mainChunkSize += bitsUsed[cel->best_coding];
552 if (cel->best_coding == RoQ_ID_SLD)
553 tempData->codebooks.usedCB4[cel->cbEntry]++;
555 if (cel->best_coding == RoQ_ID_CCC)
556 for (i=0; i<4; i++) {
557 if (cel->subCels[i].best_coding == RoQ_ID_SLD)
558 tempData->codebooks.usedCB4[cel->subCels[i].cbEntry]++;
559 else if (cel->subCels[i].best_coding == RoQ_ID_CCC)
561 tempData->codebooks.usedCB2[cel->subCels[i].subCels[j]]++;
565 static void remap_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
567 RoqContext *const roq = &enc->common;
570 /* Make remaps for the final codebook usage */
571 for (i=0; i<(enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4); i++) {
572 if (tempData->codebooks.usedCB4[i]) {
573 tempData->i2f4[i] = idx;
574 tempData->f2i4[idx] = i;
576 tempData->codebooks.usedCB2[roq->cb4x4[i].idx[j]]++;
581 tempData->numCB4 = idx;
584 for (i=0; i<MAX_CBS_2x2; i++) {
585 if (tempData->codebooks.usedCB2[i]) {
586 tempData->i2f2[i] = idx;
587 tempData->f2i2[idx] = i;
591 tempData->numCB2 = idx;
596 * Write codebook chunk
598 static void write_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
600 RoqContext *const roq = &enc->common;
602 uint8_t **outp= &enc->out_buf;
604 if (tempData->numCB2) {
605 bytestream_put_le16(outp, RoQ_QUAD_CODEBOOK);
606 bytestream_put_le32(outp, tempData->numCB2*6 + tempData->numCB4*4);
607 bytestream_put_byte(outp, tempData->numCB4);
608 bytestream_put_byte(outp, tempData->numCB2);
610 for (i=0; i<tempData->numCB2; i++) {
611 bytestream_put_buffer(outp, roq->cb2x2[tempData->f2i2[i]].y, 4);
612 bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].u);
613 bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].v);
616 for (i=0; i<tempData->numCB4; i++)
618 bytestream_put_byte(outp, tempData->i2f2[roq->cb4x4[tempData->f2i4[i]].idx[j]]);
623 static inline uint8_t motion_arg(motion_vect mot)
625 uint8_t ax = 8 - ((uint8_t) mot.d[0]);
626 uint8_t ay = 8 - ((uint8_t) mot.d[1]);
627 return ((ax&15)<<4) | (ay&15);
630 typedef struct CodingSpool {
633 uint8_t argumentSpool[64];
638 /* NOTE: Typecodes must be spooled AFTER arguments!! */
639 static void write_typecode(CodingSpool *s, uint8_t type)
641 s->typeSpool |= (type & 3) << (14 - s->typeSpoolLength);
642 s->typeSpoolLength += 2;
643 if (s->typeSpoolLength == 16) {
644 bytestream_put_le16(s->pout, s->typeSpool);
645 bytestream_put_buffer(s->pout, s->argumentSpool,
646 s->args - s->argumentSpool);
647 s->typeSpoolLength = 0;
649 s->args = s->argumentSpool;
653 static void reconstruct_and_encode_image(RoqEncContext *enc,
654 RoqTempdata *tempData,
655 int w, int h, int numBlocks)
657 RoqContext *const roq = &enc->common;
669 spool.typeSpoolLength=0;
670 spool.args = spool.argumentSpool;
671 spool.pout = &enc->out_buf;
673 if (tempData->used_option[RoQ_ID_CCC]%2)
674 tempData->mainChunkSize+=8; //FIXME
676 /* Write the video chunk header */
677 bytestream_put_le16(&enc->out_buf, RoQ_QUAD_VQ);
678 bytestream_put_le32(&enc->out_buf, tempData->mainChunkSize/8);
679 bytestream_put_byte(&enc->out_buf, 0x0);
680 bytestream_put_byte(&enc->out_buf, 0x0);
682 for (i=0; i<numBlocks; i++) {
683 eval = tempData->cel_evals + i;
687 dist += eval->eval_dist[eval->best_coding];
689 switch (eval->best_coding) {
691 write_typecode(&spool, RoQ_ID_MOT);
695 bytestream_put_byte(&spool.args, motion_arg(eval->motion));
697 write_typecode(&spool, RoQ_ID_FCC);
698 ff_apply_motion_8x8(roq, x, y,
699 eval->motion.d[0], eval->motion.d[1]);
703 bytestream_put_byte(&spool.args, tempData->i2f4[eval->cbEntry]);
704 write_typecode(&spool, RoQ_ID_SLD);
706 qcell = roq->cb4x4 + eval->cbEntry;
707 ff_apply_vector_4x4(roq, x , y , roq->cb2x2 + qcell->idx[0]);
708 ff_apply_vector_4x4(roq, x+4, y , roq->cb2x2 + qcell->idx[1]);
709 ff_apply_vector_4x4(roq, x , y+4, roq->cb2x2 + qcell->idx[2]);
710 ff_apply_vector_4x4(roq, x+4, y+4, roq->cb2x2 + qcell->idx[3]);
714 write_typecode(&spool, RoQ_ID_CCC);
716 for (j=0; j<4; j++) {
720 switch(eval->subCels[j].best_coding) {
725 bytestream_put_byte(&spool.args,
726 motion_arg(eval->subCels[j].motion));
728 ff_apply_motion_4x4(roq, subX, subY,
729 eval->subCels[j].motion.d[0],
730 eval->subCels[j].motion.d[1]);
734 bytestream_put_byte(&spool.args,
735 tempData->i2f4[eval->subCels[j].cbEntry]);
737 qcell = roq->cb4x4 + eval->subCels[j].cbEntry;
739 ff_apply_vector_2x2(roq, subX , subY ,
740 roq->cb2x2 + qcell->idx[0]);
741 ff_apply_vector_2x2(roq, subX+2, subY ,
742 roq->cb2x2 + qcell->idx[1]);
743 ff_apply_vector_2x2(roq, subX , subY+2,
744 roq->cb2x2 + qcell->idx[2]);
745 ff_apply_vector_2x2(roq, subX+2, subY+2,
746 roq->cb2x2 + qcell->idx[3]);
750 for (k=0; k<4; k++) {
751 int cb_idx = eval->subCels[j].subCels[k];
752 bytestream_put_byte(&spool.args,
753 tempData->i2f2[cb_idx]);
755 ff_apply_vector_2x2(roq, subX + 2*(k&1), subY + (k&2),
756 roq->cb2x2 + cb_idx);
760 write_typecode(&spool, eval->subCels[j].best_coding);
766 /* Flush the remainder of the argument/type spool */
767 while (spool.typeSpoolLength)
768 write_typecode(&spool, 0x0);
773 * Create a single YUV cell from a 2x2 section of the image
775 static inline void frame_block_to_cell(uint8_t *block, uint8_t * const *data,
776 int top, int left, const int *stride)
781 for (j=0; j<2; j++) {
782 int x = (top+i)*stride[0] + left + j;
783 *block++ = data[0][x];
784 x = (top+i)*stride[1] + left + j;
794 * Create YUV clusters for the entire image
796 static void create_clusters(const AVFrame *frame, int w, int h, uint8_t *yuvClusters)
801 for (j=0; j<w; j+=4) {
802 for (k=0; k < 2; k++)
803 for (l=0; l < 2; l++)
804 frame_block_to_cell(yuvClusters + (l + 2*k)*6, frame->data,
805 i+2*k, j+2*l, frame->linesize);
810 static int generate_codebook(RoqEncContext *enc, RoqTempdata *tempdata,
811 int *points, int inputCount, roq_cell *results,
812 int size, int cbsize)
814 int i, j, k, ret = 0;
815 int c_size = size*size/4;
817 int *codebook = av_malloc_array(6*c_size, cbsize*sizeof(int));
821 return AVERROR(ENOMEM);
824 closest_cb = av_malloc_array(6*c_size, inputCount*sizeof(int));
826 ret = AVERROR(ENOMEM);
830 closest_cb = tempdata->closest_cb2;
832 ret = avpriv_init_elbg(points, 6 * c_size, inputCount, codebook,
833 cbsize, 1, closest_cb, &enc->randctx);
836 ret = avpriv_do_elbg(points, 6 * c_size, inputCount, codebook,
837 cbsize, 1, closest_cb, &enc->randctx);
842 for (i=0; i<cbsize; i++)
843 for (k=0; k<c_size; k++) {
845 results->y[j] = *buf++;
847 results->u = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
848 results->v = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
858 static int generate_new_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
861 RoqCodebooks *codebooks = &tempData->codebooks;
862 RoqContext *const roq = &enc->common;
863 int max = roq->width * roq->height / 16;
865 roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);
866 uint8_t *yuvClusters=av_malloc_array(max, sizeof(int)*6*4);
867 int *points = av_malloc_array(max, 6*4*sizeof(int));
870 if (!results4 || !yuvClusters || !points) {
871 ret = AVERROR(ENOMEM);
875 /* Subsample YUV data */
876 create_clusters(enc->frame_to_enc, roq->width, roq->height, yuvClusters);
878 /* Cast to integer and apply chroma bias */
879 for (i=0; i<max*24; i++) {
880 bias = ((i%6)<4) ? 1 : CHROMA_BIAS;
881 points[i] = bias*yuvClusters[i];
884 /* Create 4x4 codebooks */
885 if ((ret = generate_codebook(enc, tempData, points, max,
886 results4, 4, (enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4))) < 0)
889 codebooks->numCB4 = (enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4);
891 tempData->closest_cb2 = av_malloc_array(max, 4*sizeof(int));
892 if (!tempData->closest_cb2) {
893 ret = AVERROR(ENOMEM);
897 /* Create 2x2 codebooks */
898 if ((ret = generate_codebook(enc, tempData, points, max * 4,
899 roq->cb2x2, 2, MAX_CBS_2x2)) < 0)
902 codebooks->numCB2 = MAX_CBS_2x2;
904 /* Unpack 2x2 codebook clusters */
905 for (i=0; i<codebooks->numCB2; i++)
906 unpack_roq_cell(roq->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
908 /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */
909 for (i=0; i<codebooks->numCB4; i++) {
910 for (j=0; j<4; j++) {
911 unpack_roq_cell(&results4[4*i + j], mb2);
912 index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
913 &roq->cb4x4[i].idx[j], 2);
915 unpack_roq_qcell(codebooks->unpacked_cb2, roq->cb4x4 + i,
916 codebooks->unpacked_cb4 + i*4*4*3);
917 enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
918 codebooks->unpacked_cb4_enlarged + i*8*8*3);
921 av_free(yuvClusters);
927 static int roq_encode_video(RoqEncContext *enc)
929 RoqTempdata *tempData = enc->tmpData;
930 RoqContext *const roq = &enc->common;
933 memset(tempData, 0, sizeof(*tempData));
935 ret = create_cel_evals(roq, tempData);
939 ret = generate_new_codebooks(enc, tempData);
943 if (enc->framesSinceKeyframe >= 1) {
944 motion_search(enc, 8);
945 motion_search(enc, 4);
949 for (int i = 0; i < roq->width * roq->height / 64; i++)
950 gather_data_for_cel(tempData->cel_evals + i, enc, tempData);
952 /* Quake 3 can't handle chunks bigger than 65535 bytes */
953 if (tempData->mainChunkSize/8 > 65535 && enc->quake3_compat) {
954 if (enc->lambda > 100000) {
955 av_log(roq->avctx, AV_LOG_ERROR, "Cannot encode video in Quake compatible form\n");
956 return AVERROR(EINVAL);
958 av_log(roq->avctx, AV_LOG_ERROR,
959 "Warning, generated a frame too big for Quake (%d > 65535), "
960 "now switching to a bigger qscale value.\n",
961 tempData->mainChunkSize/8);
963 tempData->mainChunkSize = 0;
964 memset(tempData->used_option, 0, sizeof(tempData->used_option));
965 memset(tempData->codebooks.usedCB4, 0,
966 sizeof(tempData->codebooks.usedCB4));
967 memset(tempData->codebooks.usedCB2, 0,
968 sizeof(tempData->codebooks.usedCB2));
973 remap_codebooks(enc, tempData);
975 write_codebooks(enc, tempData);
977 reconstruct_and_encode_image(enc, tempData, roq->width, roq->height,
978 roq->width * roq->height / 64);
980 /* Rotate frame history */
981 FFSWAP(AVFrame *, roq->current_frame, roq->last_frame);
982 FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);
983 FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);
985 av_freep(&tempData->cel_evals);
986 av_freep(&tempData->closest_cb2);
988 enc->framesSinceKeyframe++;
993 static av_cold int roq_encode_end(AVCodecContext *avctx)
995 RoqEncContext *const enc = avctx->priv_data;
997 av_frame_free(&enc->common.current_frame);
998 av_frame_free(&enc->common.last_frame);
1000 av_freep(&enc->tmpData);
1001 av_freep(&enc->this_motion4);
1002 av_freep(&enc->last_motion4);
1003 av_freep(&enc->this_motion8);
1004 av_freep(&enc->last_motion8);
1009 static av_cold int roq_encode_init(AVCodecContext *avctx)
1011 RoqEncContext *const enc = avctx->priv_data;
1012 RoqContext *const roq = &enc->common;
1014 av_lfg_init(&enc->randctx, 1);
1018 enc->framesSinceKeyframe = 0;
1019 if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
1020 av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
1021 return AVERROR(EINVAL);
1024 if (avctx->width > 65535 || avctx->height > 65535) {
1025 av_log(avctx, AV_LOG_ERROR, "Dimensions are max %d\n", enc->quake3_compat ? 32768 : 65535);
1026 return AVERROR(EINVAL);
1029 if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
1030 av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two, this is not supported by quake\n");
1032 roq->width = avctx->width;
1033 roq->height = avctx->height;
1035 enc->framesSinceKeyframe = 0;
1036 enc->first_frame = 1;
1038 roq->last_frame = av_frame_alloc();
1039 roq->current_frame = av_frame_alloc();
1040 if (!roq->last_frame || !roq->current_frame)
1041 return AVERROR(ENOMEM);
1043 enc->tmpData = av_malloc(sizeof(RoqTempdata));
1046 av_mallocz_array(roq->width * roq->height / 16, sizeof(motion_vect));
1049 av_malloc_array (roq->width * roq->height / 16, sizeof(motion_vect));
1052 av_mallocz_array(roq->width * roq->height / 64, sizeof(motion_vect));
1055 av_malloc_array (roq->width * roq->height / 64, sizeof(motion_vect));
1057 if (!enc->tmpData || !enc->this_motion4 || !enc->last_motion4 ||
1058 !enc->this_motion8 || !enc->last_motion8)
1059 return AVERROR(ENOMEM);
1064 static void roq_write_video_info_chunk(RoqEncContext *enc)
1066 /* ROQ info chunk */
1067 bytestream_put_le16(&enc->out_buf, RoQ_INFO);
1070 bytestream_put_le32(&enc->out_buf, 8);
1072 /* Unused argument */
1073 bytestream_put_byte(&enc->out_buf, 0x00);
1074 bytestream_put_byte(&enc->out_buf, 0x00);
1077 bytestream_put_le16(&enc->out_buf, enc->common.width);
1080 bytestream_put_le16(&enc->out_buf, enc->common.height);
1082 /* Unused in Quake 3, mimics the output of the real encoder */
1083 bytestream_put_byte(&enc->out_buf, 0x08);
1084 bytestream_put_byte(&enc->out_buf, 0x00);
1085 bytestream_put_byte(&enc->out_buf, 0x04);
1086 bytestream_put_byte(&enc->out_buf, 0x00);
1089 static int roq_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1090 const AVFrame *frame, int *got_packet)
1092 RoqEncContext *const enc = avctx->priv_data;
1093 RoqContext *const roq = &enc->common;
1098 enc->frame_to_enc = frame;
1101 enc->lambda = frame->quality - 1;
1103 enc->lambda = 2*ROQ_LAMBDA_SCALE;
1105 /* 138 bits max per 8x8 block +
1106 * 256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */
1107 size = ((roq->width * roq->height / 64) * 138 + 7) / 8 + 256 * (6 + 4) + 8;
1108 if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0)
1110 enc->out_buf = pkt->data;
1112 /* Check for I-frame */
1113 if (enc->framesSinceKeyframe == avctx->gop_size)
1114 enc->framesSinceKeyframe = 0;
1116 if (enc->first_frame) {
1117 /* Alloc memory for the reconstruction data (we must know the stride
1119 if ((ret = ff_get_buffer(avctx, roq->current_frame, 0)) < 0 ||
1120 (ret = ff_get_buffer(avctx, roq->last_frame, 0)) < 0)
1123 /* Before the first video frame, write a "video info" chunk */
1124 roq_write_video_info_chunk(enc);
1126 enc->first_frame = 0;
1129 /* Encode the actual frame */
1130 ret = roq_encode_video(enc);
1134 pkt->size = enc->out_buf - pkt->data;
1135 if (enc->framesSinceKeyframe == 1)
1136 pkt->flags |= AV_PKT_FLAG_KEY;
1142 #define OFFSET(x) offsetof(RoqEncContext, x)
1143 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1144 static const AVOption options[] = {
1145 { "quake3_compat", "Whether to respect known limitations in Quake 3 decoder", OFFSET(quake3_compat), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, VE },
1149 static const AVClass roq_class = {
1150 .class_name = "RoQ",
1151 .item_name = av_default_item_name,
1153 .version = LIBAVUTIL_VERSION_INT,
1156 AVCodec ff_roq_encoder = {
1158 .long_name = NULL_IF_CONFIG_SMALL("id RoQ video"),
1159 .type = AVMEDIA_TYPE_VIDEO,
1160 .id = AV_CODEC_ID_ROQ,
1161 .priv_data_size = sizeof(RoqEncContext),
1162 .init = roq_encode_init,
1163 .encode2 = roq_encode_frame,
1164 .close = roq_encode_end,
1165 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUVJ444P,
1167 .priv_class = &roq_class,
1168 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,