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 SubcelEvaluation {
91 typedef struct CelEvaluation {
95 SubcelEvaluation subCels[4];
100 int sourceX, sourceY;
103 typedef struct RoqEncContext {
108 motion_vect *this_motion4;
109 motion_vect *last_motion4;
111 motion_vect *this_motion8;
112 motion_vect *last_motion8;
114 unsigned int framesSinceKeyframe;
116 const AVFrame *frame_to_enc;
118 struct RoqTempData *tmpData;
120 CelEvaluation *cel_evals;
122 int *points; // Allocated together with closest_cb
125 int quake3_compat; // Quake 3 compatibility option
128 /* Macroblock support functions */
129 static void unpack_roq_cell(roq_cell *cell, uint8_t u[4*3])
131 memcpy(u , cell->y, 4);
132 memset(u+4, cell->u, 4);
133 memset(u+8, cell->v, 4);
136 static void unpack_roq_qcell(uint8_t cb2[], roq_qcell *qcell, uint8_t u[4*4*3])
139 static const int offsets[4] = {0, 2, 8, 10};
141 for (cp=0; cp<3; cp++)
142 for (i=0; i<4; i++) {
143 u[4*4*cp + offsets[i] ] = cb2[qcell->idx[i]*2*2*3 + 4*cp ];
144 u[4*4*cp + offsets[i]+1] = cb2[qcell->idx[i]*2*2*3 + 4*cp+1];
145 u[4*4*cp + offsets[i]+4] = cb2[qcell->idx[i]*2*2*3 + 4*cp+2];
146 u[4*4*cp + offsets[i]+5] = cb2[qcell->idx[i]*2*2*3 + 4*cp+3];
151 static void enlarge_roq_mb4(uint8_t base[3*16], uint8_t u[3*64])
155 for(cp=0; cp<3; cp++)
158 *u++ = base[(y/2)*4 + (x/2) + 16*cp];
161 static inline int square(int x)
166 static inline int eval_sse(const uint8_t *a, const uint8_t *b, int count)
171 diff += square(*b++ - *a++);
176 // FIXME Could use DSPContext.sse, but it is not so speed critical (used
177 // just for motion estimation).
178 static int block_sse(uint8_t * const *buf1, uint8_t * const *buf2, int x1, int y1,
179 int x2, int y2, const int *stride1, const int *stride2, int size)
184 for (k=0; k<3; k++) {
185 int bias = (k ? CHROMA_BIAS : 4);
186 for (i=0; i<size; i++)
187 sse += bias*eval_sse(buf1[k] + (y1+i)*stride1[k] + x1,
188 buf2[k] + (y2+i)*stride2[k] + x2, size);
194 static int eval_motion_dist(RoqEncContext *enc, int x, int y, motion_vect vect,
197 RoqContext *const roq = &enc->common;
201 if (mx < -7 || mx > 7)
204 if (my < -7 || my > 7)
210 if ((unsigned) mx > roq->width-size || (unsigned) my > roq->height-size)
213 return block_sse(enc->frame_to_enc->data, roq->last_frame->data, x, y,
215 enc->frame_to_enc->linesize, roq->last_frame->linesize,
220 * @return distortion between two macroblocks
222 static inline int squared_diff_macroblock(uint8_t a[], uint8_t b[], int size)
226 for(cp=0;cp<3;cp++) {
227 int bias = (cp ? CHROMA_BIAS : 4);
228 sdiff += bias*eval_sse(a, b, size*size);
236 typedef struct RoqCodebooks {
239 int usedCB2[MAX_CBS_2x2];
240 int usedCB4[MAX_CBS_4x4];
241 uint8_t unpacked_cb2[MAX_CBS_2x2*2*2*3];
242 uint8_t unpacked_cb4[MAX_CBS_4x4*4*4*3];
243 uint8_t unpacked_cb4_enlarged[MAX_CBS_4x4*8*8*3];
249 typedef struct RoqTempData
251 int f2i4[MAX_CBS_4x4];
252 int i2f4[MAX_CBS_4x4];
253 int f2i2[MAX_CBS_2x2];
254 int i2f2[MAX_CBS_2x2];
261 RoqCodebooks codebooks;
267 * Initialize cel evaluators and set their source coordinates
269 static int create_cel_evals(RoqEncContext *enc)
271 RoqContext *const roq = &enc->common;
273 enc->cel_evals = av_malloc_array(roq->width * roq->height / 64, sizeof(CelEvaluation));
275 return AVERROR(ENOMEM);
277 /* Map to the ROQ quadtree order */
278 for (int y = 0, n = 0; y < roq->height; y += 16)
279 for (int x = 0; x < roq->width; x += 16)
280 for(int i = 0; i < 4; i++) {
281 enc->cel_evals[n ].sourceX = x + (i&1)*8;
282 enc->cel_evals[n++].sourceY = y + (i&2)*4;
289 * Get macroblocks from parts of the image
291 static void get_frame_mb(const AVFrame *frame, int x, int y, uint8_t mb[], int dim)
295 for (cp=0; cp<3; cp++) {
296 int stride = frame->linesize[cp];
297 for (i=0; i<dim; i++)
298 for (j=0; j<dim; j++)
299 *mb++ = frame->data[cp][(y+i)*stride + x + j];
304 * Find the codebook with the lowest distortion from an image
306 static int index_mb(uint8_t cluster[], uint8_t cb[], int numCB,
307 int *outIndex, int dim)
309 int i, lDiff = INT_MAX, pick=0;
311 /* Diff against the others */
312 for (i=0; i<numCB; i++) {
313 int diff = squared_diff_macroblock(cluster, cb + i*dim*dim*3, dim);
324 #define EVAL_MOTION(MOTION) \
326 diff = eval_motion_dist(enc, j, i, MOTION, blocksize); \
328 if (diff < lowestdiff) { \
334 static void motion_search(RoqEncContext *enc, int blocksize)
336 static const motion_vect offsets[8] = {
347 RoqContext *const roq = &enc->common;
348 int diff, lowestdiff, oldbest;
350 motion_vect bestpick = {{0,0}};
353 motion_vect *last_motion;
354 motion_vect *this_motion;
355 motion_vect vect, vect2;
356 const int max = (roq->width / blocksize) * roq->height / blocksize;
358 if (blocksize == 4) {
359 last_motion = enc->last_motion4;
360 this_motion = enc->this_motion4;
362 last_motion = enc->last_motion8;
363 this_motion = enc->this_motion8;
366 for (i = 0; i< roq->height; i += blocksize)
367 for (j = 0; j < roq->width; j += blocksize) {
368 lowestdiff = eval_motion_dist(enc, j, i, (motion_vect) {{0,0}},
374 EVAL_MOTION(enc->this_motion8[(i/8) * (roq->width/8) + j/8]);
376 offset = (i/blocksize) * roq->width / blocksize + j / blocksize;
377 if (offset < max && offset >= 0)
378 EVAL_MOTION(last_motion[offset]);
381 if (offset < max && offset >= 0)
382 EVAL_MOTION(last_motion[offset]);
384 offset = (i/blocksize + 1) * roq->width / blocksize + j / blocksize;
385 if (offset < max && offset >= 0)
386 EVAL_MOTION(last_motion[offset]);
388 off[0]= (i/blocksize) * roq->width / blocksize + j/blocksize - 1;
389 off[1]= off[0] - roq->width / blocksize + 1;
395 vect.d[k]= mid_pred(this_motion[off[0]].d[k],
396 this_motion[off[1]].d[k],
397 this_motion[off[2]].d[k]);
401 EVAL_MOTION(this_motion[off[k]]);
403 EVAL_MOTION(this_motion[off[0]]);
408 while (oldbest != lowestdiff) {
409 oldbest = lowestdiff;
410 for (k=0; k<8; k++) {
412 vect2.d[0] += offsets[k].d[0];
413 vect2.d[1] += offsets[k].d[1];
418 offset = (i/blocksize) * roq->width / blocksize + j/blocksize;
419 this_motion[offset] = bestpick;
424 * Get distortion for all options available to a subcel
426 static void gather_data_for_subcel(SubcelEvaluation *subcel, int x,
427 int y, RoqEncContext *enc, RoqTempdata *tempData)
429 RoqContext *const roq = &enc->common;
435 static const int bitsUsed[4] = {2, 10, 10, 34};
437 if (enc->framesSinceKeyframe >= 1) {
438 subcel->motion = enc->this_motion4[y * roq->width / 16 + x / 4];
440 subcel->eval_dist[RoQ_ID_FCC] =
441 eval_motion_dist(enc, x, y,
442 enc->this_motion4[y * roq->width / 16 + x / 4], 4);
444 subcel->eval_dist[RoQ_ID_FCC] = INT_MAX;
446 if (enc->framesSinceKeyframe >= 2)
447 subcel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
448 roq->current_frame->data, x,
450 enc->frame_to_enc->linesize,
451 roq->current_frame->linesize,
454 subcel->eval_dist[RoQ_ID_MOT] = INT_MAX;
456 cluster_index = y * roq->width / 16 + x / 4;
458 get_frame_mb(enc->frame_to_enc, x, y, mb4, 4);
460 subcel->eval_dist[RoQ_ID_SLD] = index_mb(mb4,
461 tempData->codebooks.unpacked_cb4,
462 tempData->codebooks.numCB4,
463 &subcel->cbEntry, 4);
465 subcel->eval_dist[RoQ_ID_CCC] = 0;
468 subcel->subCels[i] = enc->closest_cb[cluster_index*4+i];
470 get_frame_mb(enc->frame_to_enc, x+2*(i&1),
473 subcel->eval_dist[RoQ_ID_CCC] +=
474 squared_diff_macroblock(tempData->codebooks.unpacked_cb2 + subcel->subCels[i]*2*2*3, mb2, 2);
479 if (ROQ_LAMBDA_SCALE*subcel->eval_dist[i] + enc->lambda*bitsUsed[i] <
481 subcel->best_coding = i;
482 subcel->best_bit_use = bitsUsed[i];
483 best_dist = ROQ_LAMBDA_SCALE*subcel->eval_dist[i] +
484 enc->lambda*bitsUsed[i];
489 * Get distortion for all options available to a cel
491 static void gather_data_for_cel(CelEvaluation *cel, RoqEncContext *enc,
492 RoqTempdata *tempData)
494 RoqContext *const roq = &enc->common;
496 int index = cel->sourceY * roq->width / 64 + cel->sourceX/8;
497 int i, j, best_dist, divide_bit_use;
499 int bitsUsed[4] = {2, 10, 10, 0};
501 if (enc->framesSinceKeyframe >= 1) {
502 cel->motion = enc->this_motion8[index];
504 cel->eval_dist[RoQ_ID_FCC] =
505 eval_motion_dist(enc, cel->sourceX, cel->sourceY,
506 enc->this_motion8[index], 8);
508 cel->eval_dist[RoQ_ID_FCC] = INT_MAX;
510 if (enc->framesSinceKeyframe >= 2)
511 cel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
512 roq->current_frame->data,
513 cel->sourceX, cel->sourceY,
514 cel->sourceX, cel->sourceY,
515 enc->frame_to_enc->linesize,
516 roq->current_frame->linesize,8);
518 cel->eval_dist[RoQ_ID_MOT] = INT_MAX;
520 get_frame_mb(enc->frame_to_enc, cel->sourceX, cel->sourceY, mb8, 8);
522 cel->eval_dist[RoQ_ID_SLD] =
523 index_mb(mb8, tempData->codebooks.unpacked_cb4_enlarged,
524 tempData->codebooks.numCB4, &cel->cbEntry, 8);
526 gather_data_for_subcel(cel->subCels + 0, cel->sourceX+0, cel->sourceY+0, enc, tempData);
527 gather_data_for_subcel(cel->subCels + 1, cel->sourceX+4, cel->sourceY+0, enc, tempData);
528 gather_data_for_subcel(cel->subCels + 2, cel->sourceX+0, cel->sourceY+4, enc, tempData);
529 gather_data_for_subcel(cel->subCels + 3, cel->sourceX+4, cel->sourceY+4, enc, tempData);
531 cel->eval_dist[RoQ_ID_CCC] = 0;
533 for (i=0; i<4; i++) {
534 cel->eval_dist[RoQ_ID_CCC] +=
535 cel->subCels[i].eval_dist[cel->subCels[i].best_coding];
536 divide_bit_use += cel->subCels[i].best_bit_use;
540 bitsUsed[3] = 2 + divide_bit_use;
543 if (ROQ_LAMBDA_SCALE*cel->eval_dist[i] + enc->lambda*bitsUsed[i] <
545 cel->best_coding = i;
546 best_dist = ROQ_LAMBDA_SCALE*cel->eval_dist[i] +
547 enc->lambda*bitsUsed[i];
550 tempData->used_option[cel->best_coding]++;
551 tempData->mainChunkSize += bitsUsed[cel->best_coding];
553 if (cel->best_coding == RoQ_ID_SLD)
554 tempData->codebooks.usedCB4[cel->cbEntry]++;
556 if (cel->best_coding == RoQ_ID_CCC)
557 for (i=0; i<4; i++) {
558 if (cel->subCels[i].best_coding == RoQ_ID_SLD)
559 tempData->codebooks.usedCB4[cel->subCels[i].cbEntry]++;
560 else if (cel->subCels[i].best_coding == RoQ_ID_CCC)
562 tempData->codebooks.usedCB2[cel->subCels[i].subCels[j]]++;
566 static void remap_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
568 RoqContext *const roq = &enc->common;
571 /* Make remaps for the final codebook usage */
572 for (i=0; i<(enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4); i++) {
573 if (tempData->codebooks.usedCB4[i]) {
574 tempData->i2f4[i] = idx;
575 tempData->f2i4[idx] = i;
577 tempData->codebooks.usedCB2[roq->cb4x4[i].idx[j]]++;
582 tempData->numCB4 = idx;
585 for (i=0; i<MAX_CBS_2x2; i++) {
586 if (tempData->codebooks.usedCB2[i]) {
587 tempData->i2f2[i] = idx;
588 tempData->f2i2[idx] = i;
592 tempData->numCB2 = idx;
597 * Write codebook chunk
599 static void write_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
601 RoqContext *const roq = &enc->common;
603 uint8_t **outp= &enc->out_buf;
605 if (tempData->numCB2) {
606 bytestream_put_le16(outp, RoQ_QUAD_CODEBOOK);
607 bytestream_put_le32(outp, tempData->numCB2*6 + tempData->numCB4*4);
608 bytestream_put_byte(outp, tempData->numCB4);
609 bytestream_put_byte(outp, tempData->numCB2);
611 for (i=0; i<tempData->numCB2; i++) {
612 bytestream_put_buffer(outp, roq->cb2x2[tempData->f2i2[i]].y, 4);
613 bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].u);
614 bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].v);
617 for (i=0; i<tempData->numCB4; i++)
619 bytestream_put_byte(outp, tempData->i2f2[roq->cb4x4[tempData->f2i4[i]].idx[j]]);
624 static inline uint8_t motion_arg(motion_vect mot)
626 uint8_t ax = 8 - ((uint8_t) mot.d[0]);
627 uint8_t ay = 8 - ((uint8_t) mot.d[1]);
628 return ((ax&15)<<4) | (ay&15);
631 typedef struct CodingSpool {
634 uint8_t argumentSpool[64];
639 /* NOTE: Typecodes must be spooled AFTER arguments!! */
640 static void write_typecode(CodingSpool *s, uint8_t type)
642 s->typeSpool |= (type & 3) << (14 - s->typeSpoolLength);
643 s->typeSpoolLength += 2;
644 if (s->typeSpoolLength == 16) {
645 bytestream_put_le16(s->pout, s->typeSpool);
646 bytestream_put_buffer(s->pout, s->argumentSpool,
647 s->args - s->argumentSpool);
648 s->typeSpoolLength = 0;
650 s->args = s->argumentSpool;
654 static void reconstruct_and_encode_image(RoqEncContext *enc,
655 RoqTempdata *tempData,
656 int w, int h, int numBlocks)
658 RoqContext *const roq = &enc->common;
670 spool.typeSpoolLength=0;
671 spool.args = spool.argumentSpool;
672 spool.pout = &enc->out_buf;
674 if (tempData->used_option[RoQ_ID_CCC]%2)
675 tempData->mainChunkSize+=8; //FIXME
677 /* Write the video chunk header */
678 bytestream_put_le16(&enc->out_buf, RoQ_QUAD_VQ);
679 bytestream_put_le32(&enc->out_buf, tempData->mainChunkSize/8);
680 bytestream_put_byte(&enc->out_buf, 0x0);
681 bytestream_put_byte(&enc->out_buf, 0x0);
683 for (i=0; i<numBlocks; i++) {
684 eval = enc->cel_evals + i;
688 dist += eval->eval_dist[eval->best_coding];
690 switch (eval->best_coding) {
692 write_typecode(&spool, RoQ_ID_MOT);
696 bytestream_put_byte(&spool.args, motion_arg(eval->motion));
698 write_typecode(&spool, RoQ_ID_FCC);
699 ff_apply_motion_8x8(roq, x, y,
700 eval->motion.d[0], eval->motion.d[1]);
704 bytestream_put_byte(&spool.args, tempData->i2f4[eval->cbEntry]);
705 write_typecode(&spool, RoQ_ID_SLD);
707 qcell = roq->cb4x4 + eval->cbEntry;
708 ff_apply_vector_4x4(roq, x , y , roq->cb2x2 + qcell->idx[0]);
709 ff_apply_vector_4x4(roq, x+4, y , roq->cb2x2 + qcell->idx[1]);
710 ff_apply_vector_4x4(roq, x , y+4, roq->cb2x2 + qcell->idx[2]);
711 ff_apply_vector_4x4(roq, x+4, y+4, roq->cb2x2 + qcell->idx[3]);
715 write_typecode(&spool, RoQ_ID_CCC);
717 for (j=0; j<4; j++) {
721 switch(eval->subCels[j].best_coding) {
726 bytestream_put_byte(&spool.args,
727 motion_arg(eval->subCels[j].motion));
729 ff_apply_motion_4x4(roq, subX, subY,
730 eval->subCels[j].motion.d[0],
731 eval->subCels[j].motion.d[1]);
735 bytestream_put_byte(&spool.args,
736 tempData->i2f4[eval->subCels[j].cbEntry]);
738 qcell = roq->cb4x4 + eval->subCels[j].cbEntry;
740 ff_apply_vector_2x2(roq, subX , subY ,
741 roq->cb2x2 + qcell->idx[0]);
742 ff_apply_vector_2x2(roq, subX+2, subY ,
743 roq->cb2x2 + qcell->idx[1]);
744 ff_apply_vector_2x2(roq, subX , subY+2,
745 roq->cb2x2 + qcell->idx[2]);
746 ff_apply_vector_2x2(roq, subX+2, subY+2,
747 roq->cb2x2 + qcell->idx[3]);
751 for (k=0; k<4; k++) {
752 int cb_idx = eval->subCels[j].subCels[k];
753 bytestream_put_byte(&spool.args,
754 tempData->i2f2[cb_idx]);
756 ff_apply_vector_2x2(roq, subX + 2*(k&1), subY + (k&2),
757 roq->cb2x2 + cb_idx);
761 write_typecode(&spool, eval->subCels[j].best_coding);
767 /* Flush the remainder of the argument/type spool */
768 while (spool.typeSpoolLength)
769 write_typecode(&spool, 0x0);
774 * Create a single YUV cell from a 2x2 section of the image
776 static inline void frame_block_to_cell(uint8_t *block, uint8_t * const *data,
777 int top, int left, const int *stride)
782 for (j=0; j<2; j++) {
783 int x = (top+i)*stride[0] + left + j;
784 *block++ = data[0][x];
785 x = (top+i)*stride[1] + left + j;
795 * Create YUV clusters for the entire image
797 static void create_clusters(const AVFrame *frame, int w, int h, uint8_t *yuvClusters)
802 for (j=0; j<w; j+=4) {
803 for (k=0; k < 2; k++)
804 for (l=0; l < 2; l++)
805 frame_block_to_cell(yuvClusters + (l + 2*k)*6, frame->data,
806 i+2*k, j+2*l, frame->linesize);
811 static int generate_codebook(RoqEncContext *enc,
812 int *points, int inputCount, roq_cell *results,
813 int size, int cbsize)
815 int i, j, k, ret = 0;
816 int c_size = size*size/4;
818 int *codebook = av_malloc_array(6*c_size, cbsize*sizeof(int));
819 int *closest_cb = enc->closest_cb;
822 return AVERROR(ENOMEM);
824 ret = avpriv_init_elbg(points, 6 * c_size, inputCount, codebook,
825 cbsize, 1, closest_cb, &enc->randctx);
828 ret = avpriv_do_elbg(points, 6 * c_size, inputCount, codebook,
829 cbsize, 1, closest_cb, &enc->randctx);
834 for (i=0; i<cbsize; i++)
835 for (k=0; k<c_size; k++) {
837 results->y[j] = *buf++;
839 results->u = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
840 results->v = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
848 static int generate_new_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
851 RoqCodebooks *codebooks = &tempData->codebooks;
852 RoqContext *const roq = &enc->common;
853 int max = roq->width * roq->height / 16;
855 roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);
856 uint8_t *yuvClusters=av_malloc_array(max, sizeof(int)*6*4);
857 int *points = enc->points;
860 if (!results4 || !yuvClusters) {
861 ret = AVERROR(ENOMEM);
865 /* Subsample YUV data */
866 create_clusters(enc->frame_to_enc, roq->width, roq->height, yuvClusters);
868 /* Cast to integer and apply chroma bias */
869 for (i=0; i<max*24; i++) {
870 bias = ((i%6)<4) ? 1 : CHROMA_BIAS;
871 points[i] = bias*yuvClusters[i];
874 /* Create 4x4 codebooks */
875 if ((ret = generate_codebook(enc, points, max,
876 results4, 4, (enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4))) < 0)
879 codebooks->numCB4 = (enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4);
881 /* Create 2x2 codebooks */
882 if ((ret = generate_codebook(enc, points, max * 4,
883 roq->cb2x2, 2, MAX_CBS_2x2)) < 0)
886 codebooks->numCB2 = MAX_CBS_2x2;
888 /* Unpack 2x2 codebook clusters */
889 for (i=0; i<codebooks->numCB2; i++)
890 unpack_roq_cell(roq->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
892 /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */
893 for (i=0; i<codebooks->numCB4; i++) {
894 for (j=0; j<4; j++) {
895 unpack_roq_cell(&results4[4*i + j], mb2);
896 index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
897 &roq->cb4x4[i].idx[j], 2);
899 unpack_roq_qcell(codebooks->unpacked_cb2, roq->cb4x4 + i,
900 codebooks->unpacked_cb4 + i*4*4*3);
901 enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
902 codebooks->unpacked_cb4_enlarged + i*8*8*3);
905 av_free(yuvClusters);
910 static int roq_encode_video(RoqEncContext *enc)
912 RoqTempdata *tempData = enc->tmpData;
913 RoqContext *const roq = &enc->common;
916 memset(tempData, 0, sizeof(*tempData));
918 ret = generate_new_codebooks(enc, tempData);
922 if (enc->framesSinceKeyframe >= 1) {
923 motion_search(enc, 8);
924 motion_search(enc, 4);
928 for (int i = 0; i < roq->width * roq->height / 64; i++)
929 gather_data_for_cel(enc->cel_evals + i, enc, tempData);
931 /* Quake 3 can't handle chunks bigger than 65535 bytes */
932 if (tempData->mainChunkSize/8 > 65535 && enc->quake3_compat) {
933 if (enc->lambda > 100000) {
934 av_log(roq->avctx, AV_LOG_ERROR, "Cannot encode video in Quake compatible form\n");
935 return AVERROR(EINVAL);
937 av_log(roq->avctx, AV_LOG_ERROR,
938 "Warning, generated a frame too big for Quake (%d > 65535), "
939 "now switching to a bigger qscale value.\n",
940 tempData->mainChunkSize/8);
942 tempData->mainChunkSize = 0;
943 memset(tempData->used_option, 0, sizeof(tempData->used_option));
944 memset(tempData->codebooks.usedCB4, 0,
945 sizeof(tempData->codebooks.usedCB4));
946 memset(tempData->codebooks.usedCB2, 0,
947 sizeof(tempData->codebooks.usedCB2));
952 remap_codebooks(enc, tempData);
954 write_codebooks(enc, tempData);
956 reconstruct_and_encode_image(enc, tempData, roq->width, roq->height,
957 roq->width * roq->height / 64);
959 /* Rotate frame history */
960 FFSWAP(AVFrame *, roq->current_frame, roq->last_frame);
961 FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);
962 FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);
964 enc->framesSinceKeyframe++;
969 static av_cold int roq_encode_end(AVCodecContext *avctx)
971 RoqEncContext *const enc = avctx->priv_data;
973 av_frame_free(&enc->common.current_frame);
974 av_frame_free(&enc->common.last_frame);
976 av_freep(&enc->tmpData);
977 av_freep(&enc->cel_evals);
978 av_freep(&enc->closest_cb);
979 av_freep(&enc->this_motion4);
980 av_freep(&enc->last_motion4);
981 av_freep(&enc->this_motion8);
982 av_freep(&enc->last_motion8);
987 static av_cold int roq_encode_init(AVCodecContext *avctx)
989 RoqEncContext *const enc = avctx->priv_data;
990 RoqContext *const roq = &enc->common;
992 av_lfg_init(&enc->randctx, 1);
996 enc->framesSinceKeyframe = 0;
997 if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
998 av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
999 return AVERROR(EINVAL);
1002 if (avctx->width > 65535 || avctx->height > 65535) {
1003 av_log(avctx, AV_LOG_ERROR, "Dimensions are max %d\n", enc->quake3_compat ? 32768 : 65535);
1004 return AVERROR(EINVAL);
1007 if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
1008 av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two, this is not supported by quake\n");
1010 roq->width = avctx->width;
1011 roq->height = avctx->height;
1013 enc->framesSinceKeyframe = 0;
1014 enc->first_frame = 1;
1016 roq->last_frame = av_frame_alloc();
1017 roq->current_frame = av_frame_alloc();
1018 if (!roq->last_frame || !roq->current_frame)
1019 return AVERROR(ENOMEM);
1021 enc->tmpData = av_malloc(sizeof(RoqTempdata));
1024 av_mallocz_array(roq->width * roq->height / 16, sizeof(motion_vect));
1027 av_malloc_array (roq->width * roq->height / 16, sizeof(motion_vect));
1030 av_mallocz_array(roq->width * roq->height / 64, sizeof(motion_vect));
1033 av_malloc_array (roq->width * roq->height / 64, sizeof(motion_vect));
1035 /* 4x4 codebook needs 6 * 4 * 4 / 4 * width * height / 16 * sizeof(int);
1036 * and so does the points buffer. */
1038 av_malloc_array(roq->width * roq->height, 3 * sizeof(int));
1040 if (!enc->tmpData || !enc->this_motion4 || !enc->last_motion4 ||
1041 !enc->this_motion8 || !enc->last_motion8 || !enc->closest_cb)
1042 return AVERROR(ENOMEM);
1044 enc->points = enc->closest_cb + roq->width * roq->height * 3 / 2;
1046 return create_cel_evals(enc);
1049 static void roq_write_video_info_chunk(RoqEncContext *enc)
1051 /* ROQ info chunk */
1052 bytestream_put_le16(&enc->out_buf, RoQ_INFO);
1055 bytestream_put_le32(&enc->out_buf, 8);
1057 /* Unused argument */
1058 bytestream_put_byte(&enc->out_buf, 0x00);
1059 bytestream_put_byte(&enc->out_buf, 0x00);
1062 bytestream_put_le16(&enc->out_buf, enc->common.width);
1065 bytestream_put_le16(&enc->out_buf, enc->common.height);
1067 /* Unused in Quake 3, mimics the output of the real encoder */
1068 bytestream_put_byte(&enc->out_buf, 0x08);
1069 bytestream_put_byte(&enc->out_buf, 0x00);
1070 bytestream_put_byte(&enc->out_buf, 0x04);
1071 bytestream_put_byte(&enc->out_buf, 0x00);
1074 static int roq_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1075 const AVFrame *frame, int *got_packet)
1077 RoqEncContext *const enc = avctx->priv_data;
1078 RoqContext *const roq = &enc->common;
1083 enc->frame_to_enc = frame;
1086 enc->lambda = frame->quality - 1;
1088 enc->lambda = 2*ROQ_LAMBDA_SCALE;
1090 /* 138 bits max per 8x8 block +
1091 * 256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */
1092 size = ((roq->width * roq->height / 64) * 138 + 7) / 8 + 256 * (6 + 4) + 8;
1093 if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0)
1095 enc->out_buf = pkt->data;
1097 /* Check for I-frame */
1098 if (enc->framesSinceKeyframe == avctx->gop_size)
1099 enc->framesSinceKeyframe = 0;
1101 if (enc->first_frame) {
1102 /* Alloc memory for the reconstruction data (we must know the stride
1104 if ((ret = ff_get_buffer(avctx, roq->current_frame, 0)) < 0 ||
1105 (ret = ff_get_buffer(avctx, roq->last_frame, 0)) < 0)
1108 /* Before the first video frame, write a "video info" chunk */
1109 roq_write_video_info_chunk(enc);
1111 enc->first_frame = 0;
1114 /* Encode the actual frame */
1115 ret = roq_encode_video(enc);
1119 pkt->size = enc->out_buf - pkt->data;
1120 if (enc->framesSinceKeyframe == 1)
1121 pkt->flags |= AV_PKT_FLAG_KEY;
1127 #define OFFSET(x) offsetof(RoqEncContext, x)
1128 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1129 static const AVOption options[] = {
1130 { "quake3_compat", "Whether to respect known limitations in Quake 3 decoder", OFFSET(quake3_compat), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, VE },
1134 static const AVClass roq_class = {
1135 .class_name = "RoQ",
1136 .item_name = av_default_item_name,
1138 .version = LIBAVUTIL_VERSION_INT,
1141 AVCodec ff_roq_encoder = {
1143 .long_name = NULL_IF_CONFIG_SMALL("id RoQ video"),
1144 .type = AVMEDIA_TYPE_VIDEO,
1145 .id = AV_CODEC_ID_ROQ,
1146 .priv_data_size = sizeof(RoqEncContext),
1147 .init = roq_encode_init,
1148 .encode2 = roq_encode_frame,
1149 .close = roq_encode_end,
1150 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUVJ444P,
1152 .priv_class = &roq_class,
1153 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,