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 RoqCodebooks {
84 int usedCB2[MAX_CBS_2x2];
85 int usedCB4[MAX_CBS_4x4];
86 uint8_t unpacked_cb2[MAX_CBS_2x2*2*2*3];
87 uint8_t unpacked_cb4[MAX_CBS_4x4*4*4*3];
88 uint8_t unpacked_cb4_enlarged[MAX_CBS_4x4*8*8*3];
94 typedef struct RoqTempData
96 int f2i4[MAX_CBS_4x4];
97 int i2f4[MAX_CBS_4x4];
98 int f2i2[MAX_CBS_2x2];
99 int i2f2[MAX_CBS_2x2];
106 RoqCodebooks codebooks;
111 typedef struct SubcelEvaluation {
121 typedef struct CelEvaluation {
125 SubcelEvaluation subCels[4];
130 int sourceX, sourceY;
133 typedef struct RoqEncContext {
138 motion_vect *this_motion4;
139 motion_vect *last_motion4;
141 motion_vect *this_motion8;
142 motion_vect *last_motion8;
144 unsigned int framesSinceKeyframe;
146 const AVFrame *frame_to_enc;
148 RoqTempData tmp_data;
149 roq_cell results4[4 * MAX_CBS_4x4];
150 int tmp_codebook_buf[FFMAX(24 * MAX_CBS_4x4, 6 * MAX_CBS_2x2)];
152 CelEvaluation *cel_evals;
154 int *points; // Allocated together with closest_cb
157 int quake3_compat; // Quake 3 compatibility option
160 /* Macroblock support functions */
161 static void unpack_roq_cell(roq_cell *cell, uint8_t u[4*3])
163 memcpy(u , cell->y, 4);
164 memset(u+4, cell->u, 4);
165 memset(u+8, cell->v, 4);
168 static void unpack_roq_qcell(uint8_t cb2[], roq_qcell *qcell, uint8_t u[4*4*3])
171 static const int offsets[4] = {0, 2, 8, 10};
173 for (cp=0; cp<3; cp++)
174 for (i=0; i<4; i++) {
175 u[4*4*cp + offsets[i] ] = cb2[qcell->idx[i]*2*2*3 + 4*cp ];
176 u[4*4*cp + offsets[i]+1] = cb2[qcell->idx[i]*2*2*3 + 4*cp+1];
177 u[4*4*cp + offsets[i]+4] = cb2[qcell->idx[i]*2*2*3 + 4*cp+2];
178 u[4*4*cp + offsets[i]+5] = cb2[qcell->idx[i]*2*2*3 + 4*cp+3];
183 static void enlarge_roq_mb4(uint8_t base[3*16], uint8_t u[3*64])
187 for(cp=0; cp<3; cp++)
190 *u++ = base[(y/2)*4 + (x/2) + 16*cp];
193 static inline int square(int x)
198 static inline int eval_sse(const uint8_t *a, const uint8_t *b, int count)
203 diff += square(*b++ - *a++);
208 // FIXME Could use DSPContext.sse, but it is not so speed critical (used
209 // just for motion estimation).
210 static int block_sse(uint8_t * const *buf1, uint8_t * const *buf2, int x1, int y1,
211 int x2, int y2, const int *stride1, const int *stride2, int size)
216 for (k=0; k<3; k++) {
217 int bias = (k ? CHROMA_BIAS : 4);
218 for (i=0; i<size; i++)
219 sse += bias*eval_sse(buf1[k] + (y1+i)*stride1[k] + x1,
220 buf2[k] + (y2+i)*stride2[k] + x2, size);
226 static int eval_motion_dist(RoqEncContext *enc, int x, int y, motion_vect vect,
229 RoqContext *const roq = &enc->common;
233 if (mx < -7 || mx > 7)
236 if (my < -7 || my > 7)
242 if ((unsigned) mx > roq->width-size || (unsigned) my > roq->height-size)
245 return block_sse(enc->frame_to_enc->data, roq->last_frame->data, x, y,
247 enc->frame_to_enc->linesize, roq->last_frame->linesize,
252 * @return distortion between two macroblocks
254 static inline int squared_diff_macroblock(uint8_t a[], uint8_t b[], int size)
258 for(cp=0;cp<3;cp++) {
259 int bias = (cp ? CHROMA_BIAS : 4);
260 sdiff += bias*eval_sse(a, b, size*size);
269 * Initialize cel evaluators and set their source coordinates
271 static int create_cel_evals(RoqEncContext *enc)
273 RoqContext *const roq = &enc->common;
275 enc->cel_evals = av_malloc_array(roq->width * roq->height / 64, sizeof(CelEvaluation));
277 return AVERROR(ENOMEM);
279 /* Map to the ROQ quadtree order */
280 for (int y = 0, n = 0; y < roq->height; y += 16)
281 for (int x = 0; x < roq->width; x += 16)
282 for(int i = 0; i < 4; i++) {
283 enc->cel_evals[n ].sourceX = x + (i&1)*8;
284 enc->cel_evals[n++].sourceY = y + (i&2)*4;
291 * Get macroblocks from parts of the image
293 static void get_frame_mb(const AVFrame *frame, int x, int y, uint8_t mb[], int dim)
297 for (cp=0; cp<3; cp++) {
298 int stride = frame->linesize[cp];
299 for (i=0; i<dim; i++)
300 for (j=0; j<dim; j++)
301 *mb++ = frame->data[cp][(y+i)*stride + x + j];
306 * Find the codebook with the lowest distortion from an image
308 static int index_mb(uint8_t cluster[], uint8_t cb[], int numCB,
309 int *outIndex, int dim)
311 int i, lDiff = INT_MAX, pick=0;
313 /* Diff against the others */
314 for (i=0; i<numCB; i++) {
315 int diff = squared_diff_macroblock(cluster, cb + i*dim*dim*3, dim);
326 #define EVAL_MOTION(MOTION) \
328 diff = eval_motion_dist(enc, j, i, MOTION, blocksize); \
330 if (diff < lowestdiff) { \
336 static void motion_search(RoqEncContext *enc, int blocksize)
338 static const motion_vect offsets[8] = {
349 RoqContext *const roq = &enc->common;
350 int diff, lowestdiff, oldbest;
352 motion_vect bestpick = {{0,0}};
355 motion_vect *last_motion;
356 motion_vect *this_motion;
357 motion_vect vect, vect2;
358 const int max = (roq->width / blocksize) * roq->height / blocksize;
360 if (blocksize == 4) {
361 last_motion = enc->last_motion4;
362 this_motion = enc->this_motion4;
364 last_motion = enc->last_motion8;
365 this_motion = enc->this_motion8;
368 for (i = 0; i< roq->height; i += blocksize)
369 for (j = 0; j < roq->width; j += blocksize) {
370 lowestdiff = eval_motion_dist(enc, j, i, (motion_vect) {{0,0}},
376 EVAL_MOTION(enc->this_motion8[(i/8) * (roq->width/8) + j/8]);
378 offset = (i/blocksize) * roq->width / blocksize + j / blocksize;
379 if (offset < max && offset >= 0)
380 EVAL_MOTION(last_motion[offset]);
383 if (offset < max && offset >= 0)
384 EVAL_MOTION(last_motion[offset]);
386 offset = (i/blocksize + 1) * roq->width / blocksize + j / blocksize;
387 if (offset < max && offset >= 0)
388 EVAL_MOTION(last_motion[offset]);
390 off[0]= (i/blocksize) * roq->width / blocksize + j/blocksize - 1;
391 off[1]= off[0] - roq->width / blocksize + 1;
397 vect.d[k]= mid_pred(this_motion[off[0]].d[k],
398 this_motion[off[1]].d[k],
399 this_motion[off[2]].d[k]);
403 EVAL_MOTION(this_motion[off[k]]);
405 EVAL_MOTION(this_motion[off[0]]);
410 while (oldbest != lowestdiff) {
411 oldbest = lowestdiff;
412 for (k=0; k<8; k++) {
414 vect2.d[0] += offsets[k].d[0];
415 vect2.d[1] += offsets[k].d[1];
420 offset = (i/blocksize) * roq->width / blocksize + j/blocksize;
421 this_motion[offset] = bestpick;
426 * Get distortion for all options available to a subcel
428 static void gather_data_for_subcel(SubcelEvaluation *subcel, int x,
429 int y, RoqEncContext *enc)
431 RoqContext *const roq = &enc->common;
432 RoqTempData *const tempData = &enc->tmp_data;
438 static const int bitsUsed[4] = {2, 10, 10, 34};
440 if (enc->framesSinceKeyframe >= 1) {
441 subcel->motion = enc->this_motion4[y * roq->width / 16 + x / 4];
443 subcel->eval_dist[RoQ_ID_FCC] =
444 eval_motion_dist(enc, x, y,
445 enc->this_motion4[y * roq->width / 16 + x / 4], 4);
447 subcel->eval_dist[RoQ_ID_FCC] = INT_MAX;
449 if (enc->framesSinceKeyframe >= 2)
450 subcel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
451 roq->current_frame->data, x,
453 enc->frame_to_enc->linesize,
454 roq->current_frame->linesize,
457 subcel->eval_dist[RoQ_ID_MOT] = INT_MAX;
459 cluster_index = y * roq->width / 16 + x / 4;
461 get_frame_mb(enc->frame_to_enc, x, y, mb4, 4);
463 subcel->eval_dist[RoQ_ID_SLD] = index_mb(mb4,
464 tempData->codebooks.unpacked_cb4,
465 tempData->codebooks.numCB4,
466 &subcel->cbEntry, 4);
468 subcel->eval_dist[RoQ_ID_CCC] = 0;
471 subcel->subCels[i] = enc->closest_cb[cluster_index*4+i];
473 get_frame_mb(enc->frame_to_enc, x+2*(i&1),
476 subcel->eval_dist[RoQ_ID_CCC] +=
477 squared_diff_macroblock(tempData->codebooks.unpacked_cb2 + subcel->subCels[i]*2*2*3, mb2, 2);
482 if (ROQ_LAMBDA_SCALE*subcel->eval_dist[i] + enc->lambda*bitsUsed[i] <
484 subcel->best_coding = i;
485 subcel->best_bit_use = bitsUsed[i];
486 best_dist = ROQ_LAMBDA_SCALE*subcel->eval_dist[i] +
487 enc->lambda*bitsUsed[i];
492 * Get distortion for all options available to a cel
494 static void gather_data_for_cel(CelEvaluation *cel, RoqEncContext *enc)
496 RoqContext *const roq = &enc->common;
497 RoqTempData *const tempData = &enc->tmp_data;
499 int index = cel->sourceY * roq->width / 64 + cel->sourceX/8;
500 int i, j, best_dist, divide_bit_use;
502 int bitsUsed[4] = {2, 10, 10, 0};
504 if (enc->framesSinceKeyframe >= 1) {
505 cel->motion = enc->this_motion8[index];
507 cel->eval_dist[RoQ_ID_FCC] =
508 eval_motion_dist(enc, cel->sourceX, cel->sourceY,
509 enc->this_motion8[index], 8);
511 cel->eval_dist[RoQ_ID_FCC] = INT_MAX;
513 if (enc->framesSinceKeyframe >= 2)
514 cel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
515 roq->current_frame->data,
516 cel->sourceX, cel->sourceY,
517 cel->sourceX, cel->sourceY,
518 enc->frame_to_enc->linesize,
519 roq->current_frame->linesize,8);
521 cel->eval_dist[RoQ_ID_MOT] = INT_MAX;
523 get_frame_mb(enc->frame_to_enc, cel->sourceX, cel->sourceY, mb8, 8);
525 cel->eval_dist[RoQ_ID_SLD] =
526 index_mb(mb8, tempData->codebooks.unpacked_cb4_enlarged,
527 tempData->codebooks.numCB4, &cel->cbEntry, 8);
529 gather_data_for_subcel(cel->subCels + 0, cel->sourceX+0, cel->sourceY+0, enc);
530 gather_data_for_subcel(cel->subCels + 1, cel->sourceX+4, cel->sourceY+0, enc);
531 gather_data_for_subcel(cel->subCels + 2, cel->sourceX+0, cel->sourceY+4, enc);
532 gather_data_for_subcel(cel->subCels + 3, cel->sourceX+4, cel->sourceY+4, enc);
534 cel->eval_dist[RoQ_ID_CCC] = 0;
536 for (i=0; i<4; i++) {
537 cel->eval_dist[RoQ_ID_CCC] +=
538 cel->subCels[i].eval_dist[cel->subCels[i].best_coding];
539 divide_bit_use += cel->subCels[i].best_bit_use;
543 bitsUsed[3] = 2 + divide_bit_use;
546 if (ROQ_LAMBDA_SCALE*cel->eval_dist[i] + enc->lambda*bitsUsed[i] <
548 cel->best_coding = i;
549 best_dist = ROQ_LAMBDA_SCALE*cel->eval_dist[i] +
550 enc->lambda*bitsUsed[i];
553 tempData->used_option[cel->best_coding]++;
554 tempData->mainChunkSize += bitsUsed[cel->best_coding];
556 if (cel->best_coding == RoQ_ID_SLD)
557 tempData->codebooks.usedCB4[cel->cbEntry]++;
559 if (cel->best_coding == RoQ_ID_CCC)
560 for (i=0; i<4; i++) {
561 if (cel->subCels[i].best_coding == RoQ_ID_SLD)
562 tempData->codebooks.usedCB4[cel->subCels[i].cbEntry]++;
563 else if (cel->subCels[i].best_coding == RoQ_ID_CCC)
565 tempData->codebooks.usedCB2[cel->subCels[i].subCels[j]]++;
569 static void remap_codebooks(RoqEncContext *enc)
571 RoqContext *const roq = &enc->common;
572 RoqTempData *const tempData = &enc->tmp_data;
575 /* Make remaps for the final codebook usage */
576 for (i=0; i<(enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4); i++) {
577 if (tempData->codebooks.usedCB4[i]) {
578 tempData->i2f4[i] = idx;
579 tempData->f2i4[idx] = i;
581 tempData->codebooks.usedCB2[roq->cb4x4[i].idx[j]]++;
586 tempData->numCB4 = idx;
589 for (i=0; i<MAX_CBS_2x2; i++) {
590 if (tempData->codebooks.usedCB2[i]) {
591 tempData->i2f2[i] = idx;
592 tempData->f2i2[idx] = i;
596 tempData->numCB2 = idx;
601 * Write codebook chunk
603 static void write_codebooks(RoqEncContext *enc)
605 RoqContext *const roq = &enc->common;
606 RoqTempData *const tempData = &enc->tmp_data;
608 uint8_t **outp= &enc->out_buf;
610 if (tempData->numCB2) {
611 bytestream_put_le16(outp, RoQ_QUAD_CODEBOOK);
612 bytestream_put_le32(outp, tempData->numCB2*6 + tempData->numCB4*4);
613 bytestream_put_byte(outp, tempData->numCB4);
614 bytestream_put_byte(outp, tempData->numCB2);
616 for (i=0; i<tempData->numCB2; i++) {
617 bytestream_put_buffer(outp, roq->cb2x2[tempData->f2i2[i]].y, 4);
618 bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].u);
619 bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].v);
622 for (i=0; i<tempData->numCB4; i++)
624 bytestream_put_byte(outp, tempData->i2f2[roq->cb4x4[tempData->f2i4[i]].idx[j]]);
629 static inline uint8_t motion_arg(motion_vect mot)
631 uint8_t ax = 8 - ((uint8_t) mot.d[0]);
632 uint8_t ay = 8 - ((uint8_t) mot.d[1]);
633 return ((ax&15)<<4) | (ay&15);
636 typedef struct CodingSpool {
639 uint8_t argumentSpool[64];
644 /* NOTE: Typecodes must be spooled AFTER arguments!! */
645 static void write_typecode(CodingSpool *s, uint8_t type)
647 s->typeSpool |= (type & 3) << (14 - s->typeSpoolLength);
648 s->typeSpoolLength += 2;
649 if (s->typeSpoolLength == 16) {
650 bytestream_put_le16(s->pout, s->typeSpool);
651 bytestream_put_buffer(s->pout, s->argumentSpool,
652 s->args - s->argumentSpool);
653 s->typeSpoolLength = 0;
655 s->args = s->argumentSpool;
659 static void reconstruct_and_encode_image(RoqEncContext *enc,
660 int w, int h, int numBlocks)
662 RoqContext *const roq = &enc->common;
663 RoqTempData *const tempData = &enc->tmp_data;
675 spool.typeSpoolLength=0;
676 spool.args = spool.argumentSpool;
677 spool.pout = &enc->out_buf;
679 if (tempData->used_option[RoQ_ID_CCC]%2)
680 tempData->mainChunkSize+=8; //FIXME
682 /* Write the video chunk header */
683 bytestream_put_le16(&enc->out_buf, RoQ_QUAD_VQ);
684 bytestream_put_le32(&enc->out_buf, tempData->mainChunkSize/8);
685 bytestream_put_byte(&enc->out_buf, 0x0);
686 bytestream_put_byte(&enc->out_buf, 0x0);
688 for (i=0; i<numBlocks; i++) {
689 eval = enc->cel_evals + i;
693 dist += eval->eval_dist[eval->best_coding];
695 switch (eval->best_coding) {
697 write_typecode(&spool, RoQ_ID_MOT);
701 bytestream_put_byte(&spool.args, motion_arg(eval->motion));
703 write_typecode(&spool, RoQ_ID_FCC);
704 ff_apply_motion_8x8(roq, x, y,
705 eval->motion.d[0], eval->motion.d[1]);
709 bytestream_put_byte(&spool.args, tempData->i2f4[eval->cbEntry]);
710 write_typecode(&spool, RoQ_ID_SLD);
712 qcell = roq->cb4x4 + eval->cbEntry;
713 ff_apply_vector_4x4(roq, x , y , roq->cb2x2 + qcell->idx[0]);
714 ff_apply_vector_4x4(roq, x+4, y , roq->cb2x2 + qcell->idx[1]);
715 ff_apply_vector_4x4(roq, x , y+4, roq->cb2x2 + qcell->idx[2]);
716 ff_apply_vector_4x4(roq, x+4, y+4, roq->cb2x2 + qcell->idx[3]);
720 write_typecode(&spool, RoQ_ID_CCC);
722 for (j=0; j<4; j++) {
726 switch(eval->subCels[j].best_coding) {
731 bytestream_put_byte(&spool.args,
732 motion_arg(eval->subCels[j].motion));
734 ff_apply_motion_4x4(roq, subX, subY,
735 eval->subCels[j].motion.d[0],
736 eval->subCels[j].motion.d[1]);
740 bytestream_put_byte(&spool.args,
741 tempData->i2f4[eval->subCels[j].cbEntry]);
743 qcell = roq->cb4x4 + eval->subCels[j].cbEntry;
745 ff_apply_vector_2x2(roq, subX , subY ,
746 roq->cb2x2 + qcell->idx[0]);
747 ff_apply_vector_2x2(roq, subX+2, subY ,
748 roq->cb2x2 + qcell->idx[1]);
749 ff_apply_vector_2x2(roq, subX , subY+2,
750 roq->cb2x2 + qcell->idx[2]);
751 ff_apply_vector_2x2(roq, subX+2, subY+2,
752 roq->cb2x2 + qcell->idx[3]);
756 for (k=0; k<4; k++) {
757 int cb_idx = eval->subCels[j].subCels[k];
758 bytestream_put_byte(&spool.args,
759 tempData->i2f2[cb_idx]);
761 ff_apply_vector_2x2(roq, subX + 2*(k&1), subY + (k&2),
762 roq->cb2x2 + cb_idx);
766 write_typecode(&spool, eval->subCels[j].best_coding);
772 /* Flush the remainder of the argument/type spool */
773 while (spool.typeSpoolLength)
774 write_typecode(&spool, 0x0);
779 * Create a single YUV cell from a 2x2 section of the image
781 static inline void frame_block_to_cell(int *block, uint8_t * const *data,
782 int top, int left, const int *stride)
787 for (j=0; j<2; j++) {
788 int x = (top+i)*stride[0] + left + j;
789 *block++ = data[0][x];
790 x = (top+i)*stride[1] + left + j;
795 *block++ = (u + 2) / 4 * CHROMA_BIAS;
796 *block++ = (v + 2) / 4 * CHROMA_BIAS;
800 * Create YUV clusters for the entire image
802 static void create_clusters(const AVFrame *frame, int w, int h, int *points)
807 for (j=0; j<w; j+=4) {
808 for (k=0; k < 2; k++)
809 for (l=0; l < 2; l++)
810 frame_block_to_cell(points + (l + 2*k)*6, frame->data,
811 i+2*k, j+2*l, frame->linesize);
816 static int generate_codebook(RoqEncContext *enc,
817 int *points, int inputCount, roq_cell *results,
818 int size, int cbsize)
820 int i, j, k, ret = 0;
821 int c_size = size*size/4;
823 int *codebook = enc->tmp_codebook_buf;
824 int *closest_cb = enc->closest_cb;
826 ret = avpriv_init_elbg(points, 6 * c_size, inputCount, codebook,
827 cbsize, 1, closest_cb, &enc->randctx);
830 ret = avpriv_do_elbg(points, 6 * c_size, inputCount, codebook,
831 cbsize, 1, closest_cb, &enc->randctx);
836 for (i=0; i<cbsize; i++)
837 for (k=0; k<c_size; k++) {
839 results->y[j] = *buf++;
841 results->u = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
842 results->v = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
848 static int generate_new_codebooks(RoqEncContext *enc)
851 RoqCodebooks *codebooks = &enc->tmp_data.codebooks;
852 RoqContext *const roq = &enc->common;
853 int max = roq->width * roq->height / 16;
855 int *points = enc->points;
857 /* Subsample YUV data */
858 create_clusters(enc->frame_to_enc, roq->width, roq->height, points);
860 codebooks->numCB4 = (enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4);
862 /* Create 4x4 codebooks */
863 if ((ret = generate_codebook(enc, points, max, enc->results4,
864 4, codebooks->numCB4)) < 0)
867 /* Create 2x2 codebooks */
868 if ((ret = generate_codebook(enc, points, max * 4,
869 roq->cb2x2, 2, MAX_CBS_2x2)) < 0)
872 codebooks->numCB2 = MAX_CBS_2x2;
874 /* Unpack 2x2 codebook clusters */
875 for (i=0; i<codebooks->numCB2; i++)
876 unpack_roq_cell(roq->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
878 /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */
879 for (i=0; i<codebooks->numCB4; i++) {
880 for (j=0; j<4; j++) {
881 unpack_roq_cell(&enc->results4[4*i + j], mb2);
882 index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
883 &roq->cb4x4[i].idx[j], 2);
885 unpack_roq_qcell(codebooks->unpacked_cb2, roq->cb4x4 + i,
886 codebooks->unpacked_cb4 + i*4*4*3);
887 enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
888 codebooks->unpacked_cb4_enlarged + i*8*8*3);
894 static int roq_encode_video(RoqEncContext *enc)
896 RoqTempData *const tempData = &enc->tmp_data;
897 RoqContext *const roq = &enc->common;
900 memset(tempData, 0, sizeof(*tempData));
902 ret = generate_new_codebooks(enc);
906 if (enc->framesSinceKeyframe >= 1) {
907 motion_search(enc, 8);
908 motion_search(enc, 4);
912 for (int i = 0; i < roq->width * roq->height / 64; i++)
913 gather_data_for_cel(enc->cel_evals + i, enc);
915 /* Quake 3 can't handle chunks bigger than 65535 bytes */
916 if (tempData->mainChunkSize/8 > 65535 && enc->quake3_compat) {
917 if (enc->lambda > 100000) {
918 av_log(roq->avctx, AV_LOG_ERROR, "Cannot encode video in Quake compatible form\n");
919 return AVERROR(EINVAL);
921 av_log(roq->avctx, AV_LOG_ERROR,
922 "Warning, generated a frame too big for Quake (%d > 65535), "
923 "now switching to a bigger qscale value.\n",
924 tempData->mainChunkSize/8);
926 tempData->mainChunkSize = 0;
927 memset(tempData->used_option, 0, sizeof(tempData->used_option));
928 memset(tempData->codebooks.usedCB4, 0,
929 sizeof(tempData->codebooks.usedCB4));
930 memset(tempData->codebooks.usedCB2, 0,
931 sizeof(tempData->codebooks.usedCB2));
936 remap_codebooks(enc);
938 write_codebooks(enc);
940 reconstruct_and_encode_image(enc, roq->width, roq->height,
941 roq->width * roq->height / 64);
943 /* Rotate frame history */
944 FFSWAP(AVFrame *, roq->current_frame, roq->last_frame);
945 FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);
946 FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);
948 enc->framesSinceKeyframe++;
953 static av_cold int roq_encode_end(AVCodecContext *avctx)
955 RoqEncContext *const enc = avctx->priv_data;
957 av_frame_free(&enc->common.current_frame);
958 av_frame_free(&enc->common.last_frame);
960 av_freep(&enc->cel_evals);
961 av_freep(&enc->closest_cb);
962 av_freep(&enc->this_motion4);
963 av_freep(&enc->last_motion4);
964 av_freep(&enc->this_motion8);
965 av_freep(&enc->last_motion8);
970 static av_cold int roq_encode_init(AVCodecContext *avctx)
972 RoqEncContext *const enc = avctx->priv_data;
973 RoqContext *const roq = &enc->common;
975 av_lfg_init(&enc->randctx, 1);
979 enc->framesSinceKeyframe = 0;
980 if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
981 av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
982 return AVERROR(EINVAL);
985 if (avctx->width > 65535 || avctx->height > 65535) {
986 av_log(avctx, AV_LOG_ERROR, "Dimensions are max %d\n", enc->quake3_compat ? 32768 : 65535);
987 return AVERROR(EINVAL);
990 if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
991 av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two, this is not supported by quake\n");
993 roq->width = avctx->width;
994 roq->height = avctx->height;
996 enc->framesSinceKeyframe = 0;
997 enc->first_frame = 1;
999 roq->last_frame = av_frame_alloc();
1000 roq->current_frame = av_frame_alloc();
1001 if (!roq->last_frame || !roq->current_frame)
1002 return AVERROR(ENOMEM);
1005 av_mallocz_array(roq->width * roq->height / 16, sizeof(motion_vect));
1008 av_malloc_array (roq->width * roq->height / 16, sizeof(motion_vect));
1011 av_mallocz_array(roq->width * roq->height / 64, sizeof(motion_vect));
1014 av_malloc_array (roq->width * roq->height / 64, sizeof(motion_vect));
1016 /* 4x4 codebook needs 6 * 4 * 4 / 4 * width * height / 16 * sizeof(int);
1017 * and so does the points buffer. */
1019 av_malloc_array(roq->width * roq->height, 3 * sizeof(int));
1021 if (!enc->this_motion4 || !enc->last_motion4 ||
1022 !enc->this_motion8 || !enc->last_motion8 || !enc->closest_cb)
1023 return AVERROR(ENOMEM);
1025 enc->points = enc->closest_cb + roq->width * roq->height * 3 / 2;
1027 return create_cel_evals(enc);
1030 static void roq_write_video_info_chunk(RoqEncContext *enc)
1032 /* ROQ info chunk */
1033 bytestream_put_le16(&enc->out_buf, RoQ_INFO);
1036 bytestream_put_le32(&enc->out_buf, 8);
1038 /* Unused argument */
1039 bytestream_put_byte(&enc->out_buf, 0x00);
1040 bytestream_put_byte(&enc->out_buf, 0x00);
1043 bytestream_put_le16(&enc->out_buf, enc->common.width);
1046 bytestream_put_le16(&enc->out_buf, enc->common.height);
1048 /* Unused in Quake 3, mimics the output of the real encoder */
1049 bytestream_put_byte(&enc->out_buf, 0x08);
1050 bytestream_put_byte(&enc->out_buf, 0x00);
1051 bytestream_put_byte(&enc->out_buf, 0x04);
1052 bytestream_put_byte(&enc->out_buf, 0x00);
1055 static int roq_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1056 const AVFrame *frame, int *got_packet)
1058 RoqEncContext *const enc = avctx->priv_data;
1059 RoqContext *const roq = &enc->common;
1064 enc->frame_to_enc = frame;
1067 enc->lambda = frame->quality - 1;
1069 enc->lambda = 2*ROQ_LAMBDA_SCALE;
1071 /* 138 bits max per 8x8 block +
1072 * 256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */
1073 size = ((roq->width * roq->height / 64) * 138 + 7) / 8 + 256 * (6 + 4) + 8;
1074 if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0)
1076 enc->out_buf = pkt->data;
1078 /* Check for I-frame */
1079 if (enc->framesSinceKeyframe == avctx->gop_size)
1080 enc->framesSinceKeyframe = 0;
1082 if (enc->first_frame) {
1083 /* Alloc memory for the reconstruction data (we must know the stride
1085 if ((ret = ff_get_buffer(avctx, roq->current_frame, 0)) < 0 ||
1086 (ret = ff_get_buffer(avctx, roq->last_frame, 0)) < 0)
1089 /* Before the first video frame, write a "video info" chunk */
1090 roq_write_video_info_chunk(enc);
1092 enc->first_frame = 0;
1095 /* Encode the actual frame */
1096 ret = roq_encode_video(enc);
1100 pkt->size = enc->out_buf - pkt->data;
1101 if (enc->framesSinceKeyframe == 1)
1102 pkt->flags |= AV_PKT_FLAG_KEY;
1108 #define OFFSET(x) offsetof(RoqEncContext, x)
1109 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1110 static const AVOption options[] = {
1111 { "quake3_compat", "Whether to respect known limitations in Quake 3 decoder", OFFSET(quake3_compat), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, VE },
1115 static const AVClass roq_class = {
1116 .class_name = "RoQ",
1117 .item_name = av_default_item_name,
1119 .version = LIBAVUTIL_VERSION_INT,
1122 AVCodec ff_roq_encoder = {
1124 .long_name = NULL_IF_CONFIG_SMALL("id RoQ video"),
1125 .type = AVMEDIA_TYPE_VIDEO,
1126 .id = AV_CODEC_ID_ROQ,
1127 .priv_data_size = sizeof(RoqEncContext),
1128 .init = roq_encode_init,
1129 .encode2 = roq_encode_frame,
1130 .close = roq_encode_end,
1131 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUVJ444P,
1133 .priv_class = &roq_class,
1134 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,