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