You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2140 lines
70KB

  1. /*
  2. * FFV1 codec for libavcodec
  3. *
  4. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * FF Video Codec 1 (a lossless codec)
  25. */
  26. #include "avcodec.h"
  27. #include "internal.h"
  28. #include "get_bits.h"
  29. #include "put_bits.h"
  30. #include "dsputil.h"
  31. #include "rangecoder.h"
  32. #include "golomb.h"
  33. #include "mathops.h"
  34. #include "libavutil/pixdesc.h"
  35. #include "libavutil/avassert.h"
  36. #include "libavutil/crc.h"
  37. #include "libavutil/opt.h"
  38. #include "libavutil/imgutils.h"
  39. #ifdef __INTEL_COMPILER
  40. #undef av_flatten
  41. #define av_flatten
  42. #endif
  43. #define MAX_PLANES 4
  44. #define CONTEXT_SIZE 32
  45. #define MAX_QUANT_TABLES 8
  46. #define MAX_CONTEXT_INPUTS 5
  47. extern const uint8_t ff_log2_run[41];
  48. static const int8_t quant5_10bit[256]={
  49. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
  50. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  51. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  52. 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  53. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  54. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  55. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  56. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  57. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  58. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  59. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  60. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  61. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-1,
  62. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  63. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  64. -1,-1,-1,-1,-1,-1,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,
  65. };
  66. static const int8_t quant5[256]={
  67. 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  68. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  69. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  70. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  71. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  72. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  73. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  74. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  75. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  76. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  77. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  78. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  79. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  80. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  81. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  82. -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-1,-1,-1,
  83. };
  84. static const int8_t quant9_10bit[256]={
  85. 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2,
  86. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
  87. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  88. 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  89. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  90. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  91. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  92. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  93. -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
  94. -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
  95. -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
  96. -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
  97. -4,-4,-4,-4,-4,-4,-4,-4,-4,-3,-3,-3,-3,-3,-3,-3,
  98. -3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,
  99. -3,-3,-3,-3,-3,-3,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
  100. -2,-2,-2,-2,-1,-1,-1,-1,-1,-1,-1,-1,-0,-0,-0,-0,
  101. };
  102. static const int8_t quant11[256]={
  103. 0, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4,
  104. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  105. 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  106. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  107. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  108. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  109. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  110. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  111. -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,
  112. -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,
  113. -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,
  114. -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,
  115. -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,
  116. -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-4,-4,
  117. -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
  118. -4,-4,-4,-4,-4,-3,-3,-3,-3,-3,-3,-3,-2,-2,-2,-1,
  119. };
  120. static const uint8_t ver2_state[256]= {
  121. 0, 10, 10, 10, 10, 16, 16, 16, 28, 16, 16, 29, 42, 49, 20, 49,
  122. 59, 25, 26, 26, 27, 31, 33, 33, 33, 34, 34, 37, 67, 38, 39, 39,
  123. 40, 40, 41, 79, 43, 44, 45, 45, 48, 48, 64, 50, 51, 52, 88, 52,
  124. 53, 74, 55, 57, 58, 58, 74, 60, 101, 61, 62, 84, 66, 66, 68, 69,
  125. 87, 82, 71, 97, 73, 73, 82, 75, 111, 77, 94, 78, 87, 81, 83, 97,
  126. 85, 83, 94, 86, 99, 89, 90, 99, 111, 92, 93, 134, 95, 98, 105, 98,
  127. 105, 110, 102, 108, 102, 118, 103, 106, 106, 113, 109, 112, 114, 112, 116, 125,
  128. 115, 116, 117, 117, 126, 119, 125, 121, 121, 123, 145, 124, 126, 131, 127, 129,
  129. 165, 130, 132, 138, 133, 135, 145, 136, 137, 139, 146, 141, 143, 142, 144, 148,
  130. 147, 155, 151, 149, 151, 150, 152, 157, 153, 154, 156, 168, 158, 162, 161, 160,
  131. 172, 163, 169, 164, 166, 184, 167, 170, 177, 174, 171, 173, 182, 176, 180, 178,
  132. 175, 189, 179, 181, 186, 183, 192, 185, 200, 187, 191, 188, 190, 197, 193, 196,
  133. 197, 194, 195, 196, 198, 202, 199, 201, 210, 203, 207, 204, 205, 206, 208, 214,
  134. 209, 211, 221, 212, 213, 215, 224, 216, 217, 218, 219, 220, 222, 228, 223, 225,
  135. 226, 224, 227, 229, 240, 230, 231, 232, 233, 234, 235, 236, 238, 239, 237, 242,
  136. 241, 243, 242, 244, 245, 246, 247, 248, 249, 250, 251, 252, 252, 253, 254, 255,
  137. };
  138. typedef struct VlcState{
  139. int16_t drift;
  140. uint16_t error_sum;
  141. int8_t bias;
  142. uint8_t count;
  143. } VlcState;
  144. typedef struct PlaneContext{
  145. int16_t quant_table[MAX_CONTEXT_INPUTS][256];
  146. int quant_table_index;
  147. int context_count;
  148. uint8_t (*state)[CONTEXT_SIZE];
  149. VlcState *vlc_state;
  150. uint8_t interlace_bit_state[2];
  151. } PlaneContext;
  152. #define MAX_SLICES 256
  153. typedef struct FFV1Context{
  154. AVClass *class;
  155. AVCodecContext *avctx;
  156. RangeCoder c;
  157. GetBitContext gb;
  158. PutBitContext pb;
  159. uint64_t rc_stat[256][2];
  160. uint64_t (*rc_stat2[MAX_QUANT_TABLES])[32][2];
  161. int version;
  162. int minor_version;
  163. int width, height;
  164. int chroma_h_shift, chroma_v_shift;
  165. int chroma_planes;
  166. int transparency;
  167. int flags;
  168. int picture_number;
  169. AVFrame picture;
  170. AVFrame last_picture;
  171. int plane_count;
  172. int ac; ///< 1=range coder <-> 0=golomb rice
  173. int ac_byte_count; ///< number of bytes used for AC coding
  174. PlaneContext plane[MAX_PLANES];
  175. int16_t quant_table[MAX_CONTEXT_INPUTS][256];
  176. int16_t quant_tables[MAX_QUANT_TABLES][MAX_CONTEXT_INPUTS][256];
  177. int context_count[MAX_QUANT_TABLES];
  178. uint8_t state_transition[256];
  179. uint8_t (*initial_states[MAX_QUANT_TABLES])[32];
  180. int run_index;
  181. int colorspace;
  182. int16_t *sample_buffer;
  183. int gob_count;
  184. int packed_at_lsb;
  185. int ec;
  186. int slice_damaged;
  187. int key_frame_ok;
  188. int quant_table_count;
  189. DSPContext dsp;
  190. struct FFV1Context *slice_context[MAX_SLICES];
  191. int slice_count;
  192. int num_v_slices;
  193. int num_h_slices;
  194. int slice_width;
  195. int slice_height;
  196. int slice_x;
  197. int slice_y;
  198. int bits_per_raw_sample;
  199. }FFV1Context;
  200. static av_always_inline int fold(int diff, int bits){
  201. if(bits==8)
  202. diff= (int8_t)diff;
  203. else{
  204. diff+= 1<<(bits-1);
  205. diff&=(1<<bits)-1;
  206. diff-= 1<<(bits-1);
  207. }
  208. return diff;
  209. }
  210. static inline int predict(int16_t *src, int16_t *last)
  211. {
  212. const int LT= last[-1];
  213. const int T= last[ 0];
  214. const int L = src[-1];
  215. return mid_pred(L, L + T - LT, T);
  216. }
  217. static inline int get_context(PlaneContext *p, int16_t *src,
  218. int16_t *last, int16_t *last2)
  219. {
  220. const int LT= last[-1];
  221. const int T= last[ 0];
  222. const int RT= last[ 1];
  223. const int L = src[-1];
  224. if(p->quant_table[3][127]){
  225. const int TT= last2[0];
  226. const int LL= src[-2];
  227. return p->quant_table[0][(L-LT) & 0xFF] + p->quant_table[1][(LT-T) & 0xFF] + p->quant_table[2][(T-RT) & 0xFF]
  228. +p->quant_table[3][(LL-L) & 0xFF] + p->quant_table[4][(TT-T) & 0xFF];
  229. }else
  230. return p->quant_table[0][(L-LT) & 0xFF] + p->quant_table[1][(LT-T) & 0xFF] + p->quant_table[2][(T-RT) & 0xFF];
  231. }
  232. static void find_best_state(uint8_t best_state[256][256], const uint8_t one_state[256]){
  233. int i,j,k,m;
  234. double l2tab[256];
  235. for(i=1; i<256; i++)
  236. l2tab[i]= log2(i/256.0);
  237. for(i=0; i<256; i++){
  238. double best_len[256];
  239. double p= i/256.0;
  240. for(j=0; j<256; j++)
  241. best_len[j]= 1<<30;
  242. for(j=FFMAX(i-10,1); j<FFMIN(i+11,256); j++){
  243. double occ[256]={0};
  244. double len=0;
  245. occ[j]=1.0;
  246. for(k=0; k<256; k++){
  247. double newocc[256]={0};
  248. for(m=0; m<256; m++){
  249. if(occ[m]){
  250. len -=occ[m]*( p *l2tab[ m]
  251. + (1-p)*l2tab[256-m]);
  252. }
  253. }
  254. if(len < best_len[k]){
  255. best_len[k]= len;
  256. best_state[i][k]= j;
  257. }
  258. for(m=0; m<256; m++){
  259. if(occ[m]){
  260. newocc[ one_state[ m]] += occ[m]* p ;
  261. newocc[256-one_state[256-m]] += occ[m]*(1-p);
  262. }
  263. }
  264. memcpy(occ, newocc, sizeof(occ));
  265. }
  266. }
  267. }
  268. }
  269. static av_always_inline av_flatten void put_symbol_inline(RangeCoder *c, uint8_t *state, int v, int is_signed, uint64_t rc_stat[256][2], uint64_t rc_stat2[32][2]){
  270. int i;
  271. #define put_rac(C,S,B) \
  272. do{\
  273. if(rc_stat){\
  274. rc_stat[*(S)][B]++;\
  275. rc_stat2[(S)-state][B]++;\
  276. }\
  277. put_rac(C,S,B);\
  278. }while(0)
  279. if(v){
  280. const int a= FFABS(v);
  281. const int e= av_log2(a);
  282. put_rac(c, state+0, 0);
  283. if(e<=9){
  284. for(i=0; i<e; i++){
  285. put_rac(c, state+1+i, 1); //1..10
  286. }
  287. put_rac(c, state+1+i, 0);
  288. for(i=e-1; i>=0; i--){
  289. put_rac(c, state+22+i, (a>>i)&1); //22..31
  290. }
  291. if(is_signed)
  292. put_rac(c, state+11 + e, v < 0); //11..21
  293. }else{
  294. for(i=0; i<e; i++){
  295. put_rac(c, state+1+FFMIN(i,9), 1); //1..10
  296. }
  297. put_rac(c, state+1+9, 0);
  298. for(i=e-1; i>=0; i--){
  299. put_rac(c, state+22+FFMIN(i,9), (a>>i)&1); //22..31
  300. }
  301. if(is_signed)
  302. put_rac(c, state+11 + 10, v < 0); //11..21
  303. }
  304. }else{
  305. put_rac(c, state+0, 1);
  306. }
  307. #undef put_rac
  308. }
  309. static av_noinline void put_symbol(RangeCoder *c, uint8_t *state, int v, int is_signed){
  310. put_symbol_inline(c, state, v, is_signed, NULL, NULL);
  311. }
  312. static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state, int is_signed){
  313. if(get_rac(c, state+0))
  314. return 0;
  315. else{
  316. int i, e, a;
  317. e= 0;
  318. while(get_rac(c, state+1 + FFMIN(e,9))){ //1..10
  319. e++;
  320. }
  321. a= 1;
  322. for(i=e-1; i>=0; i--){
  323. a += a + get_rac(c, state+22 + FFMIN(i,9)); //22..31
  324. }
  325. e= -(is_signed && get_rac(c, state+11 + FFMIN(e, 10))); //11..21
  326. return (a^e)-e;
  327. }
  328. }
  329. static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed){
  330. return get_symbol_inline(c, state, is_signed);
  331. }
  332. static inline void update_vlc_state(VlcState * const state, const int v){
  333. int drift= state->drift;
  334. int count= state->count;
  335. state->error_sum += FFABS(v);
  336. drift += v;
  337. if(count == 128){ //FIXME variable
  338. count >>= 1;
  339. drift >>= 1;
  340. state->error_sum >>= 1;
  341. }
  342. count++;
  343. if(drift <= -count){
  344. if(state->bias > -128) state->bias--;
  345. drift += count;
  346. if(drift <= -count)
  347. drift= -count + 1;
  348. }else if(drift > 0){
  349. if(state->bias < 127) state->bias++;
  350. drift -= count;
  351. if(drift > 0)
  352. drift= 0;
  353. }
  354. state->drift= drift;
  355. state->count= count;
  356. }
  357. static inline void put_vlc_symbol(PutBitContext *pb, VlcState * const state, int v, int bits){
  358. int i, k, code;
  359. //printf("final: %d ", v);
  360. v = fold(v - state->bias, bits);
  361. i= state->count;
  362. k=0;
  363. while(i < state->error_sum){ //FIXME optimize
  364. k++;
  365. i += i;
  366. }
  367. assert(k<=8);
  368. #if 0 // JPEG LS
  369. if(k==0 && 2*state->drift <= - state->count) code= v ^ (-1);
  370. else code= v;
  371. #else
  372. code= v ^ ((2*state->drift + state->count)>>31);
  373. #endif
  374. //printf("v:%d/%d bias:%d error:%d drift:%d count:%d k:%d\n", v, code, state->bias, state->error_sum, state->drift, state->count, k);
  375. set_sr_golomb(pb, code, k, 12, bits);
  376. update_vlc_state(state, v);
  377. }
  378. static inline int get_vlc_symbol(GetBitContext *gb, VlcState * const state, int bits){
  379. int k, i, v, ret;
  380. i= state->count;
  381. k=0;
  382. while(i < state->error_sum){ //FIXME optimize
  383. k++;
  384. i += i;
  385. }
  386. assert(k<=8);
  387. v= get_sr_golomb(gb, k, 12, bits);
  388. //printf("v:%d bias:%d error:%d drift:%d count:%d k:%d", v, state->bias, state->error_sum, state->drift, state->count, k);
  389. #if 0 // JPEG LS
  390. if(k==0 && 2*state->drift <= - state->count) v ^= (-1);
  391. #else
  392. v ^= ((2*state->drift + state->count)>>31);
  393. #endif
  394. ret= fold(v + state->bias, bits);
  395. update_vlc_state(state, v);
  396. //printf("final: %d\n", ret);
  397. return ret;
  398. }
  399. #if CONFIG_FFV1_ENCODER
  400. static av_always_inline int encode_line(FFV1Context *s, int w,
  401. int16_t *sample[3],
  402. int plane_index, int bits)
  403. {
  404. PlaneContext * const p= &s->plane[plane_index];
  405. RangeCoder * const c= &s->c;
  406. int x;
  407. int run_index= s->run_index;
  408. int run_count=0;
  409. int run_mode=0;
  410. if(s->ac){
  411. if(c->bytestream_end - c->bytestream < w*20){
  412. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  413. return -1;
  414. }
  415. }else{
  416. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < w*4){
  417. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  418. return -1;
  419. }
  420. }
  421. for(x=0; x<w; x++){
  422. int diff, context;
  423. context= get_context(p, sample[0]+x, sample[1]+x, sample[2]+x);
  424. diff= sample[0][x] - predict(sample[0]+x, sample[1]+x);
  425. if(context < 0){
  426. context = -context;
  427. diff= -diff;
  428. }
  429. diff= fold(diff, bits);
  430. if(s->ac){
  431. if(s->flags & CODEC_FLAG_PASS1){
  432. put_symbol_inline(c, p->state[context], diff, 1, s->rc_stat, s->rc_stat2[p->quant_table_index][context]);
  433. }else{
  434. put_symbol_inline(c, p->state[context], diff, 1, NULL, NULL);
  435. }
  436. }else{
  437. if(context == 0) run_mode=1;
  438. if(run_mode){
  439. if(diff){
  440. while(run_count >= 1<<ff_log2_run[run_index]){
  441. run_count -= 1<<ff_log2_run[run_index];
  442. run_index++;
  443. put_bits(&s->pb, 1, 1);
  444. }
  445. put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);
  446. if(run_index) run_index--;
  447. run_count=0;
  448. run_mode=0;
  449. if(diff>0) diff--;
  450. }else{
  451. run_count++;
  452. }
  453. }
  454. // printf("count:%d index:%d, mode:%d, x:%d y:%d pos:%d\n", run_count, run_index, run_mode, x, y, (int)put_bits_count(&s->pb));
  455. if(run_mode == 0)
  456. put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);
  457. }
  458. }
  459. if(run_mode){
  460. while(run_count >= 1<<ff_log2_run[run_index]){
  461. run_count -= 1<<ff_log2_run[run_index];
  462. run_index++;
  463. put_bits(&s->pb, 1, 1);
  464. }
  465. if(run_count)
  466. put_bits(&s->pb, 1, 1);
  467. }
  468. s->run_index= run_index;
  469. return 0;
  470. }
  471. static void encode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index){
  472. int x,y,i;
  473. const int ring_size= s->avctx->context_model ? 3 : 2;
  474. int16_t *sample[3];
  475. s->run_index=0;
  476. memset(s->sample_buffer, 0, ring_size*(w+6)*sizeof(*s->sample_buffer));
  477. for(y=0; y<h; y++){
  478. for(i=0; i<ring_size; i++)
  479. sample[i]= s->sample_buffer + (w+6)*((h+i-y)%ring_size) + 3;
  480. sample[0][-1]= sample[1][0 ];
  481. sample[1][ w]= sample[1][w-1];
  482. //{START_TIMER
  483. if(s->bits_per_raw_sample<=8){
  484. for(x=0; x<w; x++){
  485. sample[0][x]= src[x + stride*y];
  486. }
  487. encode_line(s, w, sample, plane_index, 8);
  488. }else{
  489. if(s->packed_at_lsb){
  490. for(x=0; x<w; x++){
  491. sample[0][x]= ((uint16_t*)(src + stride*y))[x];
  492. }
  493. }else{
  494. for(x=0; x<w; x++){
  495. sample[0][x]= ((uint16_t*)(src + stride*y))[x] >> (16 - s->bits_per_raw_sample);
  496. }
  497. }
  498. encode_line(s, w, sample, plane_index, s->bits_per_raw_sample);
  499. }
  500. //STOP_TIMER("encode line")}
  501. }
  502. }
  503. static void encode_rgb_frame(FFV1Context *s, uint32_t *src, int w, int h, int stride){
  504. int x, y, p, i;
  505. const int ring_size= s->avctx->context_model ? 3 : 2;
  506. int16_t *sample[4][3];
  507. s->run_index=0;
  508. memset(s->sample_buffer, 0, ring_size*4*(w+6)*sizeof(*s->sample_buffer));
  509. for(y=0; y<h; y++){
  510. for(i=0; i<ring_size; i++)
  511. for(p=0; p<4; p++)
  512. sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;
  513. for(x=0; x<w; x++){
  514. unsigned v= src[x + stride*y];
  515. int b= v&0xFF;
  516. int g= (v>>8)&0xFF;
  517. int r= (v>>16)&0xFF;
  518. int a= v>>24;
  519. b -= g;
  520. r -= g;
  521. g += (b + r)>>2;
  522. b += 0x100;
  523. r += 0x100;
  524. // assert(g>=0 && b>=0 && r>=0);
  525. // assert(g<256 && b<512 && r<512);
  526. sample[0][0][x]= g;
  527. sample[1][0][x]= b;
  528. sample[2][0][x]= r;
  529. sample[3][0][x]= a;
  530. }
  531. for(p=0; p<3 + s->transparency; p++){
  532. sample[p][0][-1]= sample[p][1][0 ];
  533. sample[p][1][ w]= sample[p][1][w-1];
  534. encode_line(s, w, sample[p], (p+1)/2, 9);
  535. }
  536. }
  537. }
  538. static void write_quant_table(RangeCoder *c, int16_t *quant_table){
  539. int last=0;
  540. int i;
  541. uint8_t state[CONTEXT_SIZE];
  542. memset(state, 128, sizeof(state));
  543. for(i=1; i<128 ; i++){
  544. if(quant_table[i] != quant_table[i-1]){
  545. put_symbol(c, state, i-last-1, 0);
  546. last= i;
  547. }
  548. }
  549. put_symbol(c, state, i-last-1, 0);
  550. }
  551. static void write_quant_tables(RangeCoder *c, int16_t quant_table[MAX_CONTEXT_INPUTS][256]){
  552. int i;
  553. for(i=0; i<5; i++)
  554. write_quant_table(c, quant_table[i]);
  555. }
  556. static void write_header(FFV1Context *f){
  557. uint8_t state[CONTEXT_SIZE];
  558. int i, j;
  559. RangeCoder * const c= &f->slice_context[0]->c;
  560. memset(state, 128, sizeof(state));
  561. if(f->version < 2){
  562. put_symbol(c, state, f->version, 0);
  563. put_symbol(c, state, f->ac, 0);
  564. if(f->ac>1){
  565. for(i=1; i<256; i++){
  566. put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
  567. }
  568. }
  569. put_symbol(c, state, f->colorspace, 0); //YUV cs type
  570. if(f->version>0)
  571. put_symbol(c, state, f->bits_per_raw_sample, 0);
  572. put_rac(c, state, f->chroma_planes);
  573. put_symbol(c, state, f->chroma_h_shift, 0);
  574. put_symbol(c, state, f->chroma_v_shift, 0);
  575. put_rac(c, state, f->transparency);
  576. write_quant_tables(c, f->quant_table);
  577. }else if(f->version < 3){
  578. put_symbol(c, state, f->slice_count, 0);
  579. for(i=0; i<f->slice_count; i++){
  580. FFV1Context *fs= f->slice_context[i];
  581. put_symbol(c, state, (fs->slice_x +1)*f->num_h_slices / f->width , 0);
  582. put_symbol(c, state, (fs->slice_y +1)*f->num_v_slices / f->height , 0);
  583. put_symbol(c, state, (fs->slice_width +1)*f->num_h_slices / f->width -1, 0);
  584. put_symbol(c, state, (fs->slice_height+1)*f->num_v_slices / f->height-1, 0);
  585. for(j=0; j<f->plane_count; j++){
  586. put_symbol(c, state, f->plane[j].quant_table_index, 0);
  587. av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
  588. }
  589. }
  590. }
  591. }
  592. #endif /* CONFIG_FFV1_ENCODER */
  593. static av_cold int common_init(AVCodecContext *avctx){
  594. FFV1Context *s = avctx->priv_data;
  595. s->avctx= avctx;
  596. s->flags= avctx->flags;
  597. avcodec_get_frame_defaults(&s->picture);
  598. ff_dsputil_init(&s->dsp, avctx);
  599. s->width = avctx->width;
  600. s->height= avctx->height;
  601. assert(s->width && s->height);
  602. //defaults
  603. s->num_h_slices=1;
  604. s->num_v_slices=1;
  605. return 0;
  606. }
  607. static int init_slice_state(FFV1Context *f, FFV1Context *fs){
  608. int j;
  609. fs->plane_count= f->plane_count;
  610. fs->transparency= f->transparency;
  611. for(j=0; j<f->plane_count; j++){
  612. PlaneContext * const p= &fs->plane[j];
  613. if(fs->ac){
  614. if(!p-> state) p-> state= av_malloc(CONTEXT_SIZE*p->context_count*sizeof(uint8_t));
  615. if(!p-> state)
  616. return AVERROR(ENOMEM);
  617. }else{
  618. if(!p->vlc_state) p->vlc_state= av_malloc(p->context_count*sizeof(VlcState));
  619. if(!p->vlc_state)
  620. return AVERROR(ENOMEM);
  621. }
  622. }
  623. if (fs->ac>1){
  624. //FIXME only redo if state_transition changed
  625. for(j=1; j<256; j++){
  626. fs->c.one_state [ j]= f->state_transition[j];
  627. fs->c.zero_state[256-j]= 256-fs->c.one_state [j];
  628. }
  629. }
  630. return 0;
  631. }
  632. static int init_slices_state(FFV1Context *f){
  633. int i;
  634. for(i=0; i<f->slice_count; i++){
  635. FFV1Context *fs= f->slice_context[i];
  636. if(init_slice_state(f, fs) < 0)
  637. return -1;
  638. }
  639. return 0;
  640. }
  641. static av_cold int init_slice_contexts(FFV1Context *f){
  642. int i;
  643. f->slice_count= f->num_h_slices * f->num_v_slices;
  644. for(i=0; i<f->slice_count; i++){
  645. FFV1Context *fs= av_mallocz(sizeof(*fs));
  646. int sx= i % f->num_h_slices;
  647. int sy= i / f->num_h_slices;
  648. int sxs= f->avctx->width * sx / f->num_h_slices;
  649. int sxe= f->avctx->width *(sx+1) / f->num_h_slices;
  650. int sys= f->avctx->height* sy / f->num_v_slices;
  651. int sye= f->avctx->height*(sy+1) / f->num_v_slices;
  652. f->slice_context[i]= fs;
  653. memcpy(fs, f, sizeof(*fs));
  654. memset(fs->rc_stat2, 0, sizeof(fs->rc_stat2));
  655. fs->slice_width = sxe - sxs;
  656. fs->slice_height= sye - sys;
  657. fs->slice_x = sxs;
  658. fs->slice_y = sys;
  659. fs->sample_buffer = av_malloc(3*4 * (fs->width+6) * sizeof(*fs->sample_buffer));
  660. if (!fs->sample_buffer)
  661. return AVERROR(ENOMEM);
  662. }
  663. return 0;
  664. }
  665. static int allocate_initial_states(FFV1Context *f){
  666. int i;
  667. for(i=0; i<f->quant_table_count; i++){
  668. f->initial_states[i]= av_malloc(f->context_count[i]*sizeof(*f->initial_states[i]));
  669. if(!f->initial_states[i])
  670. return AVERROR(ENOMEM);
  671. memset(f->initial_states[i], 128, f->context_count[i]*sizeof(*f->initial_states[i]));
  672. }
  673. return 0;
  674. }
  675. #if CONFIG_FFV1_ENCODER
  676. static int write_extra_header(FFV1Context *f){
  677. RangeCoder * const c= &f->c;
  678. uint8_t state[CONTEXT_SIZE];
  679. int i, j, k;
  680. uint8_t state2[32][CONTEXT_SIZE];
  681. unsigned v;
  682. memset(state2, 128, sizeof(state2));
  683. memset(state, 128, sizeof(state));
  684. f->avctx->extradata= av_malloc(f->avctx->extradata_size= 10000 + (11*11*5*5*5+11*11*11)*32);
  685. ff_init_range_encoder(c, f->avctx->extradata, f->avctx->extradata_size);
  686. ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
  687. put_symbol(c, state, f->version, 0);
  688. if(f->version > 2)
  689. put_symbol(c, state, f->minor_version, 0);
  690. put_symbol(c, state, f->ac, 0);
  691. if(f->ac>1){
  692. for(i=1; i<256; i++){
  693. put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
  694. }
  695. }
  696. put_symbol(c, state, f->colorspace, 0); //YUV cs type
  697. put_symbol(c, state, f->bits_per_raw_sample, 0);
  698. put_rac(c, state, f->chroma_planes);
  699. put_symbol(c, state, f->chroma_h_shift, 0);
  700. put_symbol(c, state, f->chroma_v_shift, 0);
  701. put_rac(c, state, f->transparency);
  702. put_symbol(c, state, f->num_h_slices-1, 0);
  703. put_symbol(c, state, f->num_v_slices-1, 0);
  704. put_symbol(c, state, f->quant_table_count, 0);
  705. for(i=0; i<f->quant_table_count; i++)
  706. write_quant_tables(c, f->quant_tables[i]);
  707. for(i=0; i<f->quant_table_count; i++){
  708. for(j=0; j<f->context_count[i]*CONTEXT_SIZE; j++)
  709. if(f->initial_states[i] && f->initial_states[i][0][j] != 128)
  710. break;
  711. if(j<f->context_count[i]*CONTEXT_SIZE){
  712. put_rac(c, state, 1);
  713. for(j=0; j<f->context_count[i]; j++){
  714. for(k=0; k<CONTEXT_SIZE; k++){
  715. int pred= j ? f->initial_states[i][j-1][k] : 128;
  716. put_symbol(c, state2[k], (int8_t)(f->initial_states[i][j][k]-pred), 1);
  717. }
  718. }
  719. }else{
  720. put_rac(c, state, 0);
  721. }
  722. }
  723. if(f->version > 2){
  724. put_symbol(c, state, f->ec, 0);
  725. }
  726. f->avctx->extradata_size= ff_rac_terminate(c);
  727. v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
  728. AV_WL32(f->avctx->extradata + f->avctx->extradata_size, v);
  729. f->avctx->extradata_size += 4;
  730. return 0;
  731. }
  732. static int sort_stt(FFV1Context *s, uint8_t stt[256]){
  733. int i,i2,changed,print=0;
  734. do{
  735. changed=0;
  736. for(i=12; i<244; i++){
  737. for(i2=i+1; i2<245 && i2<i+4; i2++){
  738. #define COST(old, new) \
  739. s->rc_stat[old][0]*-log2((256-(new))/256.0)\
  740. +s->rc_stat[old][1]*-log2( (new) /256.0)
  741. #define COST2(old, new) \
  742. COST(old, new)\
  743. +COST(256-(old), 256-(new))
  744. double size0= COST2(i, i ) + COST2(i2, i2);
  745. double sizeX= COST2(i, i2) + COST2(i2, i );
  746. if(sizeX < size0 && i!=128 && i2!=128){
  747. int j;
  748. FFSWAP(int, stt[ i], stt[ i2]);
  749. FFSWAP(int, s->rc_stat[i ][0],s->rc_stat[ i2][0]);
  750. FFSWAP(int, s->rc_stat[i ][1],s->rc_stat[ i2][1]);
  751. if(i != 256-i2){
  752. FFSWAP(int, stt[256-i], stt[256-i2]);
  753. FFSWAP(int, s->rc_stat[256-i][0],s->rc_stat[256-i2][0]);
  754. FFSWAP(int, s->rc_stat[256-i][1],s->rc_stat[256-i2][1]);
  755. }
  756. for(j=1; j<256; j++){
  757. if (stt[j] == i ) stt[j] = i2;
  758. else if(stt[j] == i2) stt[j] = i ;
  759. if(i != 256-i2){
  760. if (stt[256-j] == 256-i ) stt[256-j] = 256-i2;
  761. else if(stt[256-j] == 256-i2) stt[256-j] = 256-i ;
  762. }
  763. }
  764. print=changed=1;
  765. }
  766. }
  767. }
  768. }while(changed);
  769. return print;
  770. }
  771. static av_cold int encode_init(AVCodecContext *avctx)
  772. {
  773. FFV1Context *s = avctx->priv_data;
  774. int i, j, k, m;
  775. common_init(avctx);
  776. s->version=0;
  777. if((avctx->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)) || avctx->slices>1)
  778. s->version = FFMAX(s->version, 2);
  779. if(avctx->level == 3){
  780. s->version = 3;
  781. }
  782. if(s->ec < 0){
  783. s->ec = (s->version >= 3);
  784. }
  785. if(s->version >= 2 && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  786. av_log(avctx, AV_LOG_ERROR, "Version 2 needed for requested features but version 2 is experimental and not enabled\n");
  787. return AVERROR_INVALIDDATA;
  788. }
  789. s->ac= avctx->coder_type > 0 ? 2 : 0;
  790. s->plane_count=3;
  791. switch(avctx->pix_fmt){
  792. case PIX_FMT_YUV444P9:
  793. case PIX_FMT_YUV422P9:
  794. case PIX_FMT_YUV420P9:
  795. if (!avctx->bits_per_raw_sample)
  796. s->bits_per_raw_sample = 9;
  797. case PIX_FMT_YUV444P10:
  798. case PIX_FMT_YUV420P10:
  799. case PIX_FMT_YUV422P10:
  800. s->packed_at_lsb = 1;
  801. if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
  802. s->bits_per_raw_sample = 10;
  803. case PIX_FMT_GRAY16:
  804. case PIX_FMT_YUV444P16:
  805. case PIX_FMT_YUV422P16:
  806. case PIX_FMT_YUV420P16:
  807. if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {
  808. s->bits_per_raw_sample = 16;
  809. } else if (!s->bits_per_raw_sample){
  810. s->bits_per_raw_sample = avctx->bits_per_raw_sample;
  811. }
  812. if(s->bits_per_raw_sample <=8){
  813. av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");
  814. return AVERROR_INVALIDDATA;
  815. }
  816. if(!s->ac && avctx->coder_type == -1) {
  817. av_log(avctx, AV_LOG_INFO, "bits_per_raw_sample > 8, forcing coder 1\n");
  818. s->ac = 2;
  819. }
  820. if(!s->ac){
  821. av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
  822. return AVERROR_INVALIDDATA;
  823. }
  824. s->version= FFMAX(s->version, 1);
  825. case PIX_FMT_GRAY8:
  826. case PIX_FMT_YUV444P:
  827. case PIX_FMT_YUV440P:
  828. case PIX_FMT_YUV422P:
  829. case PIX_FMT_YUV420P:
  830. case PIX_FMT_YUV411P:
  831. case PIX_FMT_YUV410P:
  832. s->chroma_planes= av_pix_fmt_descriptors[avctx->pix_fmt].nb_components < 3 ? 0 : 1;
  833. s->colorspace= 0;
  834. break;
  835. case PIX_FMT_YUVA444P:
  836. case PIX_FMT_YUVA422P:
  837. case PIX_FMT_YUVA420P:
  838. s->chroma_planes= 1;
  839. s->colorspace= 0;
  840. s->transparency= 1;
  841. break;
  842. case PIX_FMT_RGB32:
  843. s->colorspace= 1;
  844. s->transparency= 1;
  845. break;
  846. case PIX_FMT_0RGB32:
  847. s->colorspace= 1;
  848. break;
  849. default:
  850. av_log(avctx, AV_LOG_ERROR, "format not supported\n");
  851. return AVERROR_INVALIDDATA;
  852. }
  853. if (s->transparency) {
  854. av_log(avctx, AV_LOG_WARNING, "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");
  855. }
  856. if (avctx->context_model > 1U) {
  857. av_log(avctx, AV_LOG_ERROR, "Invalid context model %d, valid values are 0 and 1\n", avctx->context_model);
  858. return AVERROR(EINVAL);
  859. }
  860. if(s->ac>1)
  861. for(i=1; i<256; i++)
  862. s->state_transition[i]=ver2_state[i];
  863. for(i=0; i<256; i++){
  864. s->quant_table_count=2;
  865. if(s->bits_per_raw_sample <=8){
  866. s->quant_tables[0][0][i]= quant11[i];
  867. s->quant_tables[0][1][i]= 11*quant11[i];
  868. s->quant_tables[0][2][i]= 11*11*quant11[i];
  869. s->quant_tables[1][0][i]= quant11[i];
  870. s->quant_tables[1][1][i]= 11*quant11[i];
  871. s->quant_tables[1][2][i]= 11*11*quant5 [i];
  872. s->quant_tables[1][3][i]= 5*11*11*quant5 [i];
  873. s->quant_tables[1][4][i]= 5*5*11*11*quant5 [i];
  874. }else{
  875. s->quant_tables[0][0][i]= quant9_10bit[i];
  876. s->quant_tables[0][1][i]= 11*quant9_10bit[i];
  877. s->quant_tables[0][2][i]= 11*11*quant9_10bit[i];
  878. s->quant_tables[1][0][i]= quant9_10bit[i];
  879. s->quant_tables[1][1][i]= 11*quant9_10bit[i];
  880. s->quant_tables[1][2][i]= 11*11*quant5_10bit[i];
  881. s->quant_tables[1][3][i]= 5*11*11*quant5_10bit[i];
  882. s->quant_tables[1][4][i]= 5*5*11*11*quant5_10bit[i];
  883. }
  884. }
  885. s->context_count[0]= (11*11*11+1)/2;
  886. s->context_count[1]= (11*11*5*5*5+1)/2;
  887. memcpy(s->quant_table, s->quant_tables[avctx->context_model], sizeof(s->quant_table));
  888. for(i=0; i<s->plane_count; i++){
  889. PlaneContext * const p= &s->plane[i];
  890. memcpy(p->quant_table, s->quant_table, sizeof(p->quant_table));
  891. p->quant_table_index= avctx->context_model;
  892. p->context_count= s->context_count[p->quant_table_index];
  893. }
  894. if(allocate_initial_states(s) < 0)
  895. return AVERROR(ENOMEM);
  896. avctx->coded_frame= &s->picture;
  897. if(!s->transparency)
  898. s->plane_count= 2;
  899. avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
  900. s->picture_number=0;
  901. if(avctx->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)){
  902. for(i=0; i<s->quant_table_count; i++){
  903. s->rc_stat2[i]= av_mallocz(s->context_count[i]*sizeof(*s->rc_stat2[i]));
  904. if(!s->rc_stat2[i])
  905. return AVERROR(ENOMEM);
  906. }
  907. }
  908. if(avctx->stats_in){
  909. char *p= avctx->stats_in;
  910. uint8_t best_state[256][256];
  911. int gob_count=0;
  912. char *next;
  913. av_assert0(s->version>=2);
  914. for(;;){
  915. for(j=0; j<256; j++){
  916. for(i=0; i<2; i++){
  917. s->rc_stat[j][i]= strtol(p, &next, 0);
  918. if(next==p){
  919. av_log(avctx, AV_LOG_ERROR, "2Pass file invalid at %d %d [%s]\n", j,i,p);
  920. return -1;
  921. }
  922. p=next;
  923. }
  924. }
  925. for(i=0; i<s->quant_table_count; i++){
  926. for(j=0; j<s->context_count[i]; j++){
  927. for(k=0; k<32; k++){
  928. for(m=0; m<2; m++){
  929. s->rc_stat2[i][j][k][m]= strtol(p, &next, 0);
  930. if(next==p){
  931. av_log(avctx, AV_LOG_ERROR, "2Pass file invalid at %d %d %d %d [%s]\n", i,j,k,m,p);
  932. return AVERROR_INVALIDDATA;
  933. }
  934. p=next;
  935. }
  936. }
  937. }
  938. }
  939. gob_count= strtol(p, &next, 0);
  940. if(next==p || gob_count <0){
  941. av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");
  942. return AVERROR_INVALIDDATA;
  943. }
  944. p=next;
  945. while(*p=='\n' || *p==' ') p++;
  946. if(p[0]==0) break;
  947. }
  948. sort_stt(s, s->state_transition);
  949. find_best_state(best_state, s->state_transition);
  950. for(i=0; i<s->quant_table_count; i++){
  951. for(j=0; j<s->context_count[i]; j++){
  952. for(k=0; k<32; k++){
  953. double p= 128;
  954. if(s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1]){
  955. p=256.0*s->rc_stat2[i][j][k][1] / (s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1]);
  956. }
  957. s->initial_states[i][j][k]= best_state[av_clip(round(p), 1, 255)][av_clip((s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1])/gob_count, 0, 255)];
  958. }
  959. }
  960. }
  961. }
  962. if(s->version>1){
  963. for(s->num_v_slices=2; s->num_v_slices<9; s->num_v_slices++){
  964. for(s->num_h_slices=s->num_v_slices; s->num_h_slices<2*s->num_v_slices; s->num_h_slices++){
  965. if(avctx->slices == s->num_h_slices * s->num_v_slices && avctx->slices <= 64 || !avctx->slices)
  966. goto slices_ok;
  967. }
  968. }
  969. av_log(avctx, AV_LOG_ERROR, "Unsupported number %d of slices requested, please specify a supported number with -slices (ex:4,6,9,12,16, ...)\n", avctx->slices);
  970. return -1;
  971. slices_ok:
  972. write_extra_header(s);
  973. }
  974. if(init_slice_contexts(s) < 0)
  975. return -1;
  976. if(init_slices_state(s) < 0)
  977. return -1;
  978. #define STATS_OUT_SIZE 1024*1024*6
  979. if(avctx->flags & CODEC_FLAG_PASS1){
  980. avctx->stats_out= av_mallocz(STATS_OUT_SIZE);
  981. for(i=0; i<s->quant_table_count; i++){
  982. for(j=0; j<s->slice_count; j++){
  983. FFV1Context *sf= s->slice_context[j];
  984. av_assert0(!sf->rc_stat2[i]);
  985. sf->rc_stat2[i]= av_mallocz(s->context_count[i]*sizeof(*sf->rc_stat2[i]));
  986. if(!sf->rc_stat2[i])
  987. return AVERROR(ENOMEM);
  988. }
  989. }
  990. }
  991. return 0;
  992. }
  993. #endif /* CONFIG_FFV1_ENCODER */
  994. static void clear_slice_state(FFV1Context *f, FFV1Context *fs){
  995. int i, j;
  996. for(i=0; i<f->plane_count; i++){
  997. PlaneContext *p= &fs->plane[i];
  998. p->interlace_bit_state[0]= 128;
  999. p->interlace_bit_state[1]= 128;
  1000. if(fs->ac){
  1001. if(f->initial_states[p->quant_table_index]){
  1002. memcpy(p->state, f->initial_states[p->quant_table_index], CONTEXT_SIZE*p->context_count);
  1003. }else
  1004. memset(p->state, 128, CONTEXT_SIZE*p->context_count);
  1005. }else{
  1006. for(j=0; j<p->context_count; j++){
  1007. p->vlc_state[j].drift= 0;
  1008. p->vlc_state[j].error_sum= 4; //FFMAX((RANGE + 32)/64, 2);
  1009. p->vlc_state[j].bias= 0;
  1010. p->vlc_state[j].count= 1;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. #if CONFIG_FFV1_ENCODER
  1016. static void encode_slice_header(FFV1Context *f, FFV1Context *fs){
  1017. RangeCoder *c = &fs->c;
  1018. uint8_t state[CONTEXT_SIZE];
  1019. int j;
  1020. memset(state, 128, sizeof(state));
  1021. put_symbol(c, state, (fs->slice_x +1)*f->num_h_slices / f->width , 0);
  1022. put_symbol(c, state, (fs->slice_y +1)*f->num_v_slices / f->height , 0);
  1023. put_symbol(c, state, (fs->slice_width +1)*f->num_h_slices / f->width -1, 0);
  1024. put_symbol(c, state, (fs->slice_height+1)*f->num_v_slices / f->height-1, 0);
  1025. for(j=0; j<f->plane_count; j++){
  1026. put_symbol(c, state, f->plane[j].quant_table_index, 0);
  1027. av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
  1028. }
  1029. if(!f->picture.interlaced_frame) put_symbol(c, state, 3, 0);
  1030. else put_symbol(c, state, 1 + !f->picture.top_field_first, 0);
  1031. put_symbol(c, state, f->picture.sample_aspect_ratio.num, 0);
  1032. put_symbol(c, state, f->picture.sample_aspect_ratio.den, 0);
  1033. }
  1034. static int encode_slice(AVCodecContext *c, void *arg){
  1035. FFV1Context *fs= *(void**)arg;
  1036. FFV1Context *f= fs->avctx->priv_data;
  1037. int width = fs->slice_width;
  1038. int height= fs->slice_height;
  1039. int x= fs->slice_x;
  1040. int y= fs->slice_y;
  1041. AVFrame * const p= &f->picture;
  1042. const int ps= (f->bits_per_raw_sample>8)+1;
  1043. if(p->key_frame)
  1044. clear_slice_state(f, fs);
  1045. if(f->version > 2){
  1046. encode_slice_header(f, fs);
  1047. }
  1048. if(!fs->ac){
  1049. fs->ac_byte_count = f->version > 2 || (!x&&!y) ? ff_rac_terminate(&fs->c) : 0;
  1050. init_put_bits(&fs->pb, fs->c.bytestream_start + fs->ac_byte_count, fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count);
  1051. }
  1052. if(f->colorspace==0){
  1053. const int chroma_width = -((-width )>>f->chroma_h_shift);
  1054. const int chroma_height= -((-height)>>f->chroma_v_shift);
  1055. const int cx= x>>f->chroma_h_shift;
  1056. const int cy= y>>f->chroma_v_shift;
  1057. encode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
  1058. if (f->chroma_planes){
  1059. encode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
  1060. encode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
  1061. }
  1062. if (fs->transparency)
  1063. encode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
  1064. }else{
  1065. encode_rgb_frame(fs, (uint32_t*)(p->data[0]) + ps*x + y*(p->linesize[0]/4), width, height, p->linesize[0]/4);
  1066. }
  1067. emms_c();
  1068. return 0;
  1069. }
  1070. static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1071. const AVFrame *pict, int *got_packet)
  1072. {
  1073. FFV1Context *f = avctx->priv_data;
  1074. RangeCoder * const c= &f->slice_context[0]->c;
  1075. AVFrame * const p= &f->picture;
  1076. int used_count= 0;
  1077. uint8_t keystate=128;
  1078. uint8_t *buf_p;
  1079. int i, ret;
  1080. if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*((8*2+1+1)*4)/8
  1081. + FF_MIN_BUFFER_SIZE)) < 0)
  1082. return ret;
  1083. ff_init_range_encoder(c, pkt->data, pkt->size);
  1084. ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
  1085. *p = *pict;
  1086. p->pict_type= AV_PICTURE_TYPE_I;
  1087. if(avctx->gop_size==0 || f->picture_number % avctx->gop_size == 0){
  1088. put_rac(c, &keystate, 1);
  1089. p->key_frame= 1;
  1090. f->gob_count++;
  1091. write_header(f);
  1092. }else{
  1093. put_rac(c, &keystate, 0);
  1094. p->key_frame= 0;
  1095. }
  1096. if (f->ac>1){
  1097. int i;
  1098. for(i=1; i<256; i++){
  1099. c->one_state[i]= f->state_transition[i];
  1100. c->zero_state[256-i]= 256-c->one_state[i];
  1101. }
  1102. }
  1103. for(i=1; i<f->slice_count; i++){
  1104. FFV1Context *fs= f->slice_context[i];
  1105. uint8_t *start = pkt->data + (pkt->size-used_count)*i/f->slice_count;
  1106. int len = pkt->size/f->slice_count;
  1107. ff_init_range_encoder(&fs->c, start, len);
  1108. }
  1109. avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
  1110. buf_p = pkt->data;
  1111. for(i=0; i<f->slice_count; i++){
  1112. FFV1Context *fs= f->slice_context[i];
  1113. int bytes;
  1114. if(fs->ac){
  1115. uint8_t state=128;
  1116. put_rac(&fs->c, &state, 0);
  1117. bytes= ff_rac_terminate(&fs->c);
  1118. }else{
  1119. flush_put_bits(&fs->pb); //nicer padding FIXME
  1120. bytes= fs->ac_byte_count + (put_bits_count(&fs->pb)+7)/8;
  1121. }
  1122. if(i>0 || f->version>2){
  1123. av_assert0(bytes < pkt->size/f->slice_count);
  1124. memmove(buf_p, fs->c.bytestream_start, bytes);
  1125. av_assert0(bytes < (1<<24));
  1126. AV_WB24(buf_p+bytes, bytes);
  1127. bytes+=3;
  1128. }
  1129. if(f->ec){
  1130. unsigned v;
  1131. buf_p[bytes++] = 0;
  1132. v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, bytes);
  1133. AV_WL32(buf_p + bytes, v); bytes += 4;
  1134. }
  1135. buf_p += bytes;
  1136. }
  1137. if((avctx->flags&CODEC_FLAG_PASS1) && (f->picture_number&31)==0){
  1138. int j, k, m;
  1139. char *p= avctx->stats_out;
  1140. char *end= p + STATS_OUT_SIZE;
  1141. memset(f->rc_stat, 0, sizeof(f->rc_stat));
  1142. for(i=0; i<f->quant_table_count; i++)
  1143. memset(f->rc_stat2[i], 0, f->context_count[i]*sizeof(*f->rc_stat2[i]));
  1144. for(j=0; j<f->slice_count; j++){
  1145. FFV1Context *fs= f->slice_context[j];
  1146. for(i=0; i<256; i++){
  1147. f->rc_stat[i][0] += fs->rc_stat[i][0];
  1148. f->rc_stat[i][1] += fs->rc_stat[i][1];
  1149. }
  1150. for(i=0; i<f->quant_table_count; i++){
  1151. for(k=0; k<f->context_count[i]; k++){
  1152. for(m=0; m<32; m++){
  1153. f->rc_stat2[i][k][m][0] += fs->rc_stat2[i][k][m][0];
  1154. f->rc_stat2[i][k][m][1] += fs->rc_stat2[i][k][m][1];
  1155. }
  1156. }
  1157. }
  1158. }
  1159. for(j=0; j<256; j++){
  1160. snprintf(p, end-p, "%"PRIu64" %"PRIu64" ", f->rc_stat[j][0], f->rc_stat[j][1]);
  1161. p+= strlen(p);
  1162. }
  1163. snprintf(p, end-p, "\n");
  1164. for(i=0; i<f->quant_table_count; i++){
  1165. for(j=0; j<f->context_count[i]; j++){
  1166. for(m=0; m<32; m++){
  1167. snprintf(p, end-p, "%"PRIu64" %"PRIu64" ", f->rc_stat2[i][j][m][0], f->rc_stat2[i][j][m][1]);
  1168. p+= strlen(p);
  1169. }
  1170. }
  1171. }
  1172. snprintf(p, end-p, "%d\n", f->gob_count);
  1173. } else if(avctx->flags&CODEC_FLAG_PASS1)
  1174. avctx->stats_out[0] = '\0';
  1175. f->picture_number++;
  1176. pkt->size = buf_p - pkt->data;
  1177. pkt->flags |= AV_PKT_FLAG_KEY*p->key_frame;
  1178. *got_packet = 1;
  1179. return 0;
  1180. }
  1181. #endif /* CONFIG_FFV1_ENCODER */
  1182. static av_cold int common_end(AVCodecContext *avctx){
  1183. FFV1Context *s = avctx->priv_data;
  1184. int i, j;
  1185. if (avctx->codec->decode && s->picture.data[0])
  1186. avctx->release_buffer(avctx, &s->picture);
  1187. if (avctx->codec->decode && s->last_picture.data[0])
  1188. avctx->release_buffer(avctx, &s->last_picture);
  1189. for(j=0; j<s->slice_count; j++){
  1190. FFV1Context *fs= s->slice_context[j];
  1191. for(i=0; i<s->plane_count; i++){
  1192. PlaneContext *p= &fs->plane[i];
  1193. av_freep(&p->state);
  1194. av_freep(&p->vlc_state);
  1195. }
  1196. av_freep(&fs->sample_buffer);
  1197. }
  1198. av_freep(&avctx->stats_out);
  1199. for(j=0; j<s->quant_table_count; j++){
  1200. av_freep(&s->initial_states[j]);
  1201. for(i=0; i<s->slice_count; i++){
  1202. FFV1Context *sf= s->slice_context[i];
  1203. av_freep(&sf->rc_stat2[j]);
  1204. }
  1205. av_freep(&s->rc_stat2[j]);
  1206. }
  1207. for(i=0; i<s->slice_count; i++){
  1208. av_freep(&s->slice_context[i]);
  1209. }
  1210. return 0;
  1211. }
  1212. static av_always_inline void decode_line(FFV1Context *s, int w,
  1213. int16_t *sample[2],
  1214. int plane_index, int bits)
  1215. {
  1216. PlaneContext * const p= &s->plane[plane_index];
  1217. RangeCoder * const c= &s->c;
  1218. int x;
  1219. int run_count=0;
  1220. int run_mode=0;
  1221. int run_index= s->run_index;
  1222. for(x=0; x<w; x++){
  1223. int diff, context, sign;
  1224. context= get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
  1225. if(context < 0){
  1226. context= -context;
  1227. sign=1;
  1228. }else
  1229. sign=0;
  1230. av_assert2(context < p->context_count);
  1231. if(s->ac){
  1232. diff= get_symbol_inline(c, p->state[context], 1);
  1233. }else{
  1234. if(context == 0 && run_mode==0) run_mode=1;
  1235. if(run_mode){
  1236. if(run_count==0 && run_mode==1){
  1237. if(get_bits1(&s->gb)){
  1238. run_count = 1<<ff_log2_run[run_index];
  1239. if(x + run_count <= w) run_index++;
  1240. }else{
  1241. if(ff_log2_run[run_index]) run_count = get_bits(&s->gb, ff_log2_run[run_index]);
  1242. else run_count=0;
  1243. if(run_index) run_index--;
  1244. run_mode=2;
  1245. }
  1246. }
  1247. run_count--;
  1248. if(run_count < 0){
  1249. run_mode=0;
  1250. run_count=0;
  1251. diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
  1252. if(diff>=0) diff++;
  1253. }else
  1254. diff=0;
  1255. }else
  1256. diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
  1257. // printf("count:%d index:%d, mode:%d, x:%d y:%d pos:%d\n", run_count, run_index, run_mode, x, y, get_bits_count(&s->gb));
  1258. }
  1259. if(sign) diff= -diff;
  1260. sample[1][x]= (predict(sample[1] + x, sample[0] + x) + diff) & ((1<<bits)-1);
  1261. }
  1262. s->run_index= run_index;
  1263. }
  1264. static void decode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index){
  1265. int x, y;
  1266. int16_t *sample[2];
  1267. sample[0]=s->sample_buffer +3;
  1268. sample[1]=s->sample_buffer+w+6+3;
  1269. s->run_index=0;
  1270. memset(s->sample_buffer, 0, 2*(w+6)*sizeof(*s->sample_buffer));
  1271. for(y=0; y<h; y++){
  1272. int16_t *temp = sample[0]; //FIXME try a normal buffer
  1273. sample[0]= sample[1];
  1274. sample[1]= temp;
  1275. sample[1][-1]= sample[0][0 ];
  1276. sample[0][ w]= sample[0][w-1];
  1277. //{START_TIMER
  1278. if(s->avctx->bits_per_raw_sample <= 8){
  1279. decode_line(s, w, sample, plane_index, 8);
  1280. for(x=0; x<w; x++){
  1281. src[x + stride*y]= sample[1][x];
  1282. }
  1283. }else{
  1284. decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
  1285. if(s->packed_at_lsb){
  1286. for(x=0; x<w; x++){
  1287. ((uint16_t*)(src + stride*y))[x]= sample[1][x];
  1288. }
  1289. }else{
  1290. for(x=0; x<w; x++){
  1291. ((uint16_t*)(src + stride*y))[x]= sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
  1292. }
  1293. }
  1294. }
  1295. //STOP_TIMER("decode-line")}
  1296. }
  1297. }
  1298. static void decode_rgb_frame(FFV1Context *s, uint32_t *src, int w, int h, int stride){
  1299. int x, y, p;
  1300. int16_t *sample[4][2];
  1301. for(x=0; x<4; x++){
  1302. sample[x][0] = s->sample_buffer + x*2 *(w+6) + 3;
  1303. sample[x][1] = s->sample_buffer + (x*2+1)*(w+6) + 3;
  1304. }
  1305. s->run_index=0;
  1306. memset(s->sample_buffer, 0, 8*(w+6)*sizeof(*s->sample_buffer));
  1307. for(y=0; y<h; y++){
  1308. for(p=0; p<3 + s->transparency; p++){
  1309. int16_t *temp = sample[p][0]; //FIXME try a normal buffer
  1310. sample[p][0]= sample[p][1];
  1311. sample[p][1]= temp;
  1312. sample[p][1][-1]= sample[p][0][0 ];
  1313. sample[p][0][ w]= sample[p][0][w-1];
  1314. decode_line(s, w, sample[p], (p+1)/2, 9);
  1315. }
  1316. for(x=0; x<w; x++){
  1317. int g= sample[0][1][x];
  1318. int b= sample[1][1][x];
  1319. int r= sample[2][1][x];
  1320. int a= sample[3][1][x];
  1321. // assert(g>=0 && b>=0 && r>=0);
  1322. // assert(g<256 && b<512 && r<512);
  1323. b -= 0x100;
  1324. r -= 0x100;
  1325. g -= (b + r)>>2;
  1326. b += g;
  1327. r += g;
  1328. src[x + stride*y]= b + (g<<8) + (r<<16) + (a<<24);
  1329. }
  1330. }
  1331. }
  1332. static int decode_slice_header(FFV1Context *f, FFV1Context *fs){
  1333. RangeCoder *c = &fs->c;
  1334. uint8_t state[CONTEXT_SIZE];
  1335. unsigned ps, i, context_count;
  1336. memset(state, 128, sizeof(state));
  1337. av_assert0(f->version > 2);
  1338. fs->slice_x = get_symbol(c, state, 0) *f->width ;
  1339. fs->slice_y = get_symbol(c, state, 0) *f->height;
  1340. fs->slice_width =(get_symbol(c, state, 0)+1)*f->width + fs->slice_x;
  1341. fs->slice_height=(get_symbol(c, state, 0)+1)*f->height + fs->slice_y;
  1342. fs->slice_x /= f->num_h_slices;
  1343. fs->slice_y /= f->num_v_slices;
  1344. fs->slice_width = fs->slice_width /f->num_h_slices - fs->slice_x;
  1345. fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
  1346. if((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
  1347. return -1;
  1348. if( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width
  1349. || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
  1350. return -1;
  1351. for(i=0; i<f->plane_count; i++){
  1352. PlaneContext * const p= &fs->plane[i];
  1353. int idx=get_symbol(c, state, 0);
  1354. if(idx > (unsigned)f->quant_table_count){
  1355. av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
  1356. return -1;
  1357. }
  1358. p->quant_table_index= idx;
  1359. memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
  1360. context_count= f->context_count[idx];
  1361. if(p->context_count < context_count){
  1362. av_freep(&p->state);
  1363. av_freep(&p->vlc_state);
  1364. }
  1365. p->context_count= context_count;
  1366. }
  1367. ps = get_symbol(c, state, 0);
  1368. if(ps==1){
  1369. f->picture.interlaced_frame = 1;
  1370. f->picture.top_field_first = 1;
  1371. } else if(ps==2){
  1372. f->picture.interlaced_frame = 1;
  1373. f->picture.top_field_first = 0;
  1374. } else if(ps==3){
  1375. f->picture.interlaced_frame = 0;
  1376. }
  1377. f->picture.sample_aspect_ratio.num = get_symbol(c, state, 0);
  1378. f->picture.sample_aspect_ratio.den = get_symbol(c, state, 0);
  1379. return 0;
  1380. }
  1381. static int decode_slice(AVCodecContext *c, void *arg){
  1382. FFV1Context *fs= *(void**)arg;
  1383. FFV1Context *f= fs->avctx->priv_data;
  1384. int width, height, x, y;
  1385. const int ps= (c->bits_per_raw_sample>8)+1;
  1386. AVFrame * const p= &f->picture;
  1387. if(f->version > 2){
  1388. if(init_slice_state(f, fs) < 0)
  1389. return AVERROR(ENOMEM);
  1390. if(decode_slice_header(f, fs) < 0) {
  1391. fs->slice_damaged = 1;
  1392. return AVERROR_INVALIDDATA;
  1393. }
  1394. }
  1395. if(init_slice_state(f, fs) < 0)
  1396. return AVERROR(ENOMEM);
  1397. if(f->picture.key_frame)
  1398. clear_slice_state(f, fs);
  1399. width = fs->slice_width;
  1400. height= fs->slice_height;
  1401. x= fs->slice_x;
  1402. y= fs->slice_y;
  1403. if(!fs->ac){
  1404. fs->ac_byte_count = f->version > 2 || (!x&&!y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
  1405. init_get_bits(&fs->gb,
  1406. fs->c.bytestream_start + fs->ac_byte_count,
  1407. (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
  1408. }
  1409. av_assert1(width && height);
  1410. if(f->colorspace==0){
  1411. const int chroma_width = -((-width )>>f->chroma_h_shift);
  1412. const int chroma_height= -((-height)>>f->chroma_v_shift);
  1413. const int cx= x>>f->chroma_h_shift;
  1414. const int cy= y>>f->chroma_v_shift;
  1415. decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
  1416. if (f->chroma_planes){
  1417. decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
  1418. decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
  1419. }
  1420. if (fs->transparency)
  1421. decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
  1422. }else{
  1423. decode_rgb_frame(fs, (uint32_t*)p->data[0] + ps*x + y*(p->linesize[0]/4), width, height, p->linesize[0]/4);
  1424. }
  1425. if(fs->ac && f->version > 2) {
  1426. int v = fs->c.bytestream_end - fs->c.bytestream - 3 - 5*f->ec;
  1427. if(v != -1 && v!= 0) {
  1428. av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
  1429. fs->slice_damaged = 1;
  1430. }
  1431. }
  1432. emms_c();
  1433. return 0;
  1434. }
  1435. static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale){
  1436. int v;
  1437. int i=0;
  1438. uint8_t state[CONTEXT_SIZE];
  1439. memset(state, 128, sizeof(state));
  1440. for(v=0; i<128 ; v++){
  1441. unsigned len= get_symbol(c, state, 0) + 1;
  1442. if(len > 128 - i) return -1;
  1443. while(len--){
  1444. quant_table[i] = scale*v;
  1445. i++;
  1446. //printf("%2d ",v);
  1447. //if(i%16==0) printf("\n");
  1448. }
  1449. }
  1450. for(i=1; i<128; i++){
  1451. quant_table[256-i]= -quant_table[i];
  1452. }
  1453. quant_table[128]= -quant_table[127];
  1454. return 2*v - 1;
  1455. }
  1456. static int read_quant_tables(RangeCoder *c, int16_t quant_table[MAX_CONTEXT_INPUTS][256]){
  1457. int i;
  1458. int context_count=1;
  1459. for(i=0; i<5; i++){
  1460. context_count*= read_quant_table(c, quant_table[i], context_count);
  1461. if(context_count > 32768U){
  1462. return -1;
  1463. }
  1464. }
  1465. return (context_count+1)/2;
  1466. }
  1467. static int read_extra_header(FFV1Context *f){
  1468. RangeCoder * const c= &f->c;
  1469. uint8_t state[CONTEXT_SIZE];
  1470. int i, j, k;
  1471. uint8_t state2[32][CONTEXT_SIZE];
  1472. memset(state2, 128, sizeof(state2));
  1473. memset(state, 128, sizeof(state));
  1474. ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
  1475. ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
  1476. f->version= get_symbol(c, state, 0);
  1477. if(f->version > 2) {
  1478. c->bytestream_end -= 4;
  1479. f->minor_version= get_symbol(c, state, 0);
  1480. }
  1481. f->ac= f->avctx->coder_type= get_symbol(c, state, 0);
  1482. if(f->ac>1){
  1483. for(i=1; i<256; i++){
  1484. f->state_transition[i]= get_symbol(c, state, 1) + c->one_state[i];
  1485. }
  1486. }
  1487. f->colorspace= get_symbol(c, state, 0); //YUV cs type
  1488. f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
  1489. f->chroma_planes= get_rac(c, state);
  1490. f->chroma_h_shift= get_symbol(c, state, 0);
  1491. f->chroma_v_shift= get_symbol(c, state, 0);
  1492. f->transparency= get_rac(c, state);
  1493. f->plane_count= 2 + f->transparency;
  1494. f->num_h_slices= 1 + get_symbol(c, state, 0);
  1495. f->num_v_slices= 1 + get_symbol(c, state, 0);
  1496. if(f->num_h_slices > (unsigned)f->width || f->num_v_slices > (unsigned)f->height){
  1497. av_log(f->avctx, AV_LOG_ERROR, "too many slices\n");
  1498. return -1;
  1499. }
  1500. f->quant_table_count= get_symbol(c, state, 0);
  1501. if(f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
  1502. return -1;
  1503. for(i=0; i<f->quant_table_count; i++){
  1504. if((f->context_count[i]= read_quant_tables(c, f->quant_tables[i])) < 0){
  1505. av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
  1506. return -1;
  1507. }
  1508. }
  1509. if(allocate_initial_states(f) < 0)
  1510. return AVERROR(ENOMEM);
  1511. for(i=0; i<f->quant_table_count; i++){
  1512. if(get_rac(c, state)){
  1513. for(j=0; j<f->context_count[i]; j++){
  1514. for(k=0; k<CONTEXT_SIZE; k++){
  1515. int pred= j ? f->initial_states[i][j-1][k] : 128;
  1516. f->initial_states[i][j][k]= (pred+get_symbol(c, state2[k], 1))&0xFF;
  1517. }
  1518. }
  1519. }
  1520. }
  1521. if(f->version > 2){
  1522. f->ec = get_symbol(c, state, 0);
  1523. }
  1524. if(f->version > 2){
  1525. unsigned v;
  1526. v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
  1527. if(v){
  1528. av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
  1529. return AVERROR_INVALIDDATA;
  1530. }
  1531. }
  1532. return 0;
  1533. }
  1534. static int read_header(FFV1Context *f){
  1535. uint8_t state[CONTEXT_SIZE];
  1536. int i, j, context_count;
  1537. RangeCoder * const c= &f->slice_context[0]->c;
  1538. memset(state, 128, sizeof(state));
  1539. if(f->version < 2){
  1540. unsigned v= get_symbol(c, state, 0);
  1541. if(v >= 2){
  1542. av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
  1543. return AVERROR_INVALIDDATA;
  1544. }
  1545. f->version = v;
  1546. f->ac= f->avctx->coder_type= get_symbol(c, state, 0);
  1547. if(f->ac>1){
  1548. for(i=1; i<256; i++){
  1549. f->state_transition[i]= get_symbol(c, state, 1) + c->one_state[i];
  1550. }
  1551. }
  1552. f->colorspace= get_symbol(c, state, 0); //YUV cs type
  1553. if(f->version>0)
  1554. f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
  1555. f->chroma_planes= get_rac(c, state);
  1556. f->chroma_h_shift= get_symbol(c, state, 0);
  1557. f->chroma_v_shift= get_symbol(c, state, 0);
  1558. f->transparency= get_rac(c, state);
  1559. f->plane_count= 2 + f->transparency;
  1560. }
  1561. if(f->colorspace==0){
  1562. if(!f->transparency && !f->chroma_planes){
  1563. if (f->avctx->bits_per_raw_sample<=8)
  1564. f->avctx->pix_fmt= PIX_FMT_GRAY8;
  1565. else
  1566. f->avctx->pix_fmt= PIX_FMT_GRAY16;
  1567. }else if(f->avctx->bits_per_raw_sample<=8 && !f->transparency){
  1568. switch(16*f->chroma_h_shift + f->chroma_v_shift){
  1569. case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P; break;
  1570. case 0x01: f->avctx->pix_fmt= PIX_FMT_YUV440P; break;
  1571. case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P; break;
  1572. case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P; break;
  1573. case 0x20: f->avctx->pix_fmt= PIX_FMT_YUV411P; break;
  1574. case 0x22: f->avctx->pix_fmt= PIX_FMT_YUV410P; break;
  1575. default:
  1576. av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
  1577. return -1;
  1578. }
  1579. }else if(f->avctx->bits_per_raw_sample<=8 && f->transparency){
  1580. switch(16*f->chroma_h_shift + f->chroma_v_shift){
  1581. case 0x00: f->avctx->pix_fmt= PIX_FMT_YUVA444P; break;
  1582. case 0x10: f->avctx->pix_fmt= PIX_FMT_YUVA422P; break;
  1583. case 0x11: f->avctx->pix_fmt= PIX_FMT_YUVA420P; break;
  1584. default:
  1585. av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
  1586. return -1;
  1587. }
  1588. }else if(f->avctx->bits_per_raw_sample==9) {
  1589. f->packed_at_lsb=1;
  1590. switch(16*f->chroma_h_shift + f->chroma_v_shift){
  1591. case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P9; break;
  1592. case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P9; break;
  1593. case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P9; break;
  1594. default:
  1595. av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
  1596. return -1;
  1597. }
  1598. }else if(f->avctx->bits_per_raw_sample==10) {
  1599. f->packed_at_lsb=1;
  1600. switch(16*f->chroma_h_shift + f->chroma_v_shift){
  1601. case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P10; break;
  1602. case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P10; break;
  1603. case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P10; break;
  1604. default:
  1605. av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
  1606. return -1;
  1607. }
  1608. }else {
  1609. switch(16*f->chroma_h_shift + f->chroma_v_shift){
  1610. case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P16; break;
  1611. case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P16; break;
  1612. case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P16; break;
  1613. default:
  1614. av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
  1615. return -1;
  1616. }
  1617. }
  1618. }else if(f->colorspace==1){
  1619. if(f->chroma_h_shift || f->chroma_v_shift){
  1620. av_log(f->avctx, AV_LOG_ERROR, "chroma subsampling not supported in this colorspace\n");
  1621. return -1;
  1622. }
  1623. if(f->transparency) f->avctx->pix_fmt= PIX_FMT_RGB32;
  1624. else f->avctx->pix_fmt= PIX_FMT_0RGB32;
  1625. }else{
  1626. av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
  1627. return -1;
  1628. }
  1629. //printf("%d %d %d\n", f->chroma_h_shift, f->chroma_v_shift,f->avctx->pix_fmt);
  1630. if(f->version < 2){
  1631. context_count= read_quant_tables(c, f->quant_table);
  1632. if(context_count < 0){
  1633. av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
  1634. return -1;
  1635. }
  1636. }else if(f->version < 3){
  1637. f->slice_count= get_symbol(c, state, 0);
  1638. }else{
  1639. const uint8_t *p= c->bytestream_end;
  1640. for(f->slice_count = 0; f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start; f->slice_count++){
  1641. int trailer = 3 + 5*!!f->ec;
  1642. int size = AV_RB24(p-trailer);
  1643. if(size + trailer > p - c->bytestream_start)
  1644. break;
  1645. p -= size + trailer;
  1646. }
  1647. }
  1648. if(f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0){
  1649. av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
  1650. return -1;
  1651. }
  1652. for(j=0; j<f->slice_count; j++){
  1653. FFV1Context *fs= f->slice_context[j];
  1654. fs->ac= f->ac;
  1655. fs->packed_at_lsb= f->packed_at_lsb;
  1656. fs->slice_damaged = 0;
  1657. if(f->version == 2){
  1658. fs->slice_x = get_symbol(c, state, 0) *f->width ;
  1659. fs->slice_y = get_symbol(c, state, 0) *f->height;
  1660. fs->slice_width =(get_symbol(c, state, 0)+1)*f->width + fs->slice_x;
  1661. fs->slice_height=(get_symbol(c, state, 0)+1)*f->height + fs->slice_y;
  1662. fs->slice_x /= f->num_h_slices;
  1663. fs->slice_y /= f->num_v_slices;
  1664. fs->slice_width = fs->slice_width /f->num_h_slices - fs->slice_x;
  1665. fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
  1666. if((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
  1667. return -1;
  1668. if( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width
  1669. || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
  1670. return -1;
  1671. }
  1672. for(i=0; i<f->plane_count; i++){
  1673. PlaneContext * const p= &fs->plane[i];
  1674. if(f->version == 2){
  1675. int idx=get_symbol(c, state, 0);
  1676. if(idx > (unsigned)f->quant_table_count){
  1677. av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
  1678. return -1;
  1679. }
  1680. p->quant_table_index= idx;
  1681. memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
  1682. context_count= f->context_count[idx];
  1683. }else{
  1684. memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
  1685. }
  1686. if(f->version <= 2){
  1687. if(p->context_count < context_count){
  1688. av_freep(&p->state);
  1689. av_freep(&p->vlc_state);
  1690. }
  1691. p->context_count= context_count;
  1692. }
  1693. }
  1694. }
  1695. return 0;
  1696. }
  1697. static av_cold int decode_init(AVCodecContext *avctx)
  1698. {
  1699. FFV1Context *f = avctx->priv_data;
  1700. common_init(avctx);
  1701. if(avctx->extradata && read_extra_header(f) < 0)
  1702. return -1;
  1703. if(init_slice_contexts(f) < 0)
  1704. return -1;
  1705. return 0;
  1706. }
  1707. static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt){
  1708. const uint8_t *buf = avpkt->data;
  1709. int buf_size = avpkt->size;
  1710. FFV1Context *f = avctx->priv_data;
  1711. RangeCoder * const c= &f->slice_context[0]->c;
  1712. AVFrame * const p= &f->picture;
  1713. int i;
  1714. uint8_t keystate= 128;
  1715. const uint8_t *buf_p;
  1716. AVFrame *picture = data;
  1717. /* release previously stored data */
  1718. if (p->data[0])
  1719. avctx->release_buffer(avctx, p);
  1720. ff_init_range_decoder(c, buf, buf_size);
  1721. ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
  1722. p->pict_type= AV_PICTURE_TYPE_I; //FIXME I vs. P
  1723. if(get_rac(c, &keystate)){
  1724. p->key_frame= 1;
  1725. f->key_frame_ok = 0;
  1726. if(read_header(f) < 0)
  1727. return -1;
  1728. f->key_frame_ok = 1;
  1729. }else{
  1730. if (!f->key_frame_ok) {
  1731. av_log(avctx, AV_LOG_ERROR, "Cant decode non keyframe without valid keyframe\n");
  1732. return AVERROR_INVALIDDATA;
  1733. }
  1734. p->key_frame= 0;
  1735. }
  1736. p->reference= 3; //for error concealment
  1737. if(avctx->get_buffer(avctx, p) < 0){
  1738. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1739. return -1;
  1740. }
  1741. if(avctx->debug&FF_DEBUG_PICT_INFO)
  1742. av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d\n",
  1743. f->version, p->key_frame, f->ac, f->ec, f->slice_count);
  1744. buf_p= buf + buf_size;
  1745. for(i=f->slice_count-1; i>=0; i--){
  1746. FFV1Context *fs= f->slice_context[i];
  1747. int trailer = 3 + 5*!!f->ec;
  1748. int v;
  1749. if(i || f->version>2) v = AV_RB24(buf_p-trailer)+trailer;
  1750. else v = buf_p - c->bytestream_start;
  1751. if(buf_p - c->bytestream_start < v){
  1752. av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
  1753. return -1;
  1754. }
  1755. buf_p -= v;
  1756. if(f->ec){
  1757. unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
  1758. if(crc){
  1759. int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
  1760. av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
  1761. if(ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
  1762. av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n",ts*av_q2d(avctx->pkt_timebase));
  1763. } else if(ts != AV_NOPTS_VALUE) {
  1764. av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
  1765. } else {
  1766. av_log(f->avctx, AV_LOG_ERROR, "\n");
  1767. }
  1768. fs->slice_damaged = 1;
  1769. }
  1770. }
  1771. if(i){
  1772. ff_init_range_decoder(&fs->c, buf_p, v);
  1773. }else
  1774. fs->c.bytestream_end = (uint8_t *)(buf_p + v);
  1775. }
  1776. avctx->execute(avctx, decode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
  1777. for(i=f->slice_count-1; i>=0; i--){
  1778. FFV1Context *fs= f->slice_context[i];
  1779. int j;
  1780. if(fs->slice_damaged && f->last_picture.data[0]){
  1781. uint8_t *dst[4], *src[4];
  1782. for(j=0; j<4; j++){
  1783. int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
  1784. int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
  1785. dst[j] = f->picture .data[j] + f->picture .linesize[j]*
  1786. (fs->slice_y>>sv) + (fs->slice_x>>sh);
  1787. src[j] = f->last_picture.data[j] + f->last_picture.linesize[j]*
  1788. (fs->slice_y>>sv) + (fs->slice_x>>sh);
  1789. }
  1790. av_image_copy(dst, f->picture.linesize, (const uint8_t **)src, f->last_picture.linesize,
  1791. avctx->pix_fmt, fs->slice_width, fs->slice_height);
  1792. }
  1793. }
  1794. f->picture_number++;
  1795. *picture= *p;
  1796. *data_size = sizeof(AVFrame);
  1797. FFSWAP(AVFrame, f->picture, f->last_picture);
  1798. return buf_size;
  1799. }
  1800. AVCodec ff_ffv1_decoder = {
  1801. .name = "ffv1",
  1802. .type = AVMEDIA_TYPE_VIDEO,
  1803. .id = AV_CODEC_ID_FFV1,
  1804. .priv_data_size = sizeof(FFV1Context),
  1805. .init = decode_init,
  1806. .close = common_end,
  1807. .decode = decode_frame,
  1808. .capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
  1809. CODEC_CAP_SLICE_THREADS,
  1810. .long_name = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
  1811. };
  1812. #if CONFIG_FFV1_ENCODER
  1813. #define OFFSET(x) offsetof(FFV1Context, x)
  1814. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  1815. static const AVOption options[] = {
  1816. { "slicecrc", "Protect slices with CRCs", OFFSET(ec), AV_OPT_TYPE_INT, {-1}, -1, 1, VE},
  1817. {NULL}
  1818. };
  1819. static const AVClass class = {
  1820. .class_name = "ffv1 encoder",
  1821. .item_name = av_default_item_name,
  1822. .option = options,
  1823. .version = LIBAVUTIL_VERSION_INT,
  1824. };
  1825. static const AVCodecDefault ffv1_defaults[] = {
  1826. { "coder", "-1" },
  1827. { NULL },
  1828. };
  1829. AVCodec ff_ffv1_encoder = {
  1830. .name = "ffv1",
  1831. .type = AVMEDIA_TYPE_VIDEO,
  1832. .id = AV_CODEC_ID_FFV1,
  1833. .priv_data_size = sizeof(FFV1Context),
  1834. .init = encode_init,
  1835. .encode2 = encode_frame,
  1836. .close = common_end,
  1837. .capabilities = CODEC_CAP_SLICE_THREADS,
  1838. .defaults = ffv1_defaults,
  1839. .pix_fmts = (const enum PixelFormat[]){
  1840. PIX_FMT_YUV420P, PIX_FMT_YUVA420P, PIX_FMT_YUVA422P, PIX_FMT_YUV444P,
  1841. PIX_FMT_YUVA444P, PIX_FMT_YUV440P, PIX_FMT_YUV422P, PIX_FMT_YUV411P,
  1842. PIX_FMT_YUV410P, PIX_FMT_0RGB32, PIX_FMT_RGB32, PIX_FMT_YUV420P16,
  1843. PIX_FMT_YUV422P16, PIX_FMT_YUV444P16, PIX_FMT_YUV444P9, PIX_FMT_YUV422P9,
  1844. PIX_FMT_YUV420P9, PIX_FMT_YUV420P10, PIX_FMT_YUV422P10, PIX_FMT_YUV444P10,
  1845. PIX_FMT_GRAY16, PIX_FMT_GRAY8,
  1846. PIX_FMT_NONE
  1847. },
  1848. .long_name = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
  1849. .priv_class = &class,
  1850. };
  1851. #endif