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.

8079 lines
310KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file h264.c
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #include "dsputil.h"
  27. #include "avcodec.h"
  28. #include "mpegvideo.h"
  29. #include "h264.h"
  30. #include "h264data.h"
  31. #include "h264_parser.h"
  32. #include "golomb.h"
  33. #include "cabac.h"
  34. //#undef NDEBUG
  35. #include <assert.h>
  36. /**
  37. * Value of Picture.reference when Picture is not a reference picture, but
  38. * is held for delayed output.
  39. */
  40. #define DELAYED_PIC_REF 4
  41. static VLC coeff_token_vlc[4];
  42. static VLC chroma_dc_coeff_token_vlc;
  43. static VLC total_zeros_vlc[15];
  44. static VLC chroma_dc_total_zeros_vlc[3];
  45. static VLC run_vlc[6];
  46. static VLC run7_vlc;
  47. static void svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
  48. static void svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
  49. static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
  50. static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
  51. static av_always_inline uint32_t pack16to32(int a, int b){
  52. #ifdef WORDS_BIGENDIAN
  53. return (b&0xFFFF) + (a<<16);
  54. #else
  55. return (a&0xFFFF) + (b<<16);
  56. #endif
  57. }
  58. const uint8_t ff_rem6[52]={
  59. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
  60. };
  61. const uint8_t ff_div6[52]={
  62. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  63. };
  64. /**
  65. * fill a rectangle.
  66. * @param h height of the rectangle, should be a constant
  67. * @param w width of the rectangle, should be a constant
  68. * @param size the size of val (1 or 4), should be a constant
  69. */
  70. static av_always_inline void fill_rectangle(void *vp, int w, int h, int stride, uint32_t val, int size){
  71. uint8_t *p= (uint8_t*)vp;
  72. assert(size==1 || size==4);
  73. assert(w<=4);
  74. w *= size;
  75. stride *= size;
  76. assert((((long)vp)&(FFMIN(w, STRIDE_ALIGN)-1)) == 0);
  77. assert((stride&(w-1))==0);
  78. if(w==2){
  79. const uint16_t v= size==4 ? val : val*0x0101;
  80. *(uint16_t*)(p + 0*stride)= v;
  81. if(h==1) return;
  82. *(uint16_t*)(p + 1*stride)= v;
  83. if(h==2) return;
  84. *(uint16_t*)(p + 2*stride)= v;
  85. *(uint16_t*)(p + 3*stride)= v;
  86. }else if(w==4){
  87. const uint32_t v= size==4 ? val : val*0x01010101;
  88. *(uint32_t*)(p + 0*stride)= v;
  89. if(h==1) return;
  90. *(uint32_t*)(p + 1*stride)= v;
  91. if(h==2) return;
  92. *(uint32_t*)(p + 2*stride)= v;
  93. *(uint32_t*)(p + 3*stride)= v;
  94. }else if(w==8){
  95. //gcc can't optimize 64bit math on x86_32
  96. #if defined(ARCH_X86_64) || (defined(MP_WORDSIZE) && MP_WORDSIZE >= 64)
  97. const uint64_t v= val*0x0100000001ULL;
  98. *(uint64_t*)(p + 0*stride)= v;
  99. if(h==1) return;
  100. *(uint64_t*)(p + 1*stride)= v;
  101. if(h==2) return;
  102. *(uint64_t*)(p + 2*stride)= v;
  103. *(uint64_t*)(p + 3*stride)= v;
  104. }else if(w==16){
  105. const uint64_t v= val*0x0100000001ULL;
  106. *(uint64_t*)(p + 0+0*stride)= v;
  107. *(uint64_t*)(p + 8+0*stride)= v;
  108. *(uint64_t*)(p + 0+1*stride)= v;
  109. *(uint64_t*)(p + 8+1*stride)= v;
  110. if(h==2) return;
  111. *(uint64_t*)(p + 0+2*stride)= v;
  112. *(uint64_t*)(p + 8+2*stride)= v;
  113. *(uint64_t*)(p + 0+3*stride)= v;
  114. *(uint64_t*)(p + 8+3*stride)= v;
  115. #else
  116. *(uint32_t*)(p + 0+0*stride)= val;
  117. *(uint32_t*)(p + 4+0*stride)= val;
  118. if(h==1) return;
  119. *(uint32_t*)(p + 0+1*stride)= val;
  120. *(uint32_t*)(p + 4+1*stride)= val;
  121. if(h==2) return;
  122. *(uint32_t*)(p + 0+2*stride)= val;
  123. *(uint32_t*)(p + 4+2*stride)= val;
  124. *(uint32_t*)(p + 0+3*stride)= val;
  125. *(uint32_t*)(p + 4+3*stride)= val;
  126. }else if(w==16){
  127. *(uint32_t*)(p + 0+0*stride)= val;
  128. *(uint32_t*)(p + 4+0*stride)= val;
  129. *(uint32_t*)(p + 8+0*stride)= val;
  130. *(uint32_t*)(p +12+0*stride)= val;
  131. *(uint32_t*)(p + 0+1*stride)= val;
  132. *(uint32_t*)(p + 4+1*stride)= val;
  133. *(uint32_t*)(p + 8+1*stride)= val;
  134. *(uint32_t*)(p +12+1*stride)= val;
  135. if(h==2) return;
  136. *(uint32_t*)(p + 0+2*stride)= val;
  137. *(uint32_t*)(p + 4+2*stride)= val;
  138. *(uint32_t*)(p + 8+2*stride)= val;
  139. *(uint32_t*)(p +12+2*stride)= val;
  140. *(uint32_t*)(p + 0+3*stride)= val;
  141. *(uint32_t*)(p + 4+3*stride)= val;
  142. *(uint32_t*)(p + 8+3*stride)= val;
  143. *(uint32_t*)(p +12+3*stride)= val;
  144. #endif
  145. }else
  146. assert(0);
  147. assert(h==4);
  148. }
  149. static void fill_caches(H264Context *h, int mb_type, int for_deblock){
  150. MpegEncContext * const s = &h->s;
  151. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  152. int topleft_xy, top_xy, topright_xy, left_xy[2];
  153. int topleft_type, top_type, topright_type, left_type[2];
  154. int left_block[8];
  155. int i;
  156. //FIXME deblocking could skip the intra and nnz parts.
  157. if(for_deblock && (h->slice_num == 1 || h->slice_table[mb_xy] == h->slice_table[mb_xy-s->mb_stride]) && !FRAME_MBAFF)
  158. return;
  159. //wow what a mess, why didn't they simplify the interlacing&intra stuff, i can't imagine that these complex rules are worth it
  160. top_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
  161. topleft_xy = top_xy - 1;
  162. topright_xy= top_xy + 1;
  163. left_xy[1] = left_xy[0] = mb_xy-1;
  164. left_block[0]= 0;
  165. left_block[1]= 1;
  166. left_block[2]= 2;
  167. left_block[3]= 3;
  168. left_block[4]= 7;
  169. left_block[5]= 10;
  170. left_block[6]= 8;
  171. left_block[7]= 11;
  172. if(FRAME_MBAFF){
  173. const int pair_xy = s->mb_x + (s->mb_y & ~1)*s->mb_stride;
  174. const int top_pair_xy = pair_xy - s->mb_stride;
  175. const int topleft_pair_xy = top_pair_xy - 1;
  176. const int topright_pair_xy = top_pair_xy + 1;
  177. const int topleft_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topleft_pair_xy]);
  178. const int top_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
  179. const int topright_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topright_pair_xy]);
  180. const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
  181. const int curr_mb_frame_flag = !IS_INTERLACED(mb_type);
  182. const int bottom = (s->mb_y & 1);
  183. tprintf(s->avctx, "fill_caches: curr_mb_frame_flag:%d, left_mb_frame_flag:%d, topleft_mb_frame_flag:%d, top_mb_frame_flag:%d, topright_mb_frame_flag:%d\n", curr_mb_frame_flag, left_mb_frame_flag, topleft_mb_frame_flag, top_mb_frame_flag, topright_mb_frame_flag);
  184. if (bottom
  185. ? !curr_mb_frame_flag // bottom macroblock
  186. : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
  187. ) {
  188. top_xy -= s->mb_stride;
  189. }
  190. if (bottom
  191. ? !curr_mb_frame_flag // bottom macroblock
  192. : (!curr_mb_frame_flag && !topleft_mb_frame_flag) // top macroblock
  193. ) {
  194. topleft_xy -= s->mb_stride;
  195. }
  196. if (bottom
  197. ? !curr_mb_frame_flag // bottom macroblock
  198. : (!curr_mb_frame_flag && !topright_mb_frame_flag) // top macroblock
  199. ) {
  200. topright_xy -= s->mb_stride;
  201. }
  202. if (left_mb_frame_flag != curr_mb_frame_flag) {
  203. left_xy[1] = left_xy[0] = pair_xy - 1;
  204. if (curr_mb_frame_flag) {
  205. if (bottom) {
  206. left_block[0]= 2;
  207. left_block[1]= 2;
  208. left_block[2]= 3;
  209. left_block[3]= 3;
  210. left_block[4]= 8;
  211. left_block[5]= 11;
  212. left_block[6]= 8;
  213. left_block[7]= 11;
  214. } else {
  215. left_block[0]= 0;
  216. left_block[1]= 0;
  217. left_block[2]= 1;
  218. left_block[3]= 1;
  219. left_block[4]= 7;
  220. left_block[5]= 10;
  221. left_block[6]= 7;
  222. left_block[7]= 10;
  223. }
  224. } else {
  225. left_xy[1] += s->mb_stride;
  226. //left_block[0]= 0;
  227. left_block[1]= 2;
  228. left_block[2]= 0;
  229. left_block[3]= 2;
  230. //left_block[4]= 7;
  231. left_block[5]= 10;
  232. left_block[6]= 7;
  233. left_block[7]= 10;
  234. }
  235. }
  236. }
  237. h->top_mb_xy = top_xy;
  238. h->left_mb_xy[0] = left_xy[0];
  239. h->left_mb_xy[1] = left_xy[1];
  240. if(for_deblock){
  241. topleft_type = 0;
  242. topright_type = 0;
  243. top_type = h->slice_table[top_xy ] < 255 ? s->current_picture.mb_type[top_xy] : 0;
  244. left_type[0] = h->slice_table[left_xy[0] ] < 255 ? s->current_picture.mb_type[left_xy[0]] : 0;
  245. left_type[1] = h->slice_table[left_xy[1] ] < 255 ? s->current_picture.mb_type[left_xy[1]] : 0;
  246. if(FRAME_MBAFF && !IS_INTRA(mb_type)){
  247. int list;
  248. int v = *(uint16_t*)&h->non_zero_count[mb_xy][14];
  249. for(i=0; i<16; i++)
  250. h->non_zero_count_cache[scan8[i]] = (v>>i)&1;
  251. for(list=0; list<h->list_count; list++){
  252. if(USES_LIST(mb_type,list)){
  253. uint32_t *src = (uint32_t*)s->current_picture.motion_val[list][h->mb2b_xy[mb_xy]];
  254. uint32_t *dst = (uint32_t*)h->mv_cache[list][scan8[0]];
  255. int8_t *ref = &s->current_picture.ref_index[list][h->mb2b8_xy[mb_xy]];
  256. for(i=0; i<4; i++, dst+=8, src+=h->b_stride){
  257. dst[0] = src[0];
  258. dst[1] = src[1];
  259. dst[2] = src[2];
  260. dst[3] = src[3];
  261. }
  262. *(uint32_t*)&h->ref_cache[list][scan8[ 0]] =
  263. *(uint32_t*)&h->ref_cache[list][scan8[ 2]] = pack16to32(ref[0],ref[1])*0x0101;
  264. ref += h->b8_stride;
  265. *(uint32_t*)&h->ref_cache[list][scan8[ 8]] =
  266. *(uint32_t*)&h->ref_cache[list][scan8[10]] = pack16to32(ref[0],ref[1])*0x0101;
  267. }else{
  268. fill_rectangle(&h-> mv_cache[list][scan8[ 0]], 4, 4, 8, 0, 4);
  269. fill_rectangle(&h->ref_cache[list][scan8[ 0]], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1);
  270. }
  271. }
  272. }
  273. }else{
  274. topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;
  275. top_type = h->slice_table[top_xy ] == h->slice_num ? s->current_picture.mb_type[top_xy] : 0;
  276. topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;
  277. left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;
  278. left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;
  279. }
  280. if(IS_INTRA(mb_type)){
  281. h->topleft_samples_available=
  282. h->top_samples_available=
  283. h->left_samples_available= 0xFFFF;
  284. h->topright_samples_available= 0xEEEA;
  285. if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){
  286. h->topleft_samples_available= 0xB3FF;
  287. h->top_samples_available= 0x33FF;
  288. h->topright_samples_available= 0x26EA;
  289. }
  290. for(i=0; i<2; i++){
  291. if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){
  292. h->topleft_samples_available&= 0xDF5F;
  293. h->left_samples_available&= 0x5F5F;
  294. }
  295. }
  296. if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))
  297. h->topleft_samples_available&= 0x7FFF;
  298. if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))
  299. h->topright_samples_available&= 0xFBFF;
  300. if(IS_INTRA4x4(mb_type)){
  301. if(IS_INTRA4x4(top_type)){
  302. h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];
  303. h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];
  304. h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];
  305. h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];
  306. }else{
  307. int pred;
  308. if(!top_type || (IS_INTER(top_type) && h->pps.constrained_intra_pred))
  309. pred= -1;
  310. else{
  311. pred= 2;
  312. }
  313. h->intra4x4_pred_mode_cache[4+8*0]=
  314. h->intra4x4_pred_mode_cache[5+8*0]=
  315. h->intra4x4_pred_mode_cache[6+8*0]=
  316. h->intra4x4_pred_mode_cache[7+8*0]= pred;
  317. }
  318. for(i=0; i<2; i++){
  319. if(IS_INTRA4x4(left_type[i])){
  320. h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];
  321. h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];
  322. }else{
  323. int pred;
  324. if(!left_type[i] || (IS_INTER(left_type[i]) && h->pps.constrained_intra_pred))
  325. pred= -1;
  326. else{
  327. pred= 2;
  328. }
  329. h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=
  330. h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;
  331. }
  332. }
  333. }
  334. }
  335. /*
  336. 0 . T T. T T T T
  337. 1 L . .L . . . .
  338. 2 L . .L . . . .
  339. 3 . T TL . . . .
  340. 4 L . .L . . . .
  341. 5 L . .. . . . .
  342. */
  343. //FIXME constraint_intra_pred & partitioning & nnz (lets hope this is just a typo in the spec)
  344. if(top_type){
  345. h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][4];
  346. h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][5];
  347. h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][6];
  348. h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];
  349. h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][9];
  350. h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];
  351. h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][12];
  352. h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];
  353. }else{
  354. h->non_zero_count_cache[4+8*0]=
  355. h->non_zero_count_cache[5+8*0]=
  356. h->non_zero_count_cache[6+8*0]=
  357. h->non_zero_count_cache[7+8*0]=
  358. h->non_zero_count_cache[1+8*0]=
  359. h->non_zero_count_cache[2+8*0]=
  360. h->non_zero_count_cache[1+8*3]=
  361. h->non_zero_count_cache[2+8*3]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
  362. }
  363. for (i=0; i<2; i++) {
  364. if(left_type[i]){
  365. h->non_zero_count_cache[3+8*1 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[0+2*i]];
  366. h->non_zero_count_cache[3+8*2 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[1+2*i]];
  367. h->non_zero_count_cache[0+8*1 + 8*i]= h->non_zero_count[left_xy[i]][left_block[4+2*i]];
  368. h->non_zero_count_cache[0+8*4 + 8*i]= h->non_zero_count[left_xy[i]][left_block[5+2*i]];
  369. }else{
  370. h->non_zero_count_cache[3+8*1 + 2*8*i]=
  371. h->non_zero_count_cache[3+8*2 + 2*8*i]=
  372. h->non_zero_count_cache[0+8*1 + 8*i]=
  373. h->non_zero_count_cache[0+8*4 + 8*i]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
  374. }
  375. }
  376. if( h->pps.cabac ) {
  377. // top_cbp
  378. if(top_type) {
  379. h->top_cbp = h->cbp_table[top_xy];
  380. } else if(IS_INTRA(mb_type)) {
  381. h->top_cbp = 0x1C0;
  382. } else {
  383. h->top_cbp = 0;
  384. }
  385. // left_cbp
  386. if (left_type[0]) {
  387. h->left_cbp = h->cbp_table[left_xy[0]] & 0x1f0;
  388. } else if(IS_INTRA(mb_type)) {
  389. h->left_cbp = 0x1C0;
  390. } else {
  391. h->left_cbp = 0;
  392. }
  393. if (left_type[0]) {
  394. h->left_cbp |= ((h->cbp_table[left_xy[0]]>>((left_block[0]&(~1))+1))&0x1) << 1;
  395. }
  396. if (left_type[1]) {
  397. h->left_cbp |= ((h->cbp_table[left_xy[1]]>>((left_block[2]&(~1))+1))&0x1) << 3;
  398. }
  399. }
  400. #if 1
  401. if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
  402. int list;
  403. for(list=0; list<h->list_count; list++){
  404. if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !h->deblocking_filter){
  405. /*if(!h->mv_cache_clean[list]){
  406. memset(h->mv_cache [list], 0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?
  407. memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));
  408. h->mv_cache_clean[list]= 1;
  409. }*/
  410. continue;
  411. }
  412. h->mv_cache_clean[list]= 0;
  413. if(USES_LIST(top_type, list)){
  414. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  415. const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;
  416. *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];
  417. *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];
  418. *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];
  419. *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];
  420. h->ref_cache[list][scan8[0] + 0 - 1*8]=
  421. h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];
  422. h->ref_cache[list][scan8[0] + 2 - 1*8]=
  423. h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];
  424. }else{
  425. *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]=
  426. *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]=
  427. *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]=
  428. *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;
  429. *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;
  430. }
  431. for(i=0; i<2; i++){
  432. int cache_idx = scan8[0] - 1 + i*2*8;
  433. if(USES_LIST(left_type[i], list)){
  434. const int b_xy= h->mb2b_xy[left_xy[i]] + 3;
  435. const int b8_xy= h->mb2b8_xy[left_xy[i]] + 1;
  436. *(uint32_t*)h->mv_cache[list][cache_idx ]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[0+i*2]];
  437. *(uint32_t*)h->mv_cache[list][cache_idx+8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[1+i*2]];
  438. h->ref_cache[list][cache_idx ]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0+i*2]>>1)];
  439. h->ref_cache[list][cache_idx+8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[1+i*2]>>1)];
  440. }else{
  441. *(uint32_t*)h->mv_cache [list][cache_idx ]=
  442. *(uint32_t*)h->mv_cache [list][cache_idx+8]= 0;
  443. h->ref_cache[list][cache_idx ]=
  444. h->ref_cache[list][cache_idx+8]= left_type[i] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
  445. }
  446. }
  447. if((for_deblock || (IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred)) && !FRAME_MBAFF)
  448. continue;
  449. if(USES_LIST(topleft_type, list)){
  450. const int b_xy = h->mb2b_xy[topleft_xy] + 3 + 3*h->b_stride;
  451. const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + h->b8_stride;
  452. *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
  453. h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];
  454. }else{
  455. *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;
  456. h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
  457. }
  458. if(USES_LIST(topright_type, list)){
  459. const int b_xy= h->mb2b_xy[topright_xy] + 3*h->b_stride;
  460. const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;
  461. *(uint32_t*)h->mv_cache[list][scan8[0] + 4 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
  462. h->ref_cache[list][scan8[0] + 4 - 1*8]= s->current_picture.ref_index[list][b8_xy];
  463. }else{
  464. *(uint32_t*)h->mv_cache [list][scan8[0] + 4 - 1*8]= 0;
  465. h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
  466. }
  467. if((IS_SKIP(mb_type) || IS_DIRECT(mb_type)) && !FRAME_MBAFF)
  468. continue;
  469. h->ref_cache[list][scan8[5 ]+1] =
  470. h->ref_cache[list][scan8[7 ]+1] =
  471. h->ref_cache[list][scan8[13]+1] = //FIXME remove past 3 (init somewhere else)
  472. h->ref_cache[list][scan8[4 ]] =
  473. h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;
  474. *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=
  475. *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=
  476. *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
  477. *(uint32_t*)h->mv_cache [list][scan8[4 ]]=
  478. *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;
  479. if( h->pps.cabac ) {
  480. /* XXX beurk, Load mvd */
  481. if(USES_LIST(top_type, list)){
  482. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  483. *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];
  484. *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];
  485. *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];
  486. *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];
  487. }else{
  488. *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]=
  489. *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]=
  490. *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]=
  491. *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;
  492. }
  493. if(USES_LIST(left_type[0], list)){
  494. const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
  495. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[0]];
  496. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[1]];
  497. }else{
  498. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=
  499. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;
  500. }
  501. if(USES_LIST(left_type[1], list)){
  502. const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
  503. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[2]];
  504. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[3]];
  505. }else{
  506. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=
  507. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;
  508. }
  509. *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=
  510. *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=
  511. *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
  512. *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=
  513. *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;
  514. if(h->slice_type == B_TYPE){
  515. fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);
  516. if(IS_DIRECT(top_type)){
  517. *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;
  518. }else if(IS_8X8(top_type)){
  519. int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;
  520. h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];
  521. h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];
  522. }else{
  523. *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;
  524. }
  525. if(IS_DIRECT(left_type[0]))
  526. h->direct_cache[scan8[0] - 1 + 0*8]= 1;
  527. else if(IS_8X8(left_type[0]))
  528. h->direct_cache[scan8[0] - 1 + 0*8]= h->direct_table[h->mb2b8_xy[left_xy[0]] + 1 + h->b8_stride*(left_block[0]>>1)];
  529. else
  530. h->direct_cache[scan8[0] - 1 + 0*8]= 0;
  531. if(IS_DIRECT(left_type[1]))
  532. h->direct_cache[scan8[0] - 1 + 2*8]= 1;
  533. else if(IS_8X8(left_type[1]))
  534. h->direct_cache[scan8[0] - 1 + 2*8]= h->direct_table[h->mb2b8_xy[left_xy[1]] + 1 + h->b8_stride*(left_block[2]>>1)];
  535. else
  536. h->direct_cache[scan8[0] - 1 + 2*8]= 0;
  537. }
  538. }
  539. if(FRAME_MBAFF){
  540. #define MAP_MVS\
  541. MAP_F2F(scan8[0] - 1 - 1*8, topleft_type)\
  542. MAP_F2F(scan8[0] + 0 - 1*8, top_type)\
  543. MAP_F2F(scan8[0] + 1 - 1*8, top_type)\
  544. MAP_F2F(scan8[0] + 2 - 1*8, top_type)\
  545. MAP_F2F(scan8[0] + 3 - 1*8, top_type)\
  546. MAP_F2F(scan8[0] + 4 - 1*8, topright_type)\
  547. MAP_F2F(scan8[0] - 1 + 0*8, left_type[0])\
  548. MAP_F2F(scan8[0] - 1 + 1*8, left_type[0])\
  549. MAP_F2F(scan8[0] - 1 + 2*8, left_type[1])\
  550. MAP_F2F(scan8[0] - 1 + 3*8, left_type[1])
  551. if(MB_FIELD){
  552. #define MAP_F2F(idx, mb_type)\
  553. if(!IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
  554. h->ref_cache[list][idx] <<= 1;\
  555. h->mv_cache[list][idx][1] /= 2;\
  556. h->mvd_cache[list][idx][1] /= 2;\
  557. }
  558. MAP_MVS
  559. #undef MAP_F2F
  560. }else{
  561. #define MAP_F2F(idx, mb_type)\
  562. if(IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
  563. h->ref_cache[list][idx] >>= 1;\
  564. h->mv_cache[list][idx][1] <<= 1;\
  565. h->mvd_cache[list][idx][1] <<= 1;\
  566. }
  567. MAP_MVS
  568. #undef MAP_F2F
  569. }
  570. }
  571. }
  572. }
  573. #endif
  574. h->neighbor_transform_size= !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[0]);
  575. }
  576. static inline void write_back_intra_pred_mode(H264Context *h){
  577. MpegEncContext * const s = &h->s;
  578. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  579. h->intra4x4_pred_mode[mb_xy][0]= h->intra4x4_pred_mode_cache[7+8*1];
  580. h->intra4x4_pred_mode[mb_xy][1]= h->intra4x4_pred_mode_cache[7+8*2];
  581. h->intra4x4_pred_mode[mb_xy][2]= h->intra4x4_pred_mode_cache[7+8*3];
  582. h->intra4x4_pred_mode[mb_xy][3]= h->intra4x4_pred_mode_cache[7+8*4];
  583. h->intra4x4_pred_mode[mb_xy][4]= h->intra4x4_pred_mode_cache[4+8*4];
  584. h->intra4x4_pred_mode[mb_xy][5]= h->intra4x4_pred_mode_cache[5+8*4];
  585. h->intra4x4_pred_mode[mb_xy][6]= h->intra4x4_pred_mode_cache[6+8*4];
  586. }
  587. /**
  588. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  589. */
  590. static inline int check_intra4x4_pred_mode(H264Context *h){
  591. MpegEncContext * const s = &h->s;
  592. static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
  593. static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
  594. int i;
  595. if(!(h->top_samples_available&0x8000)){
  596. for(i=0; i<4; i++){
  597. int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
  598. if(status<0){
  599. av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
  600. return -1;
  601. } else if(status){
  602. h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
  603. }
  604. }
  605. }
  606. if(!(h->left_samples_available&0x8000)){
  607. for(i=0; i<4; i++){
  608. int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
  609. if(status<0){
  610. av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
  611. return -1;
  612. } else if(status){
  613. h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
  614. }
  615. }
  616. }
  617. return 0;
  618. } //FIXME cleanup like next
  619. /**
  620. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  621. */
  622. static inline int check_intra_pred_mode(H264Context *h, int mode){
  623. MpegEncContext * const s = &h->s;
  624. static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
  625. static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
  626. if(mode > 6U) {
  627. av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);
  628. return -1;
  629. }
  630. if(!(h->top_samples_available&0x8000)){
  631. mode= top[ mode ];
  632. if(mode<0){
  633. av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
  634. return -1;
  635. }
  636. }
  637. if(!(h->left_samples_available&0x8000)){
  638. mode= left[ mode ];
  639. if(mode<0){
  640. av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
  641. return -1;
  642. }
  643. }
  644. return mode;
  645. }
  646. /**
  647. * gets the predicted intra4x4 prediction mode.
  648. */
  649. static inline int pred_intra_mode(H264Context *h, int n){
  650. const int index8= scan8[n];
  651. const int left= h->intra4x4_pred_mode_cache[index8 - 1];
  652. const int top = h->intra4x4_pred_mode_cache[index8 - 8];
  653. const int min= FFMIN(left, top);
  654. tprintf(h->s.avctx, "mode:%d %d min:%d\n", left ,top, min);
  655. if(min<0) return DC_PRED;
  656. else return min;
  657. }
  658. static inline void write_back_non_zero_count(H264Context *h){
  659. MpegEncContext * const s = &h->s;
  660. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  661. h->non_zero_count[mb_xy][0]= h->non_zero_count_cache[7+8*1];
  662. h->non_zero_count[mb_xy][1]= h->non_zero_count_cache[7+8*2];
  663. h->non_zero_count[mb_xy][2]= h->non_zero_count_cache[7+8*3];
  664. h->non_zero_count[mb_xy][3]= h->non_zero_count_cache[7+8*4];
  665. h->non_zero_count[mb_xy][4]= h->non_zero_count_cache[4+8*4];
  666. h->non_zero_count[mb_xy][5]= h->non_zero_count_cache[5+8*4];
  667. h->non_zero_count[mb_xy][6]= h->non_zero_count_cache[6+8*4];
  668. h->non_zero_count[mb_xy][9]= h->non_zero_count_cache[1+8*2];
  669. h->non_zero_count[mb_xy][8]= h->non_zero_count_cache[2+8*2];
  670. h->non_zero_count[mb_xy][7]= h->non_zero_count_cache[2+8*1];
  671. h->non_zero_count[mb_xy][12]=h->non_zero_count_cache[1+8*5];
  672. h->non_zero_count[mb_xy][11]=h->non_zero_count_cache[2+8*5];
  673. h->non_zero_count[mb_xy][10]=h->non_zero_count_cache[2+8*4];
  674. if(FRAME_MBAFF){
  675. // store all luma nnzs, for deblocking
  676. int v = 0, i;
  677. for(i=0; i<16; i++)
  678. v += (!!h->non_zero_count_cache[scan8[i]]) << i;
  679. *(uint16_t*)&h->non_zero_count[mb_xy][14] = v;
  680. }
  681. }
  682. /**
  683. * gets the predicted number of non zero coefficients.
  684. * @param n block index
  685. */
  686. static inline int pred_non_zero_count(H264Context *h, int n){
  687. const int index8= scan8[n];
  688. const int left= h->non_zero_count_cache[index8 - 1];
  689. const int top = h->non_zero_count_cache[index8 - 8];
  690. int i= left + top;
  691. if(i<64) i= (i+1)>>1;
  692. tprintf(h->s.avctx, "pred_nnz L%X T%X n%d s%d P%X\n", left, top, n, scan8[n], i&31);
  693. return i&31;
  694. }
  695. static inline int fetch_diagonal_mv(H264Context *h, const int16_t **C, int i, int list, int part_width){
  696. const int topright_ref= h->ref_cache[list][ i - 8 + part_width ];
  697. MpegEncContext *s = &h->s;
  698. /* there is no consistent mapping of mvs to neighboring locations that will
  699. * make mbaff happy, so we can't move all this logic to fill_caches */
  700. if(FRAME_MBAFF){
  701. const uint32_t *mb_types = s->current_picture_ptr->mb_type;
  702. const int16_t *mv;
  703. *(uint32_t*)h->mv_cache[list][scan8[0]-2] = 0;
  704. *C = h->mv_cache[list][scan8[0]-2];
  705. if(!MB_FIELD
  706. && (s->mb_y&1) && i < scan8[0]+8 && topright_ref != PART_NOT_AVAILABLE){
  707. int topright_xy = s->mb_x + (s->mb_y-1)*s->mb_stride + (i == scan8[0]+3);
  708. if(IS_INTERLACED(mb_types[topright_xy])){
  709. #define SET_DIAG_MV(MV_OP, REF_OP, X4, Y4)\
  710. const int x4 = X4, y4 = Y4;\
  711. const int mb_type = mb_types[(x4>>2)+(y4>>2)*s->mb_stride];\
  712. if(!USES_LIST(mb_type,list) && !IS_8X8(mb_type))\
  713. return LIST_NOT_USED;\
  714. mv = s->current_picture_ptr->motion_val[list][x4 + y4*h->b_stride];\
  715. h->mv_cache[list][scan8[0]-2][0] = mv[0];\
  716. h->mv_cache[list][scan8[0]-2][1] = mv[1] MV_OP;\
  717. return s->current_picture_ptr->ref_index[list][(x4>>1) + (y4>>1)*h->b8_stride] REF_OP;
  718. SET_DIAG_MV(*2, >>1, s->mb_x*4+(i&7)-4+part_width, s->mb_y*4-1);
  719. }
  720. }
  721. if(topright_ref == PART_NOT_AVAILABLE
  722. && ((s->mb_y&1) || i >= scan8[0]+8) && (i&7)==4
  723. && h->ref_cache[list][scan8[0]-1] != PART_NOT_AVAILABLE){
  724. if(!MB_FIELD
  725. && IS_INTERLACED(mb_types[h->left_mb_xy[0]])){
  726. SET_DIAG_MV(*2, >>1, s->mb_x*4-1, (s->mb_y|1)*4+(s->mb_y&1)*2+(i>>4)-1);
  727. }
  728. if(MB_FIELD
  729. && !IS_INTERLACED(mb_types[h->left_mb_xy[0]])
  730. && i >= scan8[0]+8){
  731. // leftshift will turn LIST_NOT_USED into PART_NOT_AVAILABLE, but that's ok.
  732. SET_DIAG_MV(>>1, <<1, s->mb_x*4-1, (s->mb_y&~1)*4 - 1 + ((i-scan8[0])>>3)*2);
  733. }
  734. }
  735. #undef SET_DIAG_MV
  736. }
  737. if(topright_ref != PART_NOT_AVAILABLE){
  738. *C= h->mv_cache[list][ i - 8 + part_width ];
  739. return topright_ref;
  740. }else{
  741. tprintf(s->avctx, "topright MV not available\n");
  742. *C= h->mv_cache[list][ i - 8 - 1 ];
  743. return h->ref_cache[list][ i - 8 - 1 ];
  744. }
  745. }
  746. /**
  747. * gets the predicted MV.
  748. * @param n the block index
  749. * @param part_width the width of the partition (4, 8,16) -> (1, 2, 4)
  750. * @param mx the x component of the predicted motion vector
  751. * @param my the y component of the predicted motion vector
  752. */
  753. static inline void pred_motion(H264Context * const h, int n, int part_width, int list, int ref, int * const mx, int * const my){
  754. const int index8= scan8[n];
  755. const int top_ref= h->ref_cache[list][ index8 - 8 ];
  756. const int left_ref= h->ref_cache[list][ index8 - 1 ];
  757. const int16_t * const A= h->mv_cache[list][ index8 - 1 ];
  758. const int16_t * const B= h->mv_cache[list][ index8 - 8 ];
  759. const int16_t * C;
  760. int diagonal_ref, match_count;
  761. assert(part_width==1 || part_width==2 || part_width==4);
  762. /* mv_cache
  763. B . . A T T T T
  764. U . . L . . , .
  765. U . . L . . . .
  766. U . . L . . , .
  767. . . . L . . . .
  768. */
  769. diagonal_ref= fetch_diagonal_mv(h, &C, index8, list, part_width);
  770. match_count= (diagonal_ref==ref) + (top_ref==ref) + (left_ref==ref);
  771. tprintf(h->s.avctx, "pred_motion match_count=%d\n", match_count);
  772. if(match_count > 1){ //most common
  773. *mx= mid_pred(A[0], B[0], C[0]);
  774. *my= mid_pred(A[1], B[1], C[1]);
  775. }else if(match_count==1){
  776. if(left_ref==ref){
  777. *mx= A[0];
  778. *my= A[1];
  779. }else if(top_ref==ref){
  780. *mx= B[0];
  781. *my= B[1];
  782. }else{
  783. *mx= C[0];
  784. *my= C[1];
  785. }
  786. }else{
  787. if(top_ref == PART_NOT_AVAILABLE && diagonal_ref == PART_NOT_AVAILABLE && left_ref != PART_NOT_AVAILABLE){
  788. *mx= A[0];
  789. *my= A[1];
  790. }else{
  791. *mx= mid_pred(A[0], B[0], C[0]);
  792. *my= mid_pred(A[1], B[1], C[1]);
  793. }
  794. }
  795. tprintf(h->s.avctx, "pred_motion (%2d %2d %2d) (%2d %2d %2d) (%2d %2d %2d) -> (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1], diagonal_ref, C[0], C[1], left_ref, A[0], A[1], ref, *mx, *my, h->s.mb_x, h->s.mb_y, n, list);
  796. }
  797. /**
  798. * gets the directionally predicted 16x8 MV.
  799. * @param n the block index
  800. * @param mx the x component of the predicted motion vector
  801. * @param my the y component of the predicted motion vector
  802. */
  803. static inline void pred_16x8_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
  804. if(n==0){
  805. const int top_ref= h->ref_cache[list][ scan8[0] - 8 ];
  806. const int16_t * const B= h->mv_cache[list][ scan8[0] - 8 ];
  807. tprintf(h->s.avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1], h->s.mb_x, h->s.mb_y, n, list);
  808. if(top_ref == ref){
  809. *mx= B[0];
  810. *my= B[1];
  811. return;
  812. }
  813. }else{
  814. const int left_ref= h->ref_cache[list][ scan8[8] - 1 ];
  815. const int16_t * const A= h->mv_cache[list][ scan8[8] - 1 ];
  816. tprintf(h->s.avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
  817. if(left_ref == ref){
  818. *mx= A[0];
  819. *my= A[1];
  820. return;
  821. }
  822. }
  823. //RARE
  824. pred_motion(h, n, 4, list, ref, mx, my);
  825. }
  826. /**
  827. * gets the directionally predicted 8x16 MV.
  828. * @param n the block index
  829. * @param mx the x component of the predicted motion vector
  830. * @param my the y component of the predicted motion vector
  831. */
  832. static inline void pred_8x16_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
  833. if(n==0){
  834. const int left_ref= h->ref_cache[list][ scan8[0] - 1 ];
  835. const int16_t * const A= h->mv_cache[list][ scan8[0] - 1 ];
  836. tprintf(h->s.avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
  837. if(left_ref == ref){
  838. *mx= A[0];
  839. *my= A[1];
  840. return;
  841. }
  842. }else{
  843. const int16_t * C;
  844. int diagonal_ref;
  845. diagonal_ref= fetch_diagonal_mv(h, &C, scan8[4], list, 2);
  846. tprintf(h->s.avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", diagonal_ref, C[0], C[1], h->s.mb_x, h->s.mb_y, n, list);
  847. if(diagonal_ref == ref){
  848. *mx= C[0];
  849. *my= C[1];
  850. return;
  851. }
  852. }
  853. //RARE
  854. pred_motion(h, n, 2, list, ref, mx, my);
  855. }
  856. static inline void pred_pskip_motion(H264Context * const h, int * const mx, int * const my){
  857. const int top_ref = h->ref_cache[0][ scan8[0] - 8 ];
  858. const int left_ref= h->ref_cache[0][ scan8[0] - 1 ];
  859. tprintf(h->s.avctx, "pred_pskip: (%d) (%d) at %2d %2d\n", top_ref, left_ref, h->s.mb_x, h->s.mb_y);
  860. if(top_ref == PART_NOT_AVAILABLE || left_ref == PART_NOT_AVAILABLE
  861. || (top_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 8 ] == 0)
  862. || (left_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 1 ] == 0)){
  863. *mx = *my = 0;
  864. return;
  865. }
  866. pred_motion(h, 0, 4, 0, 0, mx, my);
  867. return;
  868. }
  869. static inline void direct_dist_scale_factor(H264Context * const h){
  870. const int poc = h->s.current_picture_ptr->poc;
  871. const int poc1 = h->ref_list[1][0].poc;
  872. int i;
  873. for(i=0; i<h->ref_count[0]; i++){
  874. int poc0 = h->ref_list[0][i].poc;
  875. int td = av_clip(poc1 - poc0, -128, 127);
  876. if(td == 0 /* FIXME || pic0 is a long-term ref */){
  877. h->dist_scale_factor[i] = 256;
  878. }else{
  879. int tb = av_clip(poc - poc0, -128, 127);
  880. int tx = (16384 + (FFABS(td) >> 1)) / td;
  881. h->dist_scale_factor[i] = av_clip((tb*tx + 32) >> 6, -1024, 1023);
  882. }
  883. }
  884. if(FRAME_MBAFF){
  885. for(i=0; i<h->ref_count[0]; i++){
  886. h->dist_scale_factor_field[2*i] =
  887. h->dist_scale_factor_field[2*i+1] = h->dist_scale_factor[i];
  888. }
  889. }
  890. }
  891. static inline void direct_ref_list_init(H264Context * const h){
  892. MpegEncContext * const s = &h->s;
  893. Picture * const ref1 = &h->ref_list[1][0];
  894. Picture * const cur = s->current_picture_ptr;
  895. int list, i, j;
  896. if(cur->pict_type == I_TYPE)
  897. cur->ref_count[0] = 0;
  898. if(cur->pict_type != B_TYPE)
  899. cur->ref_count[1] = 0;
  900. for(list=0; list<2; list++){
  901. cur->ref_count[list] = h->ref_count[list];
  902. for(j=0; j<h->ref_count[list]; j++)
  903. cur->ref_poc[list][j] = h->ref_list[list][j].poc;
  904. }
  905. if(cur->pict_type != B_TYPE || h->direct_spatial_mv_pred)
  906. return;
  907. for(list=0; list<2; list++){
  908. for(i=0; i<ref1->ref_count[list]; i++){
  909. const int poc = ref1->ref_poc[list][i];
  910. h->map_col_to_list0[list][i] = 0; /* bogus; fills in for missing frames */
  911. for(j=0; j<h->ref_count[list]; j++)
  912. if(h->ref_list[list][j].poc == poc){
  913. h->map_col_to_list0[list][i] = j;
  914. break;
  915. }
  916. }
  917. }
  918. if(FRAME_MBAFF){
  919. for(list=0; list<2; list++){
  920. for(i=0; i<ref1->ref_count[list]; i++){
  921. j = h->map_col_to_list0[list][i];
  922. h->map_col_to_list0_field[list][2*i] = 2*j;
  923. h->map_col_to_list0_field[list][2*i+1] = 2*j+1;
  924. }
  925. }
  926. }
  927. }
  928. static inline void pred_direct_motion(H264Context * const h, int *mb_type){
  929. MpegEncContext * const s = &h->s;
  930. const int mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  931. const int b8_xy = 2*s->mb_x + 2*s->mb_y*h->b8_stride;
  932. const int b4_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
  933. const int mb_type_col = h->ref_list[1][0].mb_type[mb_xy];
  934. const int16_t (*l1mv0)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[0][b4_xy];
  935. const int16_t (*l1mv1)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[1][b4_xy];
  936. const int8_t *l1ref0 = &h->ref_list[1][0].ref_index[0][b8_xy];
  937. const int8_t *l1ref1 = &h->ref_list[1][0].ref_index[1][b8_xy];
  938. const int is_b8x8 = IS_8X8(*mb_type);
  939. unsigned int sub_mb_type;
  940. int i8, i4;
  941. #define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16|MB_TYPE_INTRA4x4|MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM)
  942. if(IS_8X8(mb_type_col) && !h->sps.direct_8x8_inference_flag){
  943. /* FIXME save sub mb types from previous frames (or derive from MVs)
  944. * so we know exactly what block size to use */
  945. sub_mb_type = MB_TYPE_8x8|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_4x4 */
  946. *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1;
  947. }else if(!is_b8x8 && (mb_type_col & MB_TYPE_16x16_OR_INTRA)){
  948. sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
  949. *mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_16x16 */
  950. }else{
  951. sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
  952. *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1;
  953. }
  954. if(!is_b8x8)
  955. *mb_type |= MB_TYPE_DIRECT2;
  956. if(MB_FIELD)
  957. *mb_type |= MB_TYPE_INTERLACED;
  958. tprintf(s->avctx, "mb_type = %08x, sub_mb_type = %08x, is_b8x8 = %d, mb_type_col = %08x\n", *mb_type, sub_mb_type, is_b8x8, mb_type_col);
  959. if(h->direct_spatial_mv_pred){
  960. int ref[2];
  961. int mv[2][2];
  962. int list;
  963. /* FIXME interlacing + spatial direct uses wrong colocated block positions */
  964. /* ref = min(neighbors) */
  965. for(list=0; list<2; list++){
  966. int refa = h->ref_cache[list][scan8[0] - 1];
  967. int refb = h->ref_cache[list][scan8[0] - 8];
  968. int refc = h->ref_cache[list][scan8[0] - 8 + 4];
  969. if(refc == -2)
  970. refc = h->ref_cache[list][scan8[0] - 8 - 1];
  971. ref[list] = refa;
  972. if(ref[list] < 0 || (refb < ref[list] && refb >= 0))
  973. ref[list] = refb;
  974. if(ref[list] < 0 || (refc < ref[list] && refc >= 0))
  975. ref[list] = refc;
  976. if(ref[list] < 0)
  977. ref[list] = -1;
  978. }
  979. if(ref[0] < 0 && ref[1] < 0){
  980. ref[0] = ref[1] = 0;
  981. mv[0][0] = mv[0][1] =
  982. mv[1][0] = mv[1][1] = 0;
  983. }else{
  984. for(list=0; list<2; list++){
  985. if(ref[list] >= 0)
  986. pred_motion(h, 0, 4, list, ref[list], &mv[list][0], &mv[list][1]);
  987. else
  988. mv[list][0] = mv[list][1] = 0;
  989. }
  990. }
  991. if(ref[1] < 0){
  992. *mb_type &= ~MB_TYPE_P0L1;
  993. sub_mb_type &= ~MB_TYPE_P0L1;
  994. }else if(ref[0] < 0){
  995. *mb_type &= ~MB_TYPE_P0L0;
  996. sub_mb_type &= ~MB_TYPE_P0L0;
  997. }
  998. if(IS_16X16(*mb_type)){
  999. int a=0, b=0;
  1000. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
  1001. fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
  1002. if(!IS_INTRA(mb_type_col)
  1003. && ( (l1ref0[0] == 0 && FFABS(l1mv0[0][0]) <= 1 && FFABS(l1mv0[0][1]) <= 1)
  1004. || (l1ref0[0] < 0 && l1ref1[0] == 0 && FFABS(l1mv1[0][0]) <= 1 && FFABS(l1mv1[0][1]) <= 1
  1005. && (h->x264_build>33 || !h->x264_build)))){
  1006. if(ref[0] > 0)
  1007. a= pack16to32(mv[0][0],mv[0][1]);
  1008. if(ref[1] > 0)
  1009. b= pack16to32(mv[1][0],mv[1][1]);
  1010. }else{
  1011. a= pack16to32(mv[0][0],mv[0][1]);
  1012. b= pack16to32(mv[1][0],mv[1][1]);
  1013. }
  1014. fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);
  1015. fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);
  1016. }else{
  1017. for(i8=0; i8<4; i8++){
  1018. const int x8 = i8&1;
  1019. const int y8 = i8>>1;
  1020. if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
  1021. continue;
  1022. h->sub_mb_type[i8] = sub_mb_type;
  1023. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mv[0][0],mv[0][1]), 4);
  1024. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mv[1][0],mv[1][1]), 4);
  1025. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
  1026. fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
  1027. /* col_zero_flag */
  1028. if(!IS_INTRA(mb_type_col) && ( l1ref0[x8 + y8*h->b8_stride] == 0
  1029. || (l1ref0[x8 + y8*h->b8_stride] < 0 && l1ref1[x8 + y8*h->b8_stride] == 0
  1030. && (h->x264_build>33 || !h->x264_build)))){
  1031. const int16_t (*l1mv)[2]= l1ref0[x8 + y8*h->b8_stride] == 0 ? l1mv0 : l1mv1;
  1032. if(IS_SUB_8X8(sub_mb_type)){
  1033. const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
  1034. if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
  1035. if(ref[0] == 0)
  1036. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
  1037. if(ref[1] == 0)
  1038. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
  1039. }
  1040. }else
  1041. for(i4=0; i4<4; i4++){
  1042. const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
  1043. if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
  1044. if(ref[0] == 0)
  1045. *(uint32_t*)h->mv_cache[0][scan8[i8*4+i4]] = 0;
  1046. if(ref[1] == 0)
  1047. *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] = 0;
  1048. }
  1049. }
  1050. }
  1051. }
  1052. }
  1053. }else{ /* direct temporal mv pred */
  1054. const int *map_col_to_list0[2] = {h->map_col_to_list0[0], h->map_col_to_list0[1]};
  1055. const int *dist_scale_factor = h->dist_scale_factor;
  1056. if(FRAME_MBAFF){
  1057. if(IS_INTERLACED(*mb_type)){
  1058. map_col_to_list0[0] = h->map_col_to_list0_field[0];
  1059. map_col_to_list0[1] = h->map_col_to_list0_field[1];
  1060. dist_scale_factor = h->dist_scale_factor_field;
  1061. }
  1062. if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col)){
  1063. /* FIXME assumes direct_8x8_inference == 1 */
  1064. const int pair_xy = s->mb_x + (s->mb_y&~1)*s->mb_stride;
  1065. int mb_types_col[2];
  1066. int y_shift;
  1067. *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1
  1068. | (is_b8x8 ? 0 : MB_TYPE_DIRECT2)
  1069. | (*mb_type & MB_TYPE_INTERLACED);
  1070. sub_mb_type = MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_16x16;
  1071. if(IS_INTERLACED(*mb_type)){
  1072. /* frame to field scaling */
  1073. mb_types_col[0] = h->ref_list[1][0].mb_type[pair_xy];
  1074. mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
  1075. if(s->mb_y&1){
  1076. l1ref0 -= 2*h->b8_stride;
  1077. l1ref1 -= 2*h->b8_stride;
  1078. l1mv0 -= 4*h->b_stride;
  1079. l1mv1 -= 4*h->b_stride;
  1080. }
  1081. y_shift = 0;
  1082. if( (mb_types_col[0] & MB_TYPE_16x16_OR_INTRA)
  1083. && (mb_types_col[1] & MB_TYPE_16x16_OR_INTRA)
  1084. && !is_b8x8)
  1085. *mb_type |= MB_TYPE_16x8;
  1086. else
  1087. *mb_type |= MB_TYPE_8x8;
  1088. }else{
  1089. /* field to frame scaling */
  1090. /* col_mb_y = (mb_y&~1) + (topAbsDiffPOC < bottomAbsDiffPOC ? 0 : 1)
  1091. * but in MBAFF, top and bottom POC are equal */
  1092. int dy = (s->mb_y&1) ? 1 : 2;
  1093. mb_types_col[0] =
  1094. mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
  1095. l1ref0 += dy*h->b8_stride;
  1096. l1ref1 += dy*h->b8_stride;
  1097. l1mv0 += 2*dy*h->b_stride;
  1098. l1mv1 += 2*dy*h->b_stride;
  1099. y_shift = 2;
  1100. if((mb_types_col[0] & (MB_TYPE_16x16_OR_INTRA|MB_TYPE_16x8))
  1101. && !is_b8x8)
  1102. *mb_type |= MB_TYPE_16x16;
  1103. else
  1104. *mb_type |= MB_TYPE_8x8;
  1105. }
  1106. for(i8=0; i8<4; i8++){
  1107. const int x8 = i8&1;
  1108. const int y8 = i8>>1;
  1109. int ref0, scale;
  1110. const int16_t (*l1mv)[2]= l1mv0;
  1111. if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
  1112. continue;
  1113. h->sub_mb_type[i8] = sub_mb_type;
  1114. fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
  1115. if(IS_INTRA(mb_types_col[y8])){
  1116. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
  1117. fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
  1118. fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
  1119. continue;
  1120. }
  1121. ref0 = l1ref0[x8 + (y8*2>>y_shift)*h->b8_stride];
  1122. if(ref0 >= 0)
  1123. ref0 = map_col_to_list0[0][ref0*2>>y_shift];
  1124. else{
  1125. ref0 = map_col_to_list0[1][l1ref1[x8 + (y8*2>>y_shift)*h->b8_stride]*2>>y_shift];
  1126. l1mv= l1mv1;
  1127. }
  1128. scale = dist_scale_factor[ref0];
  1129. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
  1130. {
  1131. const int16_t *mv_col = l1mv[x8*3 + (y8*6>>y_shift)*h->b_stride];
  1132. int my_col = (mv_col[1]<<y_shift)/2;
  1133. int mx = (scale * mv_col[0] + 128) >> 8;
  1134. int my = (scale * my_col + 128) >> 8;
  1135. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
  1136. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-my_col), 4);
  1137. }
  1138. }
  1139. return;
  1140. }
  1141. }
  1142. /* one-to-one mv scaling */
  1143. if(IS_16X16(*mb_type)){
  1144. int ref, mv0, mv1;
  1145. fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
  1146. if(IS_INTRA(mb_type_col)){
  1147. ref=mv0=mv1=0;
  1148. }else{
  1149. const int ref0 = l1ref0[0] >= 0 ? map_col_to_list0[0][l1ref0[0]]
  1150. : map_col_to_list0[1][l1ref1[0]];
  1151. const int scale = dist_scale_factor[ref0];
  1152. const int16_t *mv_col = l1ref0[0] >= 0 ? l1mv0[0] : l1mv1[0];
  1153. int mv_l0[2];
  1154. mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
  1155. mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
  1156. ref= ref0;
  1157. mv0= pack16to32(mv_l0[0],mv_l0[1]);
  1158. mv1= pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
  1159. }
  1160. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  1161. fill_rectangle(&h-> mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);
  1162. fill_rectangle(&h-> mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);
  1163. }else{
  1164. for(i8=0; i8<4; i8++){
  1165. const int x8 = i8&1;
  1166. const int y8 = i8>>1;
  1167. int ref0, scale;
  1168. const int16_t (*l1mv)[2]= l1mv0;
  1169. if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
  1170. continue;
  1171. h->sub_mb_type[i8] = sub_mb_type;
  1172. fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
  1173. if(IS_INTRA(mb_type_col)){
  1174. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
  1175. fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
  1176. fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
  1177. continue;
  1178. }
  1179. ref0 = l1ref0[x8 + y8*h->b8_stride];
  1180. if(ref0 >= 0)
  1181. ref0 = map_col_to_list0[0][ref0];
  1182. else{
  1183. ref0 = map_col_to_list0[1][l1ref1[x8 + y8*h->b8_stride]];
  1184. l1mv= l1mv1;
  1185. }
  1186. scale = dist_scale_factor[ref0];
  1187. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
  1188. if(IS_SUB_8X8(sub_mb_type)){
  1189. const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
  1190. int mx = (scale * mv_col[0] + 128) >> 8;
  1191. int my = (scale * mv_col[1] + 128) >> 8;
  1192. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
  1193. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-mv_col[1]), 4);
  1194. }else
  1195. for(i4=0; i4<4; i4++){
  1196. const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
  1197. int16_t *mv_l0 = h->mv_cache[0][scan8[i8*4+i4]];
  1198. mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
  1199. mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
  1200. *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] =
  1201. pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
  1202. }
  1203. }
  1204. }
  1205. }
  1206. }
  1207. static inline void write_back_motion(H264Context *h, int mb_type){
  1208. MpegEncContext * const s = &h->s;
  1209. const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
  1210. const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
  1211. int list;
  1212. if(!USES_LIST(mb_type, 0))
  1213. fill_rectangle(&s->current_picture.ref_index[0][b8_xy], 2, 2, h->b8_stride, (uint8_t)LIST_NOT_USED, 1);
  1214. for(list=0; list<h->list_count; list++){
  1215. int y;
  1216. if(!USES_LIST(mb_type, list))
  1217. continue;
  1218. for(y=0; y<4; y++){
  1219. *(uint64_t*)s->current_picture.motion_val[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+0 + 8*y];
  1220. *(uint64_t*)s->current_picture.motion_val[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+2 + 8*y];
  1221. }
  1222. if( h->pps.cabac ) {
  1223. if(IS_SKIP(mb_type))
  1224. fill_rectangle(h->mvd_table[list][b_xy], 4, 4, h->b_stride, 0, 4);
  1225. else
  1226. for(y=0; y<4; y++){
  1227. *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+0 + 8*y];
  1228. *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+2 + 8*y];
  1229. }
  1230. }
  1231. {
  1232. int8_t *ref_index = &s->current_picture.ref_index[list][b8_xy];
  1233. ref_index[0+0*h->b8_stride]= h->ref_cache[list][scan8[0]];
  1234. ref_index[1+0*h->b8_stride]= h->ref_cache[list][scan8[4]];
  1235. ref_index[0+1*h->b8_stride]= h->ref_cache[list][scan8[8]];
  1236. ref_index[1+1*h->b8_stride]= h->ref_cache[list][scan8[12]];
  1237. }
  1238. }
  1239. if(h->slice_type == B_TYPE && h->pps.cabac){
  1240. if(IS_8X8(mb_type)){
  1241. uint8_t *direct_table = &h->direct_table[b8_xy];
  1242. direct_table[1+0*h->b8_stride] = IS_DIRECT(h->sub_mb_type[1]) ? 1 : 0;
  1243. direct_table[0+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[2]) ? 1 : 0;
  1244. direct_table[1+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[3]) ? 1 : 0;
  1245. }
  1246. }
  1247. }
  1248. /**
  1249. * Decodes a network abstraction layer unit.
  1250. * @param consumed is the number of bytes used as input
  1251. * @param length is the length of the array
  1252. * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp tailing?
  1253. * @returns decoded bytes, might be src+1 if no escapes
  1254. */
  1255. static uint8_t *decode_nal(H264Context *h, uint8_t *src, int *dst_length, int *consumed, int length){
  1256. int i, si, di;
  1257. uint8_t *dst;
  1258. int bufidx;
  1259. // src[0]&0x80; //forbidden bit
  1260. h->nal_ref_idc= src[0]>>5;
  1261. h->nal_unit_type= src[0]&0x1F;
  1262. src++; length--;
  1263. #if 0
  1264. for(i=0; i<length; i++)
  1265. printf("%2X ", src[i]);
  1266. #endif
  1267. for(i=0; i+1<length; i+=2){
  1268. if(src[i]) continue;
  1269. if(i>0 && src[i-1]==0) i--;
  1270. if(i+2<length && src[i+1]==0 && src[i+2]<=3){
  1271. if(src[i+2]!=3){
  1272. /* startcode, so we must be past the end */
  1273. length=i;
  1274. }
  1275. break;
  1276. }
  1277. }
  1278. if(i>=length-1){ //no escaped 0
  1279. *dst_length= length;
  1280. *consumed= length+1; //+1 for the header
  1281. return src;
  1282. }
  1283. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
  1284. h->rbsp_buffer[bufidx]= av_fast_realloc(h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length);
  1285. dst= h->rbsp_buffer[bufidx];
  1286. if (dst == NULL){
  1287. return NULL;
  1288. }
  1289. //printf("decoding esc\n");
  1290. si=di=0;
  1291. while(si<length){
  1292. //remove escapes (very rare 1:2^22)
  1293. if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
  1294. if(src[si+2]==3){ //escape
  1295. dst[di++]= 0;
  1296. dst[di++]= 0;
  1297. si+=3;
  1298. continue;
  1299. }else //next start code
  1300. break;
  1301. }
  1302. dst[di++]= src[si++];
  1303. }
  1304. *dst_length= di;
  1305. *consumed= si + 1;//+1 for the header
  1306. //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
  1307. return dst;
  1308. }
  1309. /**
  1310. * identifies the exact end of the bitstream
  1311. * @return the length of the trailing, or 0 if damaged
  1312. */
  1313. static int decode_rbsp_trailing(H264Context *h, uint8_t *src){
  1314. int v= *src;
  1315. int r;
  1316. tprintf(h->s.avctx, "rbsp trailing %X\n", v);
  1317. for(r=1; r<9; r++){
  1318. if(v&1) return r;
  1319. v>>=1;
  1320. }
  1321. return 0;
  1322. }
  1323. /**
  1324. * idct tranforms the 16 dc values and dequantize them.
  1325. * @param qp quantization parameter
  1326. */
  1327. static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
  1328. #define stride 16
  1329. int i;
  1330. int temp[16]; //FIXME check if this is a good idea
  1331. static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
  1332. static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
  1333. //memset(block, 64, 2*256);
  1334. //return;
  1335. for(i=0; i<4; i++){
  1336. const int offset= y_offset[i];
  1337. const int z0= block[offset+stride*0] + block[offset+stride*4];
  1338. const int z1= block[offset+stride*0] - block[offset+stride*4];
  1339. const int z2= block[offset+stride*1] - block[offset+stride*5];
  1340. const int z3= block[offset+stride*1] + block[offset+stride*5];
  1341. temp[4*i+0]= z0+z3;
  1342. temp[4*i+1]= z1+z2;
  1343. temp[4*i+2]= z1-z2;
  1344. temp[4*i+3]= z0-z3;
  1345. }
  1346. for(i=0; i<4; i++){
  1347. const int offset= x_offset[i];
  1348. const int z0= temp[4*0+i] + temp[4*2+i];
  1349. const int z1= temp[4*0+i] - temp[4*2+i];
  1350. const int z2= temp[4*1+i] - temp[4*3+i];
  1351. const int z3= temp[4*1+i] + temp[4*3+i];
  1352. block[stride*0 +offset]= ((((z0 + z3)*qmul + 128 ) >> 8)); //FIXME think about merging this into decode_resdual
  1353. block[stride*2 +offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
  1354. block[stride*8 +offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
  1355. block[stride*10+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
  1356. }
  1357. }
  1358. #if 0
  1359. /**
  1360. * dct tranforms the 16 dc values.
  1361. * @param qp quantization parameter ??? FIXME
  1362. */
  1363. static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
  1364. // const int qmul= dequant_coeff[qp][0];
  1365. int i;
  1366. int temp[16]; //FIXME check if this is a good idea
  1367. static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
  1368. static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
  1369. for(i=0; i<4; i++){
  1370. const int offset= y_offset[i];
  1371. const int z0= block[offset+stride*0] + block[offset+stride*4];
  1372. const int z1= block[offset+stride*0] - block[offset+stride*4];
  1373. const int z2= block[offset+stride*1] - block[offset+stride*5];
  1374. const int z3= block[offset+stride*1] + block[offset+stride*5];
  1375. temp[4*i+0]= z0+z3;
  1376. temp[4*i+1]= z1+z2;
  1377. temp[4*i+2]= z1-z2;
  1378. temp[4*i+3]= z0-z3;
  1379. }
  1380. for(i=0; i<4; i++){
  1381. const int offset= x_offset[i];
  1382. const int z0= temp[4*0+i] + temp[4*2+i];
  1383. const int z1= temp[4*0+i] - temp[4*2+i];
  1384. const int z2= temp[4*1+i] - temp[4*3+i];
  1385. const int z3= temp[4*1+i] + temp[4*3+i];
  1386. block[stride*0 +offset]= (z0 + z3)>>1;
  1387. block[stride*2 +offset]= (z1 + z2)>>1;
  1388. block[stride*8 +offset]= (z1 - z2)>>1;
  1389. block[stride*10+offset]= (z0 - z3)>>1;
  1390. }
  1391. }
  1392. #endif
  1393. #undef xStride
  1394. #undef stride
  1395. static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
  1396. const int stride= 16*2;
  1397. const int xStride= 16;
  1398. int a,b,c,d,e;
  1399. a= block[stride*0 + xStride*0];
  1400. b= block[stride*0 + xStride*1];
  1401. c= block[stride*1 + xStride*0];
  1402. d= block[stride*1 + xStride*1];
  1403. e= a-b;
  1404. a= a+b;
  1405. b= c-d;
  1406. c= c+d;
  1407. block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
  1408. block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
  1409. block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
  1410. block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
  1411. }
  1412. #if 0
  1413. static void chroma_dc_dct_c(DCTELEM *block){
  1414. const int stride= 16*2;
  1415. const int xStride= 16;
  1416. int a,b,c,d,e;
  1417. a= block[stride*0 + xStride*0];
  1418. b= block[stride*0 + xStride*1];
  1419. c= block[stride*1 + xStride*0];
  1420. d= block[stride*1 + xStride*1];
  1421. e= a-b;
  1422. a= a+b;
  1423. b= c-d;
  1424. c= c+d;
  1425. block[stride*0 + xStride*0]= (a+c);
  1426. block[stride*0 + xStride*1]= (e+b);
  1427. block[stride*1 + xStride*0]= (a-c);
  1428. block[stride*1 + xStride*1]= (e-b);
  1429. }
  1430. #endif
  1431. /**
  1432. * gets the chroma qp.
  1433. */
  1434. static inline int get_chroma_qp(H264Context *h, int t, int qscale){
  1435. return h->pps.chroma_qp_table[t][qscale & 0xff];
  1436. }
  1437. //FIXME need to check that this does not overflow signed 32 bit for low qp, i am not sure, it's very close
  1438. //FIXME check that gcc inlines this (and optimizes intra & separate_dc stuff away)
  1439. static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale, int intra, int separate_dc){
  1440. int i;
  1441. const int * const quant_table= quant_coeff[qscale];
  1442. const int bias= intra ? (1<<QUANT_SHIFT)/3 : (1<<QUANT_SHIFT)/6;
  1443. const unsigned int threshold1= (1<<QUANT_SHIFT) - bias - 1;
  1444. const unsigned int threshold2= (threshold1<<1);
  1445. int last_non_zero;
  1446. if(separate_dc){
  1447. if(qscale<=18){
  1448. //avoid overflows
  1449. const int dc_bias= intra ? (1<<(QUANT_SHIFT-2))/3 : (1<<(QUANT_SHIFT-2))/6;
  1450. const unsigned int dc_threshold1= (1<<(QUANT_SHIFT-2)) - dc_bias - 1;
  1451. const unsigned int dc_threshold2= (dc_threshold1<<1);
  1452. int level= block[0]*quant_coeff[qscale+18][0];
  1453. if(((unsigned)(level+dc_threshold1))>dc_threshold2){
  1454. if(level>0){
  1455. level= (dc_bias + level)>>(QUANT_SHIFT-2);
  1456. block[0]= level;
  1457. }else{
  1458. level= (dc_bias - level)>>(QUANT_SHIFT-2);
  1459. block[0]= -level;
  1460. }
  1461. // last_non_zero = i;
  1462. }else{
  1463. block[0]=0;
  1464. }
  1465. }else{
  1466. const int dc_bias= intra ? (1<<(QUANT_SHIFT+1))/3 : (1<<(QUANT_SHIFT+1))/6;
  1467. const unsigned int dc_threshold1= (1<<(QUANT_SHIFT+1)) - dc_bias - 1;
  1468. const unsigned int dc_threshold2= (dc_threshold1<<1);
  1469. int level= block[0]*quant_table[0];
  1470. if(((unsigned)(level+dc_threshold1))>dc_threshold2){
  1471. if(level>0){
  1472. level= (dc_bias + level)>>(QUANT_SHIFT+1);
  1473. block[0]= level;
  1474. }else{
  1475. level= (dc_bias - level)>>(QUANT_SHIFT+1);
  1476. block[0]= -level;
  1477. }
  1478. // last_non_zero = i;
  1479. }else{
  1480. block[0]=0;
  1481. }
  1482. }
  1483. last_non_zero= 0;
  1484. i=1;
  1485. }else{
  1486. last_non_zero= -1;
  1487. i=0;
  1488. }
  1489. for(; i<16; i++){
  1490. const int j= scantable[i];
  1491. int level= block[j]*quant_table[j];
  1492. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  1493. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  1494. if(((unsigned)(level+threshold1))>threshold2){
  1495. if(level>0){
  1496. level= (bias + level)>>QUANT_SHIFT;
  1497. block[j]= level;
  1498. }else{
  1499. level= (bias - level)>>QUANT_SHIFT;
  1500. block[j]= -level;
  1501. }
  1502. last_non_zero = i;
  1503. }else{
  1504. block[j]=0;
  1505. }
  1506. }
  1507. return last_non_zero;
  1508. }
  1509. static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
  1510. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1511. int src_x_offset, int src_y_offset,
  1512. qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
  1513. MpegEncContext * const s = &h->s;
  1514. const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
  1515. int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
  1516. const int luma_xy= (mx&3) + ((my&3)<<2);
  1517. uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
  1518. uint8_t * src_cb, * src_cr;
  1519. int extra_width= h->emu_edge_width;
  1520. int extra_height= h->emu_edge_height;
  1521. int emu=0;
  1522. const int full_mx= mx>>2;
  1523. const int full_my= my>>2;
  1524. const int pic_width = 16*s->mb_width;
  1525. const int pic_height = 16*s->mb_height >> MB_FIELD;
  1526. if(!pic->data[0]) //FIXME this is unacceptable, some senseable error concealment must be done for missing reference frames
  1527. return;
  1528. if(mx&7) extra_width -= 3;
  1529. if(my&7) extra_height -= 3;
  1530. if( full_mx < 0-extra_width
  1531. || full_my < 0-extra_height
  1532. || full_mx + 16/*FIXME*/ > pic_width + extra_width
  1533. || full_my + 16/*FIXME*/ > pic_height + extra_height){
  1534. ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
  1535. src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
  1536. emu=1;
  1537. }
  1538. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
  1539. if(!square){
  1540. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  1541. }
  1542. if(ENABLE_GRAY && s->flags&CODEC_FLAG_GRAY) return;
  1543. if(MB_FIELD){
  1544. // chroma offset when predicting from a field of opposite parity
  1545. my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
  1546. emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
  1547. }
  1548. src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
  1549. src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
  1550. if(emu){
  1551. ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  1552. src_cb= s->edge_emu_buffer;
  1553. }
  1554. chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  1555. if(emu){
  1556. ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  1557. src_cr= s->edge_emu_buffer;
  1558. }
  1559. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  1560. }
  1561. static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
  1562. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1563. int x_offset, int y_offset,
  1564. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  1565. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  1566. int list0, int list1){
  1567. MpegEncContext * const s = &h->s;
  1568. qpel_mc_func *qpix_op= qpix_put;
  1569. h264_chroma_mc_func chroma_op= chroma_put;
  1570. dest_y += 2*x_offset + 2*y_offset*h-> mb_linesize;
  1571. dest_cb += x_offset + y_offset*h->mb_uvlinesize;
  1572. dest_cr += x_offset + y_offset*h->mb_uvlinesize;
  1573. x_offset += 8*s->mb_x;
  1574. y_offset += 8*(s->mb_y >> MB_FIELD);
  1575. if(list0){
  1576. Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
  1577. mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
  1578. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1579. qpix_op, chroma_op);
  1580. qpix_op= qpix_avg;
  1581. chroma_op= chroma_avg;
  1582. }
  1583. if(list1){
  1584. Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
  1585. mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
  1586. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1587. qpix_op, chroma_op);
  1588. }
  1589. }
  1590. static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
  1591. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1592. int x_offset, int y_offset,
  1593. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  1594. h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
  1595. h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
  1596. int list0, int list1){
  1597. MpegEncContext * const s = &h->s;
  1598. dest_y += 2*x_offset + 2*y_offset*h-> mb_linesize;
  1599. dest_cb += x_offset + y_offset*h->mb_uvlinesize;
  1600. dest_cr += x_offset + y_offset*h->mb_uvlinesize;
  1601. x_offset += 8*s->mb_x;
  1602. y_offset += 8*(s->mb_y >> MB_FIELD);
  1603. if(list0 && list1){
  1604. /* don't optimize for luma-only case, since B-frames usually
  1605. * use implicit weights => chroma too. */
  1606. uint8_t *tmp_cb = s->obmc_scratchpad;
  1607. uint8_t *tmp_cr = s->obmc_scratchpad + 8;
  1608. uint8_t *tmp_y = s->obmc_scratchpad + 8*h->mb_uvlinesize;
  1609. int refn0 = h->ref_cache[0][ scan8[n] ];
  1610. int refn1 = h->ref_cache[1][ scan8[n] ];
  1611. mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
  1612. dest_y, dest_cb, dest_cr,
  1613. x_offset, y_offset, qpix_put, chroma_put);
  1614. mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
  1615. tmp_y, tmp_cb, tmp_cr,
  1616. x_offset, y_offset, qpix_put, chroma_put);
  1617. if(h->use_weight == 2){
  1618. int weight0 = h->implicit_weight[refn0][refn1];
  1619. int weight1 = 64 - weight0;
  1620. luma_weight_avg( dest_y, tmp_y, h-> mb_linesize, 5, weight0, weight1, 0);
  1621. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
  1622. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
  1623. }else{
  1624. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
  1625. h->luma_weight[0][refn0], h->luma_weight[1][refn1],
  1626. h->luma_offset[0][refn0] + h->luma_offset[1][refn1]);
  1627. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1628. h->chroma_weight[0][refn0][0], h->chroma_weight[1][refn1][0],
  1629. h->chroma_offset[0][refn0][0] + h->chroma_offset[1][refn1][0]);
  1630. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1631. h->chroma_weight[0][refn0][1], h->chroma_weight[1][refn1][1],
  1632. h->chroma_offset[0][refn0][1] + h->chroma_offset[1][refn1][1]);
  1633. }
  1634. }else{
  1635. int list = list1 ? 1 : 0;
  1636. int refn = h->ref_cache[list][ scan8[n] ];
  1637. Picture *ref= &h->ref_list[list][refn];
  1638. mc_dir_part(h, ref, n, square, chroma_height, delta, list,
  1639. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1640. qpix_put, chroma_put);
  1641. luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
  1642. h->luma_weight[list][refn], h->luma_offset[list][refn]);
  1643. if(h->use_weight_chroma){
  1644. chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1645. h->chroma_weight[list][refn][0], h->chroma_offset[list][refn][0]);
  1646. chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1647. h->chroma_weight[list][refn][1], h->chroma_offset[list][refn][1]);
  1648. }
  1649. }
  1650. }
  1651. static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
  1652. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1653. int x_offset, int y_offset,
  1654. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  1655. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  1656. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  1657. int list0, int list1){
  1658. if((h->use_weight==2 && list0 && list1
  1659. && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ] != 32))
  1660. || h->use_weight==1)
  1661. mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  1662. x_offset, y_offset, qpix_put, chroma_put,
  1663. weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
  1664. else
  1665. mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  1666. x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
  1667. }
  1668. static inline void prefetch_motion(H264Context *h, int list){
  1669. /* fetch pixels for estimated mv 4 macroblocks ahead
  1670. * optimized for 64byte cache lines */
  1671. MpegEncContext * const s = &h->s;
  1672. const int refn = h->ref_cache[list][scan8[0]];
  1673. if(refn >= 0){
  1674. const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
  1675. const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
  1676. uint8_t **src= h->ref_list[list][refn].data;
  1677. int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
  1678. s->dsp.prefetch(src[0]+off, s->linesize, 4);
  1679. off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
  1680. s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
  1681. }
  1682. }
  1683. static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1684. qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
  1685. qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
  1686. h264_weight_func *weight_op, h264_biweight_func *weight_avg){
  1687. MpegEncContext * const s = &h->s;
  1688. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  1689. const int mb_type= s->current_picture.mb_type[mb_xy];
  1690. assert(IS_INTER(mb_type));
  1691. prefetch_motion(h, 0);
  1692. if(IS_16X16(mb_type)){
  1693. mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
  1694. qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
  1695. &weight_op[0], &weight_avg[0],
  1696. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  1697. }else if(IS_16X8(mb_type)){
  1698. mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
  1699. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  1700. &weight_op[1], &weight_avg[1],
  1701. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  1702. mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
  1703. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  1704. &weight_op[1], &weight_avg[1],
  1705. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
  1706. }else if(IS_8X16(mb_type)){
  1707. mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
  1708. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  1709. &weight_op[2], &weight_avg[2],
  1710. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  1711. mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
  1712. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  1713. &weight_op[2], &weight_avg[2],
  1714. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
  1715. }else{
  1716. int i;
  1717. assert(IS_8X8(mb_type));
  1718. for(i=0; i<4; i++){
  1719. const int sub_mb_type= h->sub_mb_type[i];
  1720. const int n= 4*i;
  1721. int x_offset= (i&1)<<2;
  1722. int y_offset= (i&2)<<1;
  1723. if(IS_SUB_8X8(sub_mb_type)){
  1724. mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1725. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  1726. &weight_op[3], &weight_avg[3],
  1727. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1728. }else if(IS_SUB_8X4(sub_mb_type)){
  1729. mc_part(h, n , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1730. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  1731. &weight_op[4], &weight_avg[4],
  1732. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1733. mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
  1734. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  1735. &weight_op[4], &weight_avg[4],
  1736. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1737. }else if(IS_SUB_4X8(sub_mb_type)){
  1738. mc_part(h, n , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1739. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  1740. &weight_op[5], &weight_avg[5],
  1741. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1742. mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
  1743. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  1744. &weight_op[5], &weight_avg[5],
  1745. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1746. }else{
  1747. int j;
  1748. assert(IS_SUB_4X4(sub_mb_type));
  1749. for(j=0; j<4; j++){
  1750. int sub_x_offset= x_offset + 2*(j&1);
  1751. int sub_y_offset= y_offset + (j&2);
  1752. mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
  1753. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  1754. &weight_op[6], &weight_avg[6],
  1755. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1756. }
  1757. }
  1758. }
  1759. }
  1760. prefetch_motion(h, 1);
  1761. }
  1762. static void decode_init_vlc(void){
  1763. static int done = 0;
  1764. if (!done) {
  1765. int i;
  1766. done = 1;
  1767. init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,
  1768. &chroma_dc_coeff_token_len [0], 1, 1,
  1769. &chroma_dc_coeff_token_bits[0], 1, 1, 1);
  1770. for(i=0; i<4; i++){
  1771. init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,
  1772. &coeff_token_len [i][0], 1, 1,
  1773. &coeff_token_bits[i][0], 1, 1, 1);
  1774. }
  1775. for(i=0; i<3; i++){
  1776. init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
  1777. &chroma_dc_total_zeros_len [i][0], 1, 1,
  1778. &chroma_dc_total_zeros_bits[i][0], 1, 1, 1);
  1779. }
  1780. for(i=0; i<15; i++){
  1781. init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16,
  1782. &total_zeros_len [i][0], 1, 1,
  1783. &total_zeros_bits[i][0], 1, 1, 1);
  1784. }
  1785. for(i=0; i<6; i++){
  1786. init_vlc(&run_vlc[i], RUN_VLC_BITS, 7,
  1787. &run_len [i][0], 1, 1,
  1788. &run_bits[i][0], 1, 1, 1);
  1789. }
  1790. init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,
  1791. &run_len [6][0], 1, 1,
  1792. &run_bits[6][0], 1, 1, 1);
  1793. }
  1794. }
  1795. static void free_tables(H264Context *h){
  1796. int i;
  1797. H264Context *hx;
  1798. av_freep(&h->intra4x4_pred_mode);
  1799. av_freep(&h->chroma_pred_mode_table);
  1800. av_freep(&h->cbp_table);
  1801. av_freep(&h->mvd_table[0]);
  1802. av_freep(&h->mvd_table[1]);
  1803. av_freep(&h->direct_table);
  1804. av_freep(&h->non_zero_count);
  1805. av_freep(&h->slice_table_base);
  1806. h->slice_table= NULL;
  1807. av_freep(&h->mb2b_xy);
  1808. av_freep(&h->mb2b8_xy);
  1809. for(i = 0; i < MAX_SPS_COUNT; i++)
  1810. av_freep(h->sps_buffers + i);
  1811. for(i = 0; i < MAX_PPS_COUNT; i++)
  1812. av_freep(h->pps_buffers + i);
  1813. for(i = 0; i < h->s.avctx->thread_count; i++) {
  1814. hx = h->thread_context[i];
  1815. if(!hx) continue;
  1816. av_freep(&hx->top_borders[1]);
  1817. av_freep(&hx->top_borders[0]);
  1818. av_freep(&hx->s.obmc_scratchpad);
  1819. av_freep(&hx->s.allocated_edge_emu_buffer);
  1820. }
  1821. }
  1822. static void init_dequant8_coeff_table(H264Context *h){
  1823. int i,q,x;
  1824. const int transpose = (h->s.dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly
  1825. h->dequant8_coeff[0] = h->dequant8_buffer[0];
  1826. h->dequant8_coeff[1] = h->dequant8_buffer[1];
  1827. for(i=0; i<2; i++ ){
  1828. if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
  1829. h->dequant8_coeff[1] = h->dequant8_buffer[0];
  1830. break;
  1831. }
  1832. for(q=0; q<52; q++){
  1833. int shift = ff_div6[q];
  1834. int idx = ff_rem6[q];
  1835. for(x=0; x<64; x++)
  1836. h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =
  1837. ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
  1838. h->pps.scaling_matrix8[i][x]) << shift;
  1839. }
  1840. }
  1841. }
  1842. static void init_dequant4_coeff_table(H264Context *h){
  1843. int i,j,q,x;
  1844. const int transpose = (h->s.dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly
  1845. for(i=0; i<6; i++ ){
  1846. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  1847. for(j=0; j<i; j++){
  1848. if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
  1849. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  1850. break;
  1851. }
  1852. }
  1853. if(j<i)
  1854. continue;
  1855. for(q=0; q<52; q++){
  1856. int shift = ff_div6[q] + 2;
  1857. int idx = ff_rem6[q];
  1858. for(x=0; x<16; x++)
  1859. h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =
  1860. ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
  1861. h->pps.scaling_matrix4[i][x]) << shift;
  1862. }
  1863. }
  1864. }
  1865. static void init_dequant_tables(H264Context *h){
  1866. int i,x;
  1867. init_dequant4_coeff_table(h);
  1868. if(h->pps.transform_8x8_mode)
  1869. init_dequant8_coeff_table(h);
  1870. if(h->sps.transform_bypass){
  1871. for(i=0; i<6; i++)
  1872. for(x=0; x<16; x++)
  1873. h->dequant4_coeff[i][0][x] = 1<<6;
  1874. if(h->pps.transform_8x8_mode)
  1875. for(i=0; i<2; i++)
  1876. for(x=0; x<64; x++)
  1877. h->dequant8_coeff[i][0][x] = 1<<6;
  1878. }
  1879. }
  1880. /**
  1881. * allocates tables.
  1882. * needs width/height
  1883. */
  1884. static int alloc_tables(H264Context *h){
  1885. MpegEncContext * const s = &h->s;
  1886. const int big_mb_num= s->mb_stride * (s->mb_height+1);
  1887. int x,y;
  1888. CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8 * sizeof(uint8_t))
  1889. CHECKED_ALLOCZ(h->non_zero_count , big_mb_num * 16 * sizeof(uint8_t))
  1890. CHECKED_ALLOCZ(h->slice_table_base , (big_mb_num+s->mb_stride) * sizeof(uint8_t))
  1891. CHECKED_ALLOCZ(h->cbp_table, big_mb_num * sizeof(uint16_t))
  1892. if( h->pps.cabac ) {
  1893. CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))
  1894. CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));
  1895. CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));
  1896. CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));
  1897. }
  1898. memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride) * sizeof(uint8_t));
  1899. h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
  1900. CHECKED_ALLOCZ(h->mb2b_xy , big_mb_num * sizeof(uint32_t));
  1901. CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint32_t));
  1902. for(y=0; y<s->mb_height; y++){
  1903. for(x=0; x<s->mb_width; x++){
  1904. const int mb_xy= x + y*s->mb_stride;
  1905. const int b_xy = 4*x + 4*y*h->b_stride;
  1906. const int b8_xy= 2*x + 2*y*h->b8_stride;
  1907. h->mb2b_xy [mb_xy]= b_xy;
  1908. h->mb2b8_xy[mb_xy]= b8_xy;
  1909. }
  1910. }
  1911. s->obmc_scratchpad = NULL;
  1912. if(!h->dequant4_coeff[0])
  1913. init_dequant_tables(h);
  1914. return 0;
  1915. fail:
  1916. free_tables(h);
  1917. return -1;
  1918. }
  1919. /**
  1920. * Mimic alloc_tables(), but for every context thread.
  1921. */
  1922. static void clone_tables(H264Context *dst, H264Context *src){
  1923. dst->intra4x4_pred_mode = src->intra4x4_pred_mode;
  1924. dst->non_zero_count = src->non_zero_count;
  1925. dst->slice_table = src->slice_table;
  1926. dst->cbp_table = src->cbp_table;
  1927. dst->mb2b_xy = src->mb2b_xy;
  1928. dst->mb2b8_xy = src->mb2b8_xy;
  1929. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  1930. dst->mvd_table[0] = src->mvd_table[0];
  1931. dst->mvd_table[1] = src->mvd_table[1];
  1932. dst->direct_table = src->direct_table;
  1933. dst->s.obmc_scratchpad = NULL;
  1934. ff_h264_pred_init(&dst->hpc, src->s.codec_id);
  1935. }
  1936. /**
  1937. * Init context
  1938. * Allocate buffers which are not shared amongst multiple threads.
  1939. */
  1940. static int context_init(H264Context *h){
  1941. MpegEncContext * const s = &h->s;
  1942. CHECKED_ALLOCZ(h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
  1943. CHECKED_ALLOCZ(h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
  1944. // edge emu needs blocksize + filter length - 1 (=17x17 for halfpel / 21x21 for h264)
  1945. CHECKED_ALLOCZ(s->allocated_edge_emu_buffer,
  1946. (s->width+64)*2*21*2); //(width + edge + align)*interlaced*MBsize*tolerance
  1947. s->edge_emu_buffer= s->allocated_edge_emu_buffer + (s->width+64)*2*21;
  1948. return 0;
  1949. fail:
  1950. return -1; // free_tables will clean up for us
  1951. }
  1952. static void common_init(H264Context *h){
  1953. MpegEncContext * const s = &h->s;
  1954. s->width = s->avctx->width;
  1955. s->height = s->avctx->height;
  1956. s->codec_id= s->avctx->codec->id;
  1957. ff_h264_pred_init(&h->hpc, s->codec_id);
  1958. h->dequant_coeff_pps= -1;
  1959. s->unrestricted_mv=1;
  1960. s->decode=1; //FIXME
  1961. memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  1962. memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  1963. }
  1964. static int decode_init(AVCodecContext *avctx){
  1965. H264Context *h= avctx->priv_data;
  1966. MpegEncContext * const s = &h->s;
  1967. MPV_decode_defaults(s);
  1968. s->avctx = avctx;
  1969. common_init(h);
  1970. s->out_format = FMT_H264;
  1971. s->workaround_bugs= avctx->workaround_bugs;
  1972. // set defaults
  1973. // s->decode_mb= ff_h263_decode_mb;
  1974. s->quarter_sample = 1;
  1975. s->low_delay= 1;
  1976. avctx->pix_fmt= PIX_FMT_YUV420P;
  1977. decode_init_vlc();
  1978. if(avctx->extradata_size > 0 && avctx->extradata &&
  1979. *(char *)avctx->extradata == 1){
  1980. h->is_avc = 1;
  1981. h->got_avcC = 0;
  1982. } else {
  1983. h->is_avc = 0;
  1984. }
  1985. h->thread_context[0] = h;
  1986. return 0;
  1987. }
  1988. static int frame_start(H264Context *h){
  1989. MpegEncContext * const s = &h->s;
  1990. int i;
  1991. if(MPV_frame_start(s, s->avctx) < 0)
  1992. return -1;
  1993. ff_er_frame_start(s);
  1994. /*
  1995. * MPV_frame_start uses pict_type to derive key_frame.
  1996. * This is incorrect for H.264; IDR markings must be used.
  1997. * Zero here; IDR markings per slice in frame or fields are OR'd in later.
  1998. * See decode_nal_units().
  1999. */
  2000. s->current_picture_ptr->key_frame= 0;
  2001. assert(s->linesize && s->uvlinesize);
  2002. for(i=0; i<16; i++){
  2003. h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
  2004. h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
  2005. }
  2006. for(i=0; i<4; i++){
  2007. h->block_offset[16+i]=
  2008. h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  2009. h->block_offset[24+16+i]=
  2010. h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  2011. }
  2012. /* can't be in alloc_tables because linesize isn't known there.
  2013. * FIXME: redo bipred weight to not require extra buffer? */
  2014. for(i = 0; i < s->avctx->thread_count; i++)
  2015. if(!h->thread_context[i]->s.obmc_scratchpad)
  2016. h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
  2017. /* some macroblocks will be accessed before they're available */
  2018. if(FRAME_MBAFF || s->avctx->thread_count > 1)
  2019. memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(uint8_t));
  2020. // s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
  2021. return 0;
  2022. }
  2023. static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple){
  2024. MpegEncContext * const s = &h->s;
  2025. int i;
  2026. src_y -= linesize;
  2027. src_cb -= uvlinesize;
  2028. src_cr -= uvlinesize;
  2029. // There are two lines saved, the line above the the top macroblock of a pair,
  2030. // and the line above the bottom macroblock
  2031. h->left_border[0]= h->top_borders[0][s->mb_x][15];
  2032. for(i=1; i<17; i++){
  2033. h->left_border[i]= src_y[15+i* linesize];
  2034. }
  2035. *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y + 16*linesize);
  2036. *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
  2037. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2038. h->left_border[17 ]= h->top_borders[0][s->mb_x][16+7];
  2039. h->left_border[17+9]= h->top_borders[0][s->mb_x][24+7];
  2040. for(i=1; i<9; i++){
  2041. h->left_border[i+17 ]= src_cb[7+i*uvlinesize];
  2042. h->left_border[i+17+9]= src_cr[7+i*uvlinesize];
  2043. }
  2044. *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
  2045. *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
  2046. }
  2047. }
  2048. static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg, int simple){
  2049. MpegEncContext * const s = &h->s;
  2050. int temp8, i;
  2051. uint64_t temp64;
  2052. int deblock_left;
  2053. int deblock_top;
  2054. int mb_xy;
  2055. if(h->deblocking_filter == 2) {
  2056. mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  2057. deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];
  2058. deblock_top = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];
  2059. } else {
  2060. deblock_left = (s->mb_x > 0);
  2061. deblock_top = (s->mb_y > 0);
  2062. }
  2063. src_y -= linesize + 1;
  2064. src_cb -= uvlinesize + 1;
  2065. src_cr -= uvlinesize + 1;
  2066. #define XCHG(a,b,t,xchg)\
  2067. t= a;\
  2068. if(xchg)\
  2069. a= b;\
  2070. b= t;
  2071. if(deblock_left){
  2072. for(i = !deblock_top; i<17; i++){
  2073. XCHG(h->left_border[i ], src_y [i* linesize], temp8, xchg);
  2074. }
  2075. }
  2076. if(deblock_top){
  2077. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
  2078. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
  2079. if(s->mb_x+1 < s->mb_width){
  2080. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
  2081. }
  2082. }
  2083. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2084. if(deblock_left){
  2085. for(i = !deblock_top; i<9; i++){
  2086. XCHG(h->left_border[i+17 ], src_cb[i*uvlinesize], temp8, xchg);
  2087. XCHG(h->left_border[i+17+9], src_cr[i*uvlinesize], temp8, xchg);
  2088. }
  2089. }
  2090. if(deblock_top){
  2091. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
  2092. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
  2093. }
  2094. }
  2095. }
  2096. static inline void backup_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize){
  2097. MpegEncContext * const s = &h->s;
  2098. int i;
  2099. src_y -= 2 * linesize;
  2100. src_cb -= 2 * uvlinesize;
  2101. src_cr -= 2 * uvlinesize;
  2102. // There are two lines saved, the line above the the top macroblock of a pair,
  2103. // and the line above the bottom macroblock
  2104. h->left_border[0]= h->top_borders[0][s->mb_x][15];
  2105. h->left_border[1]= h->top_borders[1][s->mb_x][15];
  2106. for(i=2; i<34; i++){
  2107. h->left_border[i]= src_y[15+i* linesize];
  2108. }
  2109. *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y + 32*linesize);
  2110. *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+32*linesize);
  2111. *(uint64_t*)(h->top_borders[1][s->mb_x]+0)= *(uint64_t*)(src_y + 33*linesize);
  2112. *(uint64_t*)(h->top_borders[1][s->mb_x]+8)= *(uint64_t*)(src_y +8+33*linesize);
  2113. if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2114. h->left_border[34 ]= h->top_borders[0][s->mb_x][16+7];
  2115. h->left_border[34+ 1]= h->top_borders[1][s->mb_x][16+7];
  2116. h->left_border[34+18 ]= h->top_borders[0][s->mb_x][24+7];
  2117. h->left_border[34+18+1]= h->top_borders[1][s->mb_x][24+7];
  2118. for(i=2; i<18; i++){
  2119. h->left_border[i+34 ]= src_cb[7+i*uvlinesize];
  2120. h->left_border[i+34+18]= src_cr[7+i*uvlinesize];
  2121. }
  2122. *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+16*uvlinesize);
  2123. *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+16*uvlinesize);
  2124. *(uint64_t*)(h->top_borders[1][s->mb_x]+16)= *(uint64_t*)(src_cb+17*uvlinesize);
  2125. *(uint64_t*)(h->top_borders[1][s->mb_x]+24)= *(uint64_t*)(src_cr+17*uvlinesize);
  2126. }
  2127. }
  2128. static inline void xchg_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg){
  2129. MpegEncContext * const s = &h->s;
  2130. int temp8, i;
  2131. uint64_t temp64;
  2132. int deblock_left = (s->mb_x > 0);
  2133. int deblock_top = (s->mb_y > 1);
  2134. tprintf(s->avctx, "xchg_pair_border: src_y:%p src_cb:%p src_cr:%p ls:%d uvls:%d\n", src_y, src_cb, src_cr, linesize, uvlinesize);
  2135. src_y -= 2 * linesize + 1;
  2136. src_cb -= 2 * uvlinesize + 1;
  2137. src_cr -= 2 * uvlinesize + 1;
  2138. #define XCHG(a,b,t,xchg)\
  2139. t= a;\
  2140. if(xchg)\
  2141. a= b;\
  2142. b= t;
  2143. if(deblock_left){
  2144. for(i = (!deblock_top)<<1; i<34; i++){
  2145. XCHG(h->left_border[i ], src_y [i* linesize], temp8, xchg);
  2146. }
  2147. }
  2148. if(deblock_top){
  2149. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
  2150. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
  2151. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+0), *(uint64_t*)(src_y +1 +linesize), temp64, xchg);
  2152. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+8), *(uint64_t*)(src_y +9 +linesize), temp64, 1);
  2153. if(s->mb_x+1 < s->mb_width){
  2154. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
  2155. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x+1]), *(uint64_t*)(src_y +17 +linesize), temp64, 1);
  2156. }
  2157. }
  2158. if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2159. if(deblock_left){
  2160. for(i = (!deblock_top) << 1; i<18; i++){
  2161. XCHG(h->left_border[i+34 ], src_cb[i*uvlinesize], temp8, xchg);
  2162. XCHG(h->left_border[i+34+18], src_cr[i*uvlinesize], temp8, xchg);
  2163. }
  2164. }
  2165. if(deblock_top){
  2166. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
  2167. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
  2168. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+16), *(uint64_t*)(src_cb+1 +uvlinesize), temp64, 1);
  2169. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+24), *(uint64_t*)(src_cr+1 +uvlinesize), temp64, 1);
  2170. }
  2171. }
  2172. }
  2173. static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
  2174. MpegEncContext * const s = &h->s;
  2175. const int mb_x= s->mb_x;
  2176. const int mb_y= s->mb_y;
  2177. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2178. const int mb_type= s->current_picture.mb_type[mb_xy];
  2179. uint8_t *dest_y, *dest_cb, *dest_cr;
  2180. int linesize, uvlinesize /*dct_offset*/;
  2181. int i;
  2182. int *block_offset = &h->block_offset[0];
  2183. const unsigned int bottom = mb_y & 1;
  2184. const int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);
  2185. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  2186. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  2187. dest_y = s->current_picture.data[0] + (mb_y * 16* s->linesize ) + mb_x * 16;
  2188. dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2189. dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2190. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
  2191. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
  2192. if (!simple && MB_FIELD) {
  2193. linesize = h->mb_linesize = s->linesize * 2;
  2194. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2195. block_offset = &h->block_offset[24];
  2196. if(mb_y&1){ //FIXME move out of this func?
  2197. dest_y -= s->linesize*15;
  2198. dest_cb-= s->uvlinesize*7;
  2199. dest_cr-= s->uvlinesize*7;
  2200. }
  2201. if(FRAME_MBAFF) {
  2202. int list;
  2203. for(list=0; list<h->list_count; list++){
  2204. if(!USES_LIST(mb_type, list))
  2205. continue;
  2206. if(IS_16X16(mb_type)){
  2207. int8_t *ref = &h->ref_cache[list][scan8[0]];
  2208. fill_rectangle(ref, 4, 4, 8, 16+*ref^(s->mb_y&1), 1);
  2209. }else{
  2210. for(i=0; i<16; i+=4){
  2211. //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?
  2212. int ref = h->ref_cache[list][scan8[i]];
  2213. if(ref >= 0)
  2214. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, 16+ref^(s->mb_y&1), 1);
  2215. }
  2216. }
  2217. }
  2218. }
  2219. } else {
  2220. linesize = h->mb_linesize = s->linesize;
  2221. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2222. // dct_offset = s->linesize * 16;
  2223. }
  2224. if(transform_bypass){
  2225. idct_dc_add =
  2226. idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  2227. }else if(IS_8x8DCT(mb_type)){
  2228. idct_dc_add = s->dsp.h264_idct8_dc_add;
  2229. idct_add = s->dsp.h264_idct8_add;
  2230. }else{
  2231. idct_dc_add = s->dsp.h264_idct_dc_add;
  2232. idct_add = s->dsp.h264_idct_add;
  2233. }
  2234. if(!simple && FRAME_MBAFF && h->deblocking_filter && IS_INTRA(mb_type)
  2235. && (!bottom || !IS_INTRA(s->current_picture.mb_type[mb_xy-s->mb_stride]))){
  2236. int mbt_y = mb_y&~1;
  2237. uint8_t *top_y = s->current_picture.data[0] + (mbt_y * 16* s->linesize ) + mb_x * 16;
  2238. uint8_t *top_cb = s->current_picture.data[1] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
  2239. uint8_t *top_cr = s->current_picture.data[2] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
  2240. xchg_pair_border(h, top_y, top_cb, top_cr, s->linesize, s->uvlinesize, 1);
  2241. }
  2242. if (!simple && IS_INTRA_PCM(mb_type)) {
  2243. unsigned int x, y;
  2244. // The pixels are stored in h->mb array in the same order as levels,
  2245. // copy them in output in the correct order.
  2246. for(i=0; i<16; i++) {
  2247. for (y=0; y<4; y++) {
  2248. for (x=0; x<4; x++) {
  2249. *(dest_y + block_offset[i] + y*linesize + x) = h->mb[i*16+y*4+x];
  2250. }
  2251. }
  2252. }
  2253. for(i=16; i<16+4; i++) {
  2254. for (y=0; y<4; y++) {
  2255. for (x=0; x<4; x++) {
  2256. *(dest_cb + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
  2257. }
  2258. }
  2259. }
  2260. for(i=20; i<20+4; i++) {
  2261. for (y=0; y<4; y++) {
  2262. for (x=0; x<4; x++) {
  2263. *(dest_cr + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
  2264. }
  2265. }
  2266. }
  2267. } else {
  2268. if(IS_INTRA(mb_type)){
  2269. if(h->deblocking_filter && (simple || !FRAME_MBAFF))
  2270. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
  2271. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2272. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  2273. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  2274. }
  2275. if(IS_INTRA4x4(mb_type)){
  2276. if(simple || !s->encoding){
  2277. if(IS_8x8DCT(mb_type)){
  2278. for(i=0; i<16; i+=4){
  2279. uint8_t * const ptr= dest_y + block_offset[i];
  2280. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2281. const int nnz = h->non_zero_count_cache[ scan8[i] ];
  2282. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  2283. (h->topright_samples_available<<i)&0x4000, linesize);
  2284. if(nnz){
  2285. if(nnz == 1 && h->mb[i*16])
  2286. idct_dc_add(ptr, h->mb + i*16, linesize);
  2287. else
  2288. idct_add(ptr, h->mb + i*16, linesize);
  2289. }
  2290. }
  2291. }else
  2292. for(i=0; i<16; i++){
  2293. uint8_t * const ptr= dest_y + block_offset[i];
  2294. uint8_t *topright;
  2295. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2296. int nnz, tr;
  2297. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  2298. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  2299. assert(mb_y || linesize <= block_offset[i]);
  2300. if(!topright_avail){
  2301. tr= ptr[3 - linesize]*0x01010101;
  2302. topright= (uint8_t*) &tr;
  2303. }else
  2304. topright= ptr + 4 - linesize;
  2305. }else
  2306. topright= NULL;
  2307. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  2308. nnz = h->non_zero_count_cache[ scan8[i] ];
  2309. if(nnz){
  2310. if(is_h264){
  2311. if(nnz == 1 && h->mb[i*16])
  2312. idct_dc_add(ptr, h->mb + i*16, linesize);
  2313. else
  2314. idct_add(ptr, h->mb + i*16, linesize);
  2315. }else
  2316. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
  2317. }
  2318. }
  2319. }
  2320. }else{
  2321. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  2322. if(is_h264){
  2323. if(!transform_bypass)
  2324. h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
  2325. }else
  2326. svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
  2327. }
  2328. if(h->deblocking_filter && (simple || !FRAME_MBAFF))
  2329. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
  2330. }else if(is_h264){
  2331. hl_motion(h, dest_y, dest_cb, dest_cr,
  2332. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  2333. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  2334. s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
  2335. }
  2336. if(!IS_INTRA4x4(mb_type)){
  2337. if(is_h264){
  2338. if(IS_INTRA16x16(mb_type)){
  2339. for(i=0; i<16; i++){
  2340. if(h->non_zero_count_cache[ scan8[i] ])
  2341. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2342. else if(h->mb[i*16])
  2343. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2344. }
  2345. }else{
  2346. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2347. for(i=0; i<16; i+=di){
  2348. int nnz = h->non_zero_count_cache[ scan8[i] ];
  2349. if(nnz){
  2350. if(nnz==1 && h->mb[i*16])
  2351. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2352. else
  2353. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2354. }
  2355. }
  2356. }
  2357. }else{
  2358. for(i=0; i<16; i++){
  2359. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
  2360. uint8_t * const ptr= dest_y + block_offset[i];
  2361. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2362. }
  2363. }
  2364. }
  2365. }
  2366. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2367. uint8_t *dest[2] = {dest_cb, dest_cr};
  2368. if(transform_bypass){
  2369. idct_add = idct_dc_add = s->dsp.add_pixels4;
  2370. }else{
  2371. idct_add = s->dsp.h264_idct_add;
  2372. idct_dc_add = s->dsp.h264_idct_dc_add;
  2373. chroma_dc_dequant_idct_c(h->mb + 16*16, h->chroma_qp[0], h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
  2374. chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->chroma_qp[1], h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
  2375. }
  2376. if(is_h264){
  2377. for(i=16; i<16+8; i++){
  2378. if(h->non_zero_count_cache[ scan8[i] ])
  2379. idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2380. else if(h->mb[i*16])
  2381. idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2382. }
  2383. }else{
  2384. for(i=16; i<16+8; i++){
  2385. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  2386. uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
  2387. svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
  2388. }
  2389. }
  2390. }
  2391. }
  2392. }
  2393. if(h->deblocking_filter) {
  2394. if (!simple && FRAME_MBAFF) {
  2395. //FIXME try deblocking one mb at a time?
  2396. // the reduction in load/storing mvs and such might outweigh the extra backup/xchg_border
  2397. const int mb_y = s->mb_y - 1;
  2398. uint8_t *pair_dest_y, *pair_dest_cb, *pair_dest_cr;
  2399. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2400. const int mb_type_top = s->current_picture.mb_type[mb_xy];
  2401. const int mb_type_bottom= s->current_picture.mb_type[mb_xy+s->mb_stride];
  2402. if (!bottom) return;
  2403. pair_dest_y = s->current_picture.data[0] + (mb_y * 16* s->linesize ) + mb_x * 16;
  2404. pair_dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2405. pair_dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2406. if(IS_INTRA(mb_type_top | mb_type_bottom))
  2407. xchg_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize, 0);
  2408. backup_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize);
  2409. // deblock a pair
  2410. // top
  2411. s->mb_y--;
  2412. tprintf(h->s.avctx, "call mbaff filter_mb mb_x:%d mb_y:%d pair_dest_y = %p, dest_y = %p\n", mb_x, mb_y, pair_dest_y, dest_y);
  2413. fill_caches(h, mb_type_top, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2414. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2415. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2416. filter_mb(h, mb_x, mb_y, pair_dest_y, pair_dest_cb, pair_dest_cr, linesize, uvlinesize);
  2417. // bottom
  2418. s->mb_y++;
  2419. tprintf(h->s.avctx, "call mbaff filter_mb\n");
  2420. fill_caches(h, mb_type_bottom, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2421. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
  2422. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
  2423. filter_mb(h, mb_x, mb_y+1, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2424. } else {
  2425. tprintf(h->s.avctx, "call filter_mb\n");
  2426. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
  2427. fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2428. filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2429. }
  2430. }
  2431. }
  2432. /**
  2433. * Process a macroblock; this case avoids checks for expensive uncommon cases.
  2434. */
  2435. static void hl_decode_mb_simple(H264Context *h){
  2436. hl_decode_mb_internal(h, 1);
  2437. }
  2438. /**
  2439. * Process a macroblock; this handles edge cases, such as interlacing.
  2440. */
  2441. static void av_noinline hl_decode_mb_complex(H264Context *h){
  2442. hl_decode_mb_internal(h, 0);
  2443. }
  2444. static void hl_decode_mb(H264Context *h){
  2445. MpegEncContext * const s = &h->s;
  2446. const int mb_x= s->mb_x;
  2447. const int mb_y= s->mb_y;
  2448. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2449. const int mb_type= s->current_picture.mb_type[mb_xy];
  2450. int is_complex = FRAME_MBAFF || MB_FIELD || IS_INTRA_PCM(mb_type) || s->codec_id != CODEC_ID_H264 || (ENABLE_GRAY && (s->flags&CODEC_FLAG_GRAY)) || s->encoding;
  2451. if(!s->decode)
  2452. return;
  2453. if (is_complex)
  2454. hl_decode_mb_complex(h);
  2455. else hl_decode_mb_simple(h);
  2456. }
  2457. static void pic_as_field(Picture *pic, const int parity){
  2458. int i;
  2459. for (i = 0; i < 4; ++i) {
  2460. if (parity == PICT_BOTTOM_FIELD)
  2461. pic->data[i] += pic->linesize[i];
  2462. pic->reference = parity;
  2463. pic->linesize[i] *= 2;
  2464. }
  2465. }
  2466. static int split_field_copy(Picture *dest, Picture *src,
  2467. int parity, int id_add){
  2468. int match = !!(src->reference & parity);
  2469. if (match) {
  2470. *dest = *src;
  2471. pic_as_field(dest, parity);
  2472. dest->pic_id *= 2;
  2473. dest->pic_id += id_add;
  2474. }
  2475. return match;
  2476. }
  2477. /**
  2478. * Split one reference list into field parts, interleaving by parity
  2479. * as per H.264 spec section 8.2.4.2.5. Output fields have their data pointers
  2480. * set to look at the actual start of data for that field.
  2481. *
  2482. * @param dest output list
  2483. * @param dest_len maximum number of fields to put in dest
  2484. * @param src the source reference list containing fields and/or field pairs
  2485. * (aka short_ref/long_ref, or
  2486. * refFrameListXShortTerm/refFrameListLongTerm in spec-speak)
  2487. * @param src_len number of Picture's in source (pairs and unmatched fields)
  2488. * @param parity the parity of the picture being decoded/needing
  2489. * these ref pics (PICT_{TOP,BOTTOM}_FIELD)
  2490. * @return number of fields placed in dest
  2491. */
  2492. static int split_field_half_ref_list(Picture *dest, int dest_len,
  2493. Picture *src, int src_len, int parity){
  2494. int same_parity = 1;
  2495. int same_i = 0;
  2496. int opp_i = 0;
  2497. int out_i;
  2498. int field_output;
  2499. for (out_i = 0; out_i < dest_len; out_i += field_output) {
  2500. if (same_parity && same_i < src_len) {
  2501. field_output = split_field_copy(dest + out_i, src + same_i,
  2502. parity, 1);
  2503. same_parity = !field_output;
  2504. same_i++;
  2505. } else if (opp_i < src_len) {
  2506. field_output = split_field_copy(dest + out_i, src + opp_i,
  2507. PICT_FRAME - parity, 0);
  2508. same_parity = field_output;
  2509. opp_i++;
  2510. } else {
  2511. break;
  2512. }
  2513. }
  2514. return out_i;
  2515. }
  2516. /**
  2517. * Split the reference frame list into a reference field list.
  2518. * This implements H.264 spec 8.2.4.2.5 for a combined input list.
  2519. * The input list contains both reference field pairs and
  2520. * unmatched reference fields; it is ordered as spec describes
  2521. * RefPicListX for frames in 8.2.4.2.1 and 8.2.4.2.3, except that
  2522. * unmatched field pairs are also present. Conceptually this is equivalent
  2523. * to concatenation of refFrameListXShortTerm with refFrameListLongTerm.
  2524. *
  2525. * @param dest output reference list where ordered fields are to be placed
  2526. * @param dest_len max number of fields to place at dest
  2527. * @param src source reference list, as described above
  2528. * @param src_len number of pictures (pairs and unmatched fields) in src
  2529. * @param parity parity of field being currently decoded
  2530. * (one of PICT_{TOP,BOTTOM}_FIELD)
  2531. * @param long_i index into src array that holds first long reference picture,
  2532. * or src_len if no long refs present.
  2533. */
  2534. static int split_field_ref_list(Picture *dest, int dest_len,
  2535. Picture *src, int src_len,
  2536. int parity, int long_i){
  2537. int i = split_field_half_ref_list(dest, dest_len, src, long_i, parity);
  2538. dest += i;
  2539. dest_len -= i;
  2540. i += split_field_half_ref_list(dest, dest_len, src + long_i,
  2541. src_len - long_i, parity);
  2542. return i;
  2543. }
  2544. /**
  2545. * fills the default_ref_list.
  2546. */
  2547. static int fill_default_ref_list(H264Context *h){
  2548. MpegEncContext * const s = &h->s;
  2549. int i;
  2550. int smallest_poc_greater_than_current = -1;
  2551. int structure_sel;
  2552. Picture sorted_short_ref[32];
  2553. Picture field_entry_list[2][32];
  2554. Picture *frame_list[2];
  2555. if (FIELD_PICTURE) {
  2556. structure_sel = PICT_FRAME;
  2557. frame_list[0] = field_entry_list[0];
  2558. frame_list[1] = field_entry_list[1];
  2559. } else {
  2560. structure_sel = 0;
  2561. frame_list[0] = h->default_ref_list[0];
  2562. frame_list[1] = h->default_ref_list[1];
  2563. }
  2564. if(h->slice_type==B_TYPE){
  2565. int list;
  2566. int len[2];
  2567. int short_len[2];
  2568. int out_i;
  2569. int limit= INT_MIN;
  2570. /* sort frame according to poc in B slice */
  2571. for(out_i=0; out_i<h->short_ref_count; out_i++){
  2572. int best_i=INT_MIN;
  2573. int best_poc=INT_MAX;
  2574. for(i=0; i<h->short_ref_count; i++){
  2575. const int poc= h->short_ref[i]->poc;
  2576. if(poc > limit && poc < best_poc){
  2577. best_poc= poc;
  2578. best_i= i;
  2579. }
  2580. }
  2581. assert(best_i != INT_MIN);
  2582. limit= best_poc;
  2583. sorted_short_ref[out_i]= *h->short_ref[best_i];
  2584. tprintf(h->s.avctx, "sorted poc: %d->%d poc:%d fn:%d\n", best_i, out_i, sorted_short_ref[out_i].poc, sorted_short_ref[out_i].frame_num);
  2585. if (-1 == smallest_poc_greater_than_current) {
  2586. if (h->short_ref[best_i]->poc >= s->current_picture_ptr->poc) {
  2587. smallest_poc_greater_than_current = out_i;
  2588. }
  2589. }
  2590. }
  2591. tprintf(h->s.avctx, "current poc: %d, smallest_poc_greater_than_current: %d\n", s->current_picture_ptr->poc, smallest_poc_greater_than_current);
  2592. // find the largest poc
  2593. for(list=0; list<2; list++){
  2594. int index = 0;
  2595. int j= -99;
  2596. int step= list ? -1 : 1;
  2597. for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++, j+=step) {
  2598. int sel;
  2599. while(j<0 || j>= h->short_ref_count){
  2600. if(j != -99 && step == (list ? -1 : 1))
  2601. return -1;
  2602. step = -step;
  2603. j= smallest_poc_greater_than_current + (step>>1);
  2604. }
  2605. sel = sorted_short_ref[j].reference | structure_sel;
  2606. if(sel != PICT_FRAME) continue;
  2607. frame_list[list][index ]= sorted_short_ref[j];
  2608. frame_list[list][index++].pic_id= sorted_short_ref[j].frame_num;
  2609. }
  2610. short_len[list] = index;
  2611. for(i = 0; i < 16 && index < h->ref_count[ list ]; i++){
  2612. int sel;
  2613. if(h->long_ref[i] == NULL) continue;
  2614. sel = h->long_ref[i]->reference | structure_sel;
  2615. if(sel != PICT_FRAME) continue;
  2616. frame_list[ list ][index ]= *h->long_ref[i];
  2617. frame_list[ list ][index++].pic_id= i;;
  2618. }
  2619. len[list] = index;
  2620. if(list && (smallest_poc_greater_than_current<=0 || smallest_poc_greater_than_current>=h->short_ref_count) && (1 < index)){
  2621. // swap the two first elements of L1 when
  2622. // L0 and L1 are identical
  2623. Picture temp= frame_list[1][0];
  2624. frame_list[1][0] = frame_list[1][1];
  2625. frame_list[1][1] = temp;
  2626. }
  2627. }
  2628. for(list=0; list<2; list++){
  2629. if (FIELD_PICTURE)
  2630. len[list] = split_field_ref_list(h->default_ref_list[list],
  2631. h->ref_count[list],
  2632. frame_list[list],
  2633. len[list],
  2634. s->picture_structure,
  2635. short_len[list]);
  2636. if(len[list] < h->ref_count[ list ])
  2637. memset(&h->default_ref_list[list][len[list]], 0, sizeof(Picture)*(h->ref_count[ list ] - len[list]));
  2638. }
  2639. }else{
  2640. int index=0;
  2641. int short_len;
  2642. for(i=0; i<h->short_ref_count; i++){
  2643. int sel;
  2644. sel = h->short_ref[i]->reference | structure_sel;
  2645. if(sel != PICT_FRAME) continue;
  2646. frame_list[0][index ]= *h->short_ref[i];
  2647. frame_list[0][index++].pic_id= h->short_ref[i]->frame_num;
  2648. }
  2649. short_len = index;
  2650. for(i = 0; i < 16; i++){
  2651. int sel;
  2652. if(h->long_ref[i] == NULL) continue;
  2653. sel = h->long_ref[i]->reference | structure_sel;
  2654. if(sel != PICT_FRAME) continue;
  2655. frame_list[0][index ]= *h->long_ref[i];
  2656. frame_list[0][index++].pic_id= i;;
  2657. }
  2658. if (FIELD_PICTURE)
  2659. index = split_field_ref_list(h->default_ref_list[0],
  2660. h->ref_count[0], frame_list[0],
  2661. index, s->picture_structure,
  2662. short_len);
  2663. if(index < h->ref_count[0])
  2664. memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index));
  2665. }
  2666. #ifdef TRACE
  2667. for (i=0; i<h->ref_count[0]; i++) {
  2668. tprintf(h->s.avctx, "List0: %s fn:%d 0x%p\n", (h->default_ref_list[0][i].long_ref ? "LT" : "ST"), h->default_ref_list[0][i].pic_id, h->default_ref_list[0][i].data[0]);
  2669. }
  2670. if(h->slice_type==B_TYPE){
  2671. for (i=0; i<h->ref_count[1]; i++) {
  2672. tprintf(h->s.avctx, "List1: %s fn:%d 0x%p\n", (h->default_ref_list[1][i].long_ref ? "LT" : "ST"), h->default_ref_list[1][i].pic_id, h->default_ref_list[0][i].data[0]);
  2673. }
  2674. }
  2675. #endif
  2676. return 0;
  2677. }
  2678. static void print_short_term(H264Context *h);
  2679. static void print_long_term(H264Context *h);
  2680. /**
  2681. * Extract structure information about the picture described by pic_num in
  2682. * the current decoding context (frame or field). Note that pic_num is
  2683. * picture number without wrapping (so, 0<=pic_num<max_pic_num).
  2684. * @param pic_num picture number for which to extract structure information
  2685. * @param structure one of PICT_XXX describing structure of picture
  2686. * with pic_num
  2687. * @return frame number (short term) or long term index of picture
  2688. * described by pic_num
  2689. */
  2690. static int pic_num_extract(H264Context *h, int pic_num, int *structure){
  2691. MpegEncContext * const s = &h->s;
  2692. *structure = s->picture_structure;
  2693. if(FIELD_PICTURE){
  2694. if (!(pic_num & 1))
  2695. /* opposite field */
  2696. *structure ^= PICT_FRAME;
  2697. pic_num >>= 1;
  2698. }
  2699. return pic_num;
  2700. }
  2701. static int decode_ref_pic_list_reordering(H264Context *h){
  2702. MpegEncContext * const s = &h->s;
  2703. int list, index, pic_structure;
  2704. print_short_term(h);
  2705. print_long_term(h);
  2706. if(h->slice_type==I_TYPE || h->slice_type==SI_TYPE) return 0; //FIXME move before func
  2707. for(list=0; list<h->list_count; list++){
  2708. memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
  2709. if(get_bits1(&s->gb)){
  2710. int pred= h->curr_pic_num;
  2711. for(index=0; ; index++){
  2712. unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
  2713. unsigned int pic_id;
  2714. int i;
  2715. Picture *ref = NULL;
  2716. if(reordering_of_pic_nums_idc==3)
  2717. break;
  2718. if(index >= h->ref_count[list]){
  2719. av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
  2720. return -1;
  2721. }
  2722. if(reordering_of_pic_nums_idc<3){
  2723. if(reordering_of_pic_nums_idc<2){
  2724. const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
  2725. int frame_num;
  2726. if(abs_diff_pic_num > h->max_pic_num){
  2727. av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
  2728. return -1;
  2729. }
  2730. if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
  2731. else pred+= abs_diff_pic_num;
  2732. pred &= h->max_pic_num - 1;
  2733. frame_num = pic_num_extract(h, pred, &pic_structure);
  2734. for(i= h->short_ref_count-1; i>=0; i--){
  2735. ref = h->short_ref[i];
  2736. assert(ref->reference);
  2737. assert(!ref->long_ref);
  2738. if(ref->data[0] != NULL &&
  2739. ref->frame_num == frame_num &&
  2740. (ref->reference & pic_structure) &&
  2741. ref->long_ref == 0) // ignore non existing pictures by testing data[0] pointer
  2742. break;
  2743. }
  2744. if(i>=0)
  2745. ref->pic_id= pred;
  2746. }else{
  2747. int long_idx;
  2748. pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
  2749. long_idx= pic_num_extract(h, pic_id, &pic_structure);
  2750. if(long_idx>31){
  2751. av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
  2752. return -1;
  2753. }
  2754. ref = h->long_ref[long_idx];
  2755. assert(!(ref && !ref->reference));
  2756. if(ref && (ref->reference & pic_structure)){
  2757. ref->pic_id= pic_id;
  2758. assert(ref->long_ref);
  2759. i=0;
  2760. }else{
  2761. i=-1;
  2762. }
  2763. }
  2764. if (i < 0) {
  2765. av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
  2766. memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
  2767. } else {
  2768. for(i=index; i+1<h->ref_count[list]; i++){
  2769. if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
  2770. break;
  2771. }
  2772. for(; i > index; i--){
  2773. h->ref_list[list][i]= h->ref_list[list][i-1];
  2774. }
  2775. h->ref_list[list][index]= *ref;
  2776. if (FIELD_PICTURE){
  2777. pic_as_field(&h->ref_list[list][index], pic_structure);
  2778. }
  2779. }
  2780. }else{
  2781. av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
  2782. return -1;
  2783. }
  2784. }
  2785. }
  2786. }
  2787. for(list=0; list<h->list_count; list++){
  2788. for(index= 0; index < h->ref_count[list]; index++){
  2789. if(!h->ref_list[list][index].data[0])
  2790. h->ref_list[list][index]= s->current_picture;
  2791. }
  2792. }
  2793. if(h->slice_type==B_TYPE && !h->direct_spatial_mv_pred)
  2794. direct_dist_scale_factor(h);
  2795. direct_ref_list_init(h);
  2796. return 0;
  2797. }
  2798. static void fill_mbaff_ref_list(H264Context *h){
  2799. int list, i, j;
  2800. for(list=0; list<2; list++){ //FIXME try list_count
  2801. for(i=0; i<h->ref_count[list]; i++){
  2802. Picture *frame = &h->ref_list[list][i];
  2803. Picture *field = &h->ref_list[list][16+2*i];
  2804. field[0] = *frame;
  2805. for(j=0; j<3; j++)
  2806. field[0].linesize[j] <<= 1;
  2807. field[0].reference = PICT_TOP_FIELD;
  2808. field[1] = field[0];
  2809. for(j=0; j<3; j++)
  2810. field[1].data[j] += frame->linesize[j];
  2811. field[1].reference = PICT_BOTTOM_FIELD;
  2812. h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
  2813. h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
  2814. for(j=0; j<2; j++){
  2815. h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
  2816. h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
  2817. }
  2818. }
  2819. }
  2820. for(j=0; j<h->ref_count[1]; j++){
  2821. for(i=0; i<h->ref_count[0]; i++)
  2822. h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
  2823. memcpy(h->implicit_weight[16+2*j], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2824. memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2825. }
  2826. }
  2827. static int pred_weight_table(H264Context *h){
  2828. MpegEncContext * const s = &h->s;
  2829. int list, i;
  2830. int luma_def, chroma_def;
  2831. h->use_weight= 0;
  2832. h->use_weight_chroma= 0;
  2833. h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
  2834. h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
  2835. luma_def = 1<<h->luma_log2_weight_denom;
  2836. chroma_def = 1<<h->chroma_log2_weight_denom;
  2837. for(list=0; list<2; list++){
  2838. for(i=0; i<h->ref_count[list]; i++){
  2839. int luma_weight_flag, chroma_weight_flag;
  2840. luma_weight_flag= get_bits1(&s->gb);
  2841. if(luma_weight_flag){
  2842. h->luma_weight[list][i]= get_se_golomb(&s->gb);
  2843. h->luma_offset[list][i]= get_se_golomb(&s->gb);
  2844. if( h->luma_weight[list][i] != luma_def
  2845. || h->luma_offset[list][i] != 0)
  2846. h->use_weight= 1;
  2847. }else{
  2848. h->luma_weight[list][i]= luma_def;
  2849. h->luma_offset[list][i]= 0;
  2850. }
  2851. chroma_weight_flag= get_bits1(&s->gb);
  2852. if(chroma_weight_flag){
  2853. int j;
  2854. for(j=0; j<2; j++){
  2855. h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
  2856. h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
  2857. if( h->chroma_weight[list][i][j] != chroma_def
  2858. || h->chroma_offset[list][i][j] != 0)
  2859. h->use_weight_chroma= 1;
  2860. }
  2861. }else{
  2862. int j;
  2863. for(j=0; j<2; j++){
  2864. h->chroma_weight[list][i][j]= chroma_def;
  2865. h->chroma_offset[list][i][j]= 0;
  2866. }
  2867. }
  2868. }
  2869. if(h->slice_type != B_TYPE) break;
  2870. }
  2871. h->use_weight= h->use_weight || h->use_weight_chroma;
  2872. return 0;
  2873. }
  2874. static void implicit_weight_table(H264Context *h){
  2875. MpegEncContext * const s = &h->s;
  2876. int ref0, ref1;
  2877. int cur_poc = s->current_picture_ptr->poc;
  2878. if( h->ref_count[0] == 1 && h->ref_count[1] == 1
  2879. && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
  2880. h->use_weight= 0;
  2881. h->use_weight_chroma= 0;
  2882. return;
  2883. }
  2884. h->use_weight= 2;
  2885. h->use_weight_chroma= 2;
  2886. h->luma_log2_weight_denom= 5;
  2887. h->chroma_log2_weight_denom= 5;
  2888. for(ref0=0; ref0 < h->ref_count[0]; ref0++){
  2889. int poc0 = h->ref_list[0][ref0].poc;
  2890. for(ref1=0; ref1 < h->ref_count[1]; ref1++){
  2891. int poc1 = h->ref_list[1][ref1].poc;
  2892. int td = av_clip(poc1 - poc0, -128, 127);
  2893. if(td){
  2894. int tb = av_clip(cur_poc - poc0, -128, 127);
  2895. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2896. int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
  2897. if(dist_scale_factor < -64 || dist_scale_factor > 128)
  2898. h->implicit_weight[ref0][ref1] = 32;
  2899. else
  2900. h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
  2901. }else
  2902. h->implicit_weight[ref0][ref1] = 32;
  2903. }
  2904. }
  2905. }
  2906. /**
  2907. * Mark a picture as no longer needed for reference. The refmask
  2908. * argument allows unreferencing of individual fields or the whole frame.
  2909. * If the picture becomes entirely unreferenced, but is being held for
  2910. * display purposes, it is marked as such.
  2911. * @param refmask mask of fields to unreference; the mask is bitwise
  2912. * anded with the reference marking of pic
  2913. * @return non-zero if pic becomes entirely unreferenced (except possibly
  2914. * for display purposes) zero if one of the fields remains in
  2915. * reference
  2916. */
  2917. static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
  2918. int i;
  2919. if (pic->reference &= refmask) {
  2920. return 0;
  2921. } else {
  2922. if(pic == h->delayed_output_pic)
  2923. pic->reference=DELAYED_PIC_REF;
  2924. else{
  2925. for(i = 0; h->delayed_pic[i]; i++)
  2926. if(pic == h->delayed_pic[i]){
  2927. pic->reference=DELAYED_PIC_REF;
  2928. break;
  2929. }
  2930. }
  2931. return 1;
  2932. }
  2933. }
  2934. /**
  2935. * instantaneous decoder refresh.
  2936. */
  2937. static void idr(H264Context *h){
  2938. int i;
  2939. for(i=0; i<16; i++){
  2940. if (h->long_ref[i] != NULL) {
  2941. unreference_pic(h, h->long_ref[i], 0);
  2942. h->long_ref[i]= NULL;
  2943. }
  2944. }
  2945. h->long_ref_count=0;
  2946. for(i=0; i<h->short_ref_count; i++){
  2947. unreference_pic(h, h->short_ref[i], 0);
  2948. h->short_ref[i]= NULL;
  2949. }
  2950. h->short_ref_count=0;
  2951. }
  2952. /* forget old pics after a seek */
  2953. static void flush_dpb(AVCodecContext *avctx){
  2954. H264Context *h= avctx->priv_data;
  2955. int i;
  2956. for(i=0; i<16; i++) {
  2957. if(h->delayed_pic[i])
  2958. h->delayed_pic[i]->reference= 0;
  2959. h->delayed_pic[i]= NULL;
  2960. }
  2961. if(h->delayed_output_pic)
  2962. h->delayed_output_pic->reference= 0;
  2963. h->delayed_output_pic= NULL;
  2964. idr(h);
  2965. if(h->s.current_picture_ptr)
  2966. h->s.current_picture_ptr->reference= 0;
  2967. h->s.first_field= 0;
  2968. }
  2969. /**
  2970. * Find a Picture in the short term reference list by frame number.
  2971. * @param frame_num frame number to search for
  2972. * @param idx the index into h->short_ref where returned picture is found
  2973. * undefined if no picture found.
  2974. * @return pointer to the found picture, or NULL if no pic with the provided
  2975. * frame number is found
  2976. */
  2977. static Picture * find_short(H264Context *h, int frame_num, int *idx){
  2978. MpegEncContext * const s = &h->s;
  2979. int i;
  2980. for(i=0; i<h->short_ref_count; i++){
  2981. Picture *pic= h->short_ref[i];
  2982. if(s->avctx->debug&FF_DEBUG_MMCO)
  2983. av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
  2984. if(pic->frame_num == frame_num) {
  2985. *idx = i;
  2986. return pic;
  2987. }
  2988. }
  2989. return NULL;
  2990. }
  2991. /**
  2992. * Remove a picture from the short term reference list by its index in
  2993. * that list. This does no checking on the provided index; it is assumed
  2994. * to be valid. Other list entries are shifted down.
  2995. * @param i index into h->short_ref of picture to remove.
  2996. */
  2997. static void remove_short_at_index(H264Context *h, int i){
  2998. assert(i > 0 && i < h->short_ref_count);
  2999. h->short_ref[i]= NULL;
  3000. if (--h->short_ref_count)
  3001. memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
  3002. }
  3003. /**
  3004. *
  3005. * @return the removed picture or NULL if an error occurs
  3006. */
  3007. static Picture * remove_short(H264Context *h, int frame_num){
  3008. MpegEncContext * const s = &h->s;
  3009. Picture *pic;
  3010. int i;
  3011. if(s->avctx->debug&FF_DEBUG_MMCO)
  3012. av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
  3013. pic = find_short(h, frame_num, &i);
  3014. if (pic)
  3015. remove_short_at_index(h, i);
  3016. return pic;
  3017. }
  3018. /**
  3019. * Remove a picture from the long term reference list by its index in
  3020. * that list. This does no checking on the provided index; it is assumed
  3021. * to be valid. The removed entry is set to NULL. Other entries are unaffected.
  3022. * @param i index into h->long_ref of picture to remove.
  3023. */
  3024. static void remove_long_at_index(H264Context *h, int i){
  3025. h->long_ref[i]= NULL;
  3026. h->long_ref_count--;
  3027. }
  3028. /**
  3029. *
  3030. * @return the removed picture or NULL if an error occurs
  3031. */
  3032. static Picture * remove_long(H264Context *h, int i){
  3033. Picture *pic;
  3034. pic= h->long_ref[i];
  3035. if (pic)
  3036. remove_long_at_index(h, i);
  3037. return pic;
  3038. }
  3039. /**
  3040. * print short term list
  3041. */
  3042. static void print_short_term(H264Context *h) {
  3043. uint32_t i;
  3044. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  3045. av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
  3046. for(i=0; i<h->short_ref_count; i++){
  3047. Picture *pic= h->short_ref[i];
  3048. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  3049. }
  3050. }
  3051. }
  3052. /**
  3053. * print long term list
  3054. */
  3055. static void print_long_term(H264Context *h) {
  3056. uint32_t i;
  3057. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  3058. av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
  3059. for(i = 0; i < 16; i++){
  3060. Picture *pic= h->long_ref[i];
  3061. if (pic) {
  3062. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  3063. }
  3064. }
  3065. }
  3066. }
  3067. /**
  3068. * Executes the reference picture marking (memory management control operations).
  3069. */
  3070. static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
  3071. MpegEncContext * const s = &h->s;
  3072. int i, j;
  3073. int current_ref_assigned=0;
  3074. Picture *pic;
  3075. if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
  3076. av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
  3077. for(i=0; i<mmco_count; i++){
  3078. int structure, frame_num, unref_pic;
  3079. if(s->avctx->debug&FF_DEBUG_MMCO)
  3080. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode, h->mmco[i].short_pic_num, h->mmco[i].long_arg);
  3081. switch(mmco[i].opcode){
  3082. case MMCO_SHORT2UNUSED:
  3083. if(s->avctx->debug&FF_DEBUG_MMCO)
  3084. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n", h->mmco[i].short_pic_num, h->short_ref_count);
  3085. frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
  3086. pic = find_short(h, frame_num, &j);
  3087. if (pic) {
  3088. if (unreference_pic(h, pic, structure ^ PICT_FRAME))
  3089. remove_short_at_index(h, j);
  3090. } else if(s->avctx->debug&FF_DEBUG_MMCO)
  3091. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short failure\n");
  3092. break;
  3093. case MMCO_SHORT2LONG:
  3094. if (FIELD_PICTURE && mmco[i].long_arg < h->long_ref_count &&
  3095. h->long_ref[mmco[i].long_arg]->frame_num ==
  3096. mmco[i].short_pic_num / 2) {
  3097. /* do nothing, we've already moved this field pair. */
  3098. } else {
  3099. int frame_num = mmco[i].short_pic_num >> FIELD_PICTURE;
  3100. pic= remove_long(h, mmco[i].long_arg);
  3101. if(pic) unreference_pic(h, pic, 0);
  3102. h->long_ref[ mmco[i].long_arg ]= remove_short(h, frame_num);
  3103. if (h->long_ref[ mmco[i].long_arg ]){
  3104. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  3105. h->long_ref_count++;
  3106. }
  3107. }
  3108. break;
  3109. case MMCO_LONG2UNUSED:
  3110. j = pic_num_extract(h, mmco[i].long_arg, &structure);
  3111. pic = h->long_ref[j];
  3112. if (pic) {
  3113. if (unreference_pic(h, pic, structure ^ PICT_FRAME))
  3114. remove_long_at_index(h, j);
  3115. } else if(s->avctx->debug&FF_DEBUG_MMCO)
  3116. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
  3117. break;
  3118. case MMCO_LONG:
  3119. unref_pic = 1;
  3120. if (FIELD_PICTURE && !s->first_field) {
  3121. if (h->long_ref[mmco[i].long_arg] == s->current_picture_ptr) {
  3122. /* Just mark second field as referenced */
  3123. unref_pic = 0;
  3124. } else if (s->current_picture_ptr->reference) {
  3125. /* First field in pair is in short term list or
  3126. * at a different long term index.
  3127. * This is not allowed; see 7.4.3, notes 2 and 3.
  3128. * Report the problem and keep the pair where it is,
  3129. * and mark this field valid.
  3130. */
  3131. av_log(h->s.avctx, AV_LOG_ERROR,
  3132. "illegal long term reference assignment for second "
  3133. "field in complementary field pair (first field is "
  3134. "short term or has non-matching long index)\n");
  3135. unref_pic = 0;
  3136. }
  3137. }
  3138. if (unref_pic) {
  3139. pic= remove_long(h, mmco[i].long_arg);
  3140. if(pic) unreference_pic(h, pic, 0);
  3141. h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
  3142. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  3143. h->long_ref_count++;
  3144. }
  3145. s->current_picture_ptr->reference |= s->picture_structure;
  3146. current_ref_assigned=1;
  3147. break;
  3148. case MMCO_SET_MAX_LONG:
  3149. assert(mmco[i].long_arg <= 16);
  3150. // just remove the long term which index is greater than new max
  3151. for(j = mmco[i].long_arg; j<16; j++){
  3152. pic = remove_long(h, j);
  3153. if (pic) unreference_pic(h, pic, 0);
  3154. }
  3155. break;
  3156. case MMCO_RESET:
  3157. while(h->short_ref_count){
  3158. pic= remove_short(h, h->short_ref[0]->frame_num);
  3159. if(pic) unreference_pic(h, pic, 0);
  3160. }
  3161. for(j = 0; j < 16; j++) {
  3162. pic= remove_long(h, j);
  3163. if(pic) unreference_pic(h, pic, 0);
  3164. }
  3165. break;
  3166. default: assert(0);
  3167. }
  3168. }
  3169. if (!current_ref_assigned && FIELD_PICTURE &&
  3170. !s->first_field && s->current_picture_ptr->reference) {
  3171. /* Second field of complementary field pair; the first field of
  3172. * which is already referenced. If short referenced, it
  3173. * should be first entry in short_ref. If not, it must exist
  3174. * in long_ref; trying to put it on the short list here is an
  3175. * error in the encoded bit stream (ref: 7.4.3, NOTE 2 and 3).
  3176. */
  3177. if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
  3178. /* Just mark the second field valid */
  3179. s->current_picture_ptr->reference = PICT_FRAME;
  3180. } else if (s->current_picture_ptr->long_ref) {
  3181. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
  3182. "assignment for second field "
  3183. "in complementary field pair "
  3184. "(first field is long term)\n");
  3185. } else {
  3186. /*
  3187. * First field in reference, but not in any sensible place on our
  3188. * reference lists. This shouldn't happen unless reference
  3189. * handling somewhere else is wrong.
  3190. */
  3191. assert(0);
  3192. }
  3193. current_ref_assigned = 1;
  3194. }
  3195. if(!current_ref_assigned){
  3196. pic= remove_short(h, s->current_picture_ptr->frame_num);
  3197. if(pic){
  3198. unreference_pic(h, pic, 0);
  3199. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
  3200. }
  3201. if(h->short_ref_count)
  3202. memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
  3203. h->short_ref[0]= s->current_picture_ptr;
  3204. h->short_ref[0]->long_ref=0;
  3205. h->short_ref_count++;
  3206. s->current_picture_ptr->reference |= s->picture_structure;
  3207. }
  3208. print_short_term(h);
  3209. print_long_term(h);
  3210. return 0;
  3211. }
  3212. static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
  3213. MpegEncContext * const s = &h->s;
  3214. int i;
  3215. if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
  3216. s->broken_link= get_bits1(gb) -1;
  3217. h->mmco[0].long_arg= get_bits1(gb) - 1; // current_long_term_idx
  3218. if(h->mmco[0].long_arg == -1)
  3219. h->mmco_index= 0;
  3220. else{
  3221. h->mmco[0].opcode= MMCO_LONG;
  3222. h->mmco_index= 1;
  3223. }
  3224. }else{
  3225. if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
  3226. for(i= 0; i<MAX_MMCO_COUNT; i++) {
  3227. MMCOOpcode opcode= get_ue_golomb(gb);
  3228. h->mmco[i].opcode= opcode;
  3229. if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
  3230. h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
  3231. /* if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
  3232. av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
  3233. return -1;
  3234. }*/
  3235. }
  3236. if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
  3237. unsigned int long_arg= get_ue_golomb(gb);
  3238. if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
  3239. av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
  3240. return -1;
  3241. }
  3242. h->mmco[i].long_arg= long_arg;
  3243. }
  3244. if(opcode > (unsigned)MMCO_LONG){
  3245. av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
  3246. return -1;
  3247. }
  3248. if(opcode == MMCO_END)
  3249. break;
  3250. }
  3251. h->mmco_index= i;
  3252. }else{
  3253. assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
  3254. if(h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
  3255. !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
  3256. h->mmco[0].opcode= MMCO_SHORT2UNUSED;
  3257. h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
  3258. h->mmco_index= 1;
  3259. if (FIELD_PICTURE) {
  3260. h->mmco[0].short_pic_num *= 2;
  3261. h->mmco[1].opcode= MMCO_SHORT2UNUSED;
  3262. h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
  3263. h->mmco_index= 2;
  3264. }
  3265. }else
  3266. h->mmco_index= 0;
  3267. }
  3268. }
  3269. return 0;
  3270. }
  3271. static int init_poc(H264Context *h){
  3272. MpegEncContext * const s = &h->s;
  3273. const int max_frame_num= 1<<h->sps.log2_max_frame_num;
  3274. int field_poc[2];
  3275. if(h->nal_unit_type == NAL_IDR_SLICE){
  3276. h->frame_num_offset= 0;
  3277. }else{
  3278. if(h->frame_num < h->prev_frame_num)
  3279. h->frame_num_offset= h->prev_frame_num_offset + max_frame_num;
  3280. else
  3281. h->frame_num_offset= h->prev_frame_num_offset;
  3282. }
  3283. if(h->sps.poc_type==0){
  3284. const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
  3285. if(h->nal_unit_type == NAL_IDR_SLICE){
  3286. h->prev_poc_msb=
  3287. h->prev_poc_lsb= 0;
  3288. }
  3289. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
  3290. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  3291. else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
  3292. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  3293. else
  3294. h->poc_msb = h->prev_poc_msb;
  3295. //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
  3296. field_poc[0] =
  3297. field_poc[1] = h->poc_msb + h->poc_lsb;
  3298. if(s->picture_structure == PICT_FRAME)
  3299. field_poc[1] += h->delta_poc_bottom;
  3300. }else if(h->sps.poc_type==1){
  3301. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  3302. int i;
  3303. if(h->sps.poc_cycle_length != 0)
  3304. abs_frame_num = h->frame_num_offset + h->frame_num;
  3305. else
  3306. abs_frame_num = 0;
  3307. if(h->nal_ref_idc==0 && abs_frame_num > 0)
  3308. abs_frame_num--;
  3309. expected_delta_per_poc_cycle = 0;
  3310. for(i=0; i < h->sps.poc_cycle_length; i++)
  3311. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
  3312. if(abs_frame_num > 0){
  3313. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  3314. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  3315. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  3316. for(i = 0; i <= frame_num_in_poc_cycle; i++)
  3317. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
  3318. } else
  3319. expectedpoc = 0;
  3320. if(h->nal_ref_idc == 0)
  3321. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  3322. field_poc[0] = expectedpoc + h->delta_poc[0];
  3323. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  3324. if(s->picture_structure == PICT_FRAME)
  3325. field_poc[1] += h->delta_poc[1];
  3326. }else{
  3327. int poc;
  3328. if(h->nal_unit_type == NAL_IDR_SLICE){
  3329. poc= 0;
  3330. }else{
  3331. if(h->nal_ref_idc) poc= 2*(h->frame_num_offset + h->frame_num);
  3332. else poc= 2*(h->frame_num_offset + h->frame_num) - 1;
  3333. }
  3334. field_poc[0]= poc;
  3335. field_poc[1]= poc;
  3336. }
  3337. if(s->picture_structure != PICT_BOTTOM_FIELD) {
  3338. s->current_picture_ptr->field_poc[0]= field_poc[0];
  3339. s->current_picture_ptr->poc = field_poc[0];
  3340. }
  3341. if(s->picture_structure != PICT_TOP_FIELD) {
  3342. s->current_picture_ptr->field_poc[1]= field_poc[1];
  3343. s->current_picture_ptr->poc = field_poc[1];
  3344. }
  3345. if(!FIELD_PICTURE || !s->first_field) {
  3346. Picture *cur = s->current_picture_ptr;
  3347. cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
  3348. }
  3349. return 0;
  3350. }
  3351. /**
  3352. * initialize scan tables
  3353. */
  3354. static void init_scan_tables(H264Context *h){
  3355. MpegEncContext * const s = &h->s;
  3356. int i;
  3357. if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
  3358. memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
  3359. memcpy(h-> field_scan, field_scan, 16*sizeof(uint8_t));
  3360. }else{
  3361. for(i=0; i<16; i++){
  3362. #define T(x) (x>>2) | ((x<<2) & 0xF)
  3363. h->zigzag_scan[i] = T(zigzag_scan[i]);
  3364. h-> field_scan[i] = T( field_scan[i]);
  3365. #undef T
  3366. }
  3367. }
  3368. if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){
  3369. memcpy(h->zigzag_scan8x8, zigzag_scan8x8, 64*sizeof(uint8_t));
  3370. memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
  3371. memcpy(h->field_scan8x8, field_scan8x8, 64*sizeof(uint8_t));
  3372. memcpy(h->field_scan8x8_cavlc, field_scan8x8_cavlc, 64*sizeof(uint8_t));
  3373. }else{
  3374. for(i=0; i<64; i++){
  3375. #define T(x) (x>>3) | ((x&7)<<3)
  3376. h->zigzag_scan8x8[i] = T(zigzag_scan8x8[i]);
  3377. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  3378. h->field_scan8x8[i] = T(field_scan8x8[i]);
  3379. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  3380. #undef T
  3381. }
  3382. }
  3383. if(h->sps.transform_bypass){ //FIXME same ugly
  3384. h->zigzag_scan_q0 = zigzag_scan;
  3385. h->zigzag_scan8x8_q0 = zigzag_scan8x8;
  3386. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  3387. h->field_scan_q0 = field_scan;
  3388. h->field_scan8x8_q0 = field_scan8x8;
  3389. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  3390. }else{
  3391. h->zigzag_scan_q0 = h->zigzag_scan;
  3392. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  3393. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  3394. h->field_scan_q0 = h->field_scan;
  3395. h->field_scan8x8_q0 = h->field_scan8x8;
  3396. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  3397. }
  3398. }
  3399. /**
  3400. * Replicates H264 "master" context to thread contexts.
  3401. */
  3402. static void clone_slice(H264Context *dst, H264Context *src)
  3403. {
  3404. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  3405. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  3406. dst->s.current_picture = src->s.current_picture;
  3407. dst->s.linesize = src->s.linesize;
  3408. dst->s.uvlinesize = src->s.uvlinesize;
  3409. dst->s.first_field = src->s.first_field;
  3410. dst->prev_poc_msb = src->prev_poc_msb;
  3411. dst->prev_poc_lsb = src->prev_poc_lsb;
  3412. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  3413. dst->prev_frame_num = src->prev_frame_num;
  3414. dst->short_ref_count = src->short_ref_count;
  3415. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  3416. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  3417. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  3418. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  3419. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  3420. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  3421. }
  3422. /**
  3423. * decodes a slice header.
  3424. * this will allso call MPV_common_init() and frame_start() as needed
  3425. *
  3426. * @param h h264context
  3427. * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
  3428. *
  3429. * @return 0 if okay, <0 if an error occured, 1 if decoding must not be multithreaded
  3430. */
  3431. static int decode_slice_header(H264Context *h, H264Context *h0){
  3432. MpegEncContext * const s = &h->s;
  3433. MpegEncContext * const s0 = &h0->s;
  3434. unsigned int first_mb_in_slice;
  3435. unsigned int pps_id;
  3436. int num_ref_idx_active_override_flag;
  3437. static const uint8_t slice_type_map[5]= {P_TYPE, B_TYPE, I_TYPE, SP_TYPE, SI_TYPE};
  3438. unsigned int slice_type, tmp, i;
  3439. int default_ref_list_done = 0;
  3440. int last_pic_structure;
  3441. s->dropable= h->nal_ref_idc == 0;
  3442. first_mb_in_slice= get_ue_golomb(&s->gb);
  3443. if((s->flags2 & CODEC_FLAG2_CHUNKS) && first_mb_in_slice == 0){
  3444. h0->current_slice = 0;
  3445. if (!s0->first_field)
  3446. s->current_picture_ptr= NULL;
  3447. }
  3448. slice_type= get_ue_golomb(&s->gb);
  3449. if(slice_type > 9){
  3450. av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
  3451. return -1;
  3452. }
  3453. if(slice_type > 4){
  3454. slice_type -= 5;
  3455. h->slice_type_fixed=1;
  3456. }else
  3457. h->slice_type_fixed=0;
  3458. slice_type= slice_type_map[ slice_type ];
  3459. if (slice_type == I_TYPE
  3460. || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
  3461. default_ref_list_done = 1;
  3462. }
  3463. h->slice_type= slice_type;
  3464. s->pict_type= h->slice_type; // to make a few old func happy, it's wrong though
  3465. pps_id= get_ue_golomb(&s->gb);
  3466. if(pps_id>=MAX_PPS_COUNT){
  3467. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  3468. return -1;
  3469. }
  3470. if(!h0->pps_buffers[pps_id]) {
  3471. av_log(h->s.avctx, AV_LOG_ERROR, "non existing PPS referenced\n");
  3472. return -1;
  3473. }
  3474. h->pps= *h0->pps_buffers[pps_id];
  3475. if(!h0->sps_buffers[h->pps.sps_id]) {
  3476. av_log(h->s.avctx, AV_LOG_ERROR, "non existing SPS referenced\n");
  3477. return -1;
  3478. }
  3479. h->sps = *h0->sps_buffers[h->pps.sps_id];
  3480. if(h == h0 && h->dequant_coeff_pps != pps_id){
  3481. h->dequant_coeff_pps = pps_id;
  3482. init_dequant_tables(h);
  3483. }
  3484. s->mb_width= h->sps.mb_width;
  3485. s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  3486. h->b_stride= s->mb_width*4;
  3487. h->b8_stride= s->mb_width*2;
  3488. s->width = 16*s->mb_width - 2*(h->sps.crop_left + h->sps.crop_right );
  3489. if(h->sps.frame_mbs_only_flag)
  3490. s->height= 16*s->mb_height - 2*(h->sps.crop_top + h->sps.crop_bottom);
  3491. else
  3492. s->height= 16*s->mb_height - 4*(h->sps.crop_top + h->sps.crop_bottom); //FIXME recheck
  3493. if (s->context_initialized
  3494. && ( s->width != s->avctx->width || s->height != s->avctx->height)) {
  3495. if(h != h0)
  3496. return -1; // width / height changed during parallelized decoding
  3497. free_tables(h);
  3498. MPV_common_end(s);
  3499. }
  3500. if (!s->context_initialized) {
  3501. if(h != h0)
  3502. return -1; // we cant (re-)initialize context during parallel decoding
  3503. if (MPV_common_init(s) < 0)
  3504. return -1;
  3505. s->first_field = 0;
  3506. init_scan_tables(h);
  3507. alloc_tables(h);
  3508. for(i = 1; i < s->avctx->thread_count; i++) {
  3509. H264Context *c;
  3510. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  3511. memcpy(c, h, sizeof(MpegEncContext));
  3512. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  3513. c->sps = h->sps;
  3514. c->pps = h->pps;
  3515. init_scan_tables(c);
  3516. clone_tables(c, h);
  3517. }
  3518. for(i = 0; i < s->avctx->thread_count; i++)
  3519. if(context_init(h->thread_context[i]) < 0)
  3520. return -1;
  3521. s->avctx->width = s->width;
  3522. s->avctx->height = s->height;
  3523. s->avctx->sample_aspect_ratio= h->sps.sar;
  3524. if(!s->avctx->sample_aspect_ratio.den)
  3525. s->avctx->sample_aspect_ratio.den = 1;
  3526. if(h->sps.timing_info_present_flag){
  3527. s->avctx->time_base= (AVRational){h->sps.num_units_in_tick * 2, h->sps.time_scale};
  3528. if(h->x264_build > 0 && h->x264_build < 44)
  3529. s->avctx->time_base.den *= 2;
  3530. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  3531. s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);
  3532. }
  3533. }
  3534. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  3535. h->mb_mbaff = 0;
  3536. h->mb_aff_frame = 0;
  3537. last_pic_structure = s0->picture_structure;
  3538. if(h->sps.frame_mbs_only_flag){
  3539. s->picture_structure= PICT_FRAME;
  3540. }else{
  3541. if(get_bits1(&s->gb)) { //field_pic_flag
  3542. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  3543. } else {
  3544. s->picture_structure= PICT_FRAME;
  3545. h->mb_aff_frame = h->sps.mb_aff;
  3546. }
  3547. }
  3548. if(h0->current_slice == 0){
  3549. /* See if we have a decoded first field looking for a pair... */
  3550. if (s0->first_field) {
  3551. assert(s0->current_picture_ptr);
  3552. assert(s0->current_picture_ptr->data[0]);
  3553. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  3554. /* figure out if we have a complementary field pair */
  3555. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  3556. /*
  3557. * Previous field is unmatched. Don't display it, but let it
  3558. * remain for reference if marked as such.
  3559. */
  3560. s0->current_picture_ptr = NULL;
  3561. s0->first_field = FIELD_PICTURE;
  3562. } else {
  3563. if (h->nal_ref_idc &&
  3564. s0->current_picture_ptr->reference &&
  3565. s0->current_picture_ptr->frame_num != h->frame_num) {
  3566. /*
  3567. * This and previous field were reference, but had
  3568. * different frame_nums. Consider this field first in
  3569. * pair. Throw away previous field except for reference
  3570. * purposes.
  3571. */
  3572. s0->first_field = 1;
  3573. s0->current_picture_ptr = NULL;
  3574. } else {
  3575. /* Second field in complementary pair */
  3576. s0->first_field = 0;
  3577. }
  3578. }
  3579. } else {
  3580. /* Frame or first field in a potentially complementary pair */
  3581. assert(!s0->current_picture_ptr);
  3582. s0->first_field = FIELD_PICTURE;
  3583. }
  3584. if((!FIELD_PICTURE || s0->first_field) && frame_start(h) < 0) {
  3585. s0->first_field = 0;
  3586. return -1;
  3587. }
  3588. }
  3589. if(h != h0)
  3590. clone_slice(h, h0);
  3591. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  3592. assert(s->mb_num == s->mb_width * s->mb_height);
  3593. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  3594. first_mb_in_slice >= s->mb_num){
  3595. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  3596. return -1;
  3597. }
  3598. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  3599. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  3600. if (s->picture_structure == PICT_BOTTOM_FIELD)
  3601. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  3602. assert(s->mb_y < s->mb_height);
  3603. if(s->picture_structure==PICT_FRAME){
  3604. h->curr_pic_num= h->frame_num;
  3605. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  3606. }else{
  3607. h->curr_pic_num= 2*h->frame_num + 1;
  3608. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  3609. }
  3610. if(h->nal_unit_type == NAL_IDR_SLICE){
  3611. get_ue_golomb(&s->gb); /* idr_pic_id */
  3612. }
  3613. if(h->sps.poc_type==0){
  3614. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  3615. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  3616. h->delta_poc_bottom= get_se_golomb(&s->gb);
  3617. }
  3618. }
  3619. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  3620. h->delta_poc[0]= get_se_golomb(&s->gb);
  3621. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  3622. h->delta_poc[1]= get_se_golomb(&s->gb);
  3623. }
  3624. init_poc(h);
  3625. if(h->pps.redundant_pic_cnt_present){
  3626. h->redundant_pic_count= get_ue_golomb(&s->gb);
  3627. }
  3628. //set defaults, might be overriden a few line later
  3629. h->ref_count[0]= h->pps.ref_count[0];
  3630. h->ref_count[1]= h->pps.ref_count[1];
  3631. if(h->slice_type == P_TYPE || h->slice_type == SP_TYPE || h->slice_type == B_TYPE){
  3632. if(h->slice_type == B_TYPE){
  3633. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  3634. if(FIELD_OR_MBAFF_PICTURE && h->direct_spatial_mv_pred)
  3635. av_log(h->s.avctx, AV_LOG_ERROR, "Interlaced pictures + spatial direct mode is not implemented\n");
  3636. }
  3637. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  3638. if(num_ref_idx_active_override_flag){
  3639. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  3640. if(h->slice_type==B_TYPE)
  3641. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  3642. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  3643. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  3644. h->ref_count[0]= h->ref_count[1]= 1;
  3645. return -1;
  3646. }
  3647. }
  3648. if(h->slice_type == B_TYPE)
  3649. h->list_count= 2;
  3650. else
  3651. h->list_count= 1;
  3652. }else
  3653. h->list_count= 0;
  3654. if(!default_ref_list_done){
  3655. fill_default_ref_list(h);
  3656. }
  3657. if(decode_ref_pic_list_reordering(h) < 0)
  3658. return -1;
  3659. if( (h->pps.weighted_pred && (h->slice_type == P_TYPE || h->slice_type == SP_TYPE ))
  3660. || (h->pps.weighted_bipred_idc==1 && h->slice_type==B_TYPE ) )
  3661. pred_weight_table(h);
  3662. else if(h->pps.weighted_bipred_idc==2 && h->slice_type==B_TYPE)
  3663. implicit_weight_table(h);
  3664. else
  3665. h->use_weight = 0;
  3666. if(h->nal_ref_idc)
  3667. decode_ref_pic_marking(h0, &s->gb);
  3668. if(FRAME_MBAFF)
  3669. fill_mbaff_ref_list(h);
  3670. if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE && h->pps.cabac ){
  3671. tmp = get_ue_golomb(&s->gb);
  3672. if(tmp > 2){
  3673. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  3674. return -1;
  3675. }
  3676. h->cabac_init_idc= tmp;
  3677. }
  3678. h->last_qscale_diff = 0;
  3679. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  3680. if(tmp>51){
  3681. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3682. return -1;
  3683. }
  3684. s->qscale= tmp;
  3685. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3686. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3687. //FIXME qscale / qp ... stuff
  3688. if(h->slice_type == SP_TYPE){
  3689. get_bits1(&s->gb); /* sp_for_switch_flag */
  3690. }
  3691. if(h->slice_type==SP_TYPE || h->slice_type == SI_TYPE){
  3692. get_se_golomb(&s->gb); /* slice_qs_delta */
  3693. }
  3694. h->deblocking_filter = 1;
  3695. h->slice_alpha_c0_offset = 0;
  3696. h->slice_beta_offset = 0;
  3697. if( h->pps.deblocking_filter_parameters_present ) {
  3698. tmp= get_ue_golomb(&s->gb);
  3699. if(tmp > 2){
  3700. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  3701. return -1;
  3702. }
  3703. h->deblocking_filter= tmp;
  3704. if(h->deblocking_filter < 2)
  3705. h->deblocking_filter^= 1; // 1<->0
  3706. if( h->deblocking_filter ) {
  3707. h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
  3708. h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
  3709. }
  3710. }
  3711. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  3712. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type != I_TYPE)
  3713. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type == B_TYPE)
  3714. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  3715. h->deblocking_filter= 0;
  3716. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3717. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  3718. /* Cheat slightly for speed:
  3719. Dont bother to deblock across slices */
  3720. h->deblocking_filter = 2;
  3721. } else {
  3722. h0->max_contexts = 1;
  3723. if(!h0->single_decode_warning) {
  3724. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3725. h0->single_decode_warning = 1;
  3726. }
  3727. if(h != h0)
  3728. return 1; // deblocking switched inside frame
  3729. }
  3730. }
  3731. #if 0 //FMO
  3732. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  3733. slice_group_change_cycle= get_bits(&s->gb, ?);
  3734. #endif
  3735. h0->last_slice_type = slice_type;
  3736. h->slice_num = ++h0->current_slice;
  3737. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
  3738. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  3739. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  3740. av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s\n",
  3741. h->slice_num,
  3742. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  3743. first_mb_in_slice,
  3744. av_get_pict_type_char(h->slice_type),
  3745. pps_id, h->frame_num,
  3746. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  3747. h->ref_count[0], h->ref_count[1],
  3748. s->qscale,
  3749. h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,
  3750. h->use_weight,
  3751. h->use_weight==1 && h->use_weight_chroma ? "c" : ""
  3752. );
  3753. }
  3754. if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
  3755. s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
  3756. s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
  3757. }else{
  3758. s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
  3759. s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
  3760. }
  3761. return 0;
  3762. }
  3763. /**
  3764. *
  3765. */
  3766. static inline int get_level_prefix(GetBitContext *gb){
  3767. unsigned int buf;
  3768. int log;
  3769. OPEN_READER(re, gb);
  3770. UPDATE_CACHE(re, gb);
  3771. buf=GET_CACHE(re, gb);
  3772. log= 32 - av_log2(buf);
  3773. #ifdef TRACE
  3774. print_bin(buf>>(32-log), log);
  3775. av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d lpr @%5d in %s get_level_prefix\n", buf>>(32-log), log, log-1, get_bits_count(gb), __FILE__);
  3776. #endif
  3777. LAST_SKIP_BITS(re, gb, log);
  3778. CLOSE_READER(re, gb);
  3779. return log-1;
  3780. }
  3781. static inline int get_dct8x8_allowed(H264Context *h){
  3782. int i;
  3783. for(i=0; i<4; i++){
  3784. if(!IS_SUB_8X8(h->sub_mb_type[i])
  3785. || (!h->sps.direct_8x8_inference_flag && IS_DIRECT(h->sub_mb_type[i])))
  3786. return 0;
  3787. }
  3788. return 1;
  3789. }
  3790. /**
  3791. * decodes a residual block.
  3792. * @param n block index
  3793. * @param scantable scantable
  3794. * @param max_coeff number of coefficients in the block
  3795. * @return <0 if an error occured
  3796. */
  3797. static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
  3798. MpegEncContext * const s = &h->s;
  3799. static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};
  3800. int level[16];
  3801. int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
  3802. //FIXME put trailing_onex into the context
  3803. if(n == CHROMA_DC_BLOCK_INDEX){
  3804. coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
  3805. total_coeff= coeff_token>>2;
  3806. }else{
  3807. if(n == LUMA_DC_BLOCK_INDEX){
  3808. total_coeff= pred_non_zero_count(h, 0);
  3809. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3810. total_coeff= coeff_token>>2;
  3811. }else{
  3812. total_coeff= pred_non_zero_count(h, n);
  3813. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3814. total_coeff= coeff_token>>2;
  3815. h->non_zero_count_cache[ scan8[n] ]= total_coeff;
  3816. }
  3817. }
  3818. //FIXME set last_non_zero?
  3819. if(total_coeff==0)
  3820. return 0;
  3821. if(total_coeff > (unsigned)max_coeff) {
  3822. av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);
  3823. return -1;
  3824. }
  3825. trailing_ones= coeff_token&3;
  3826. tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);
  3827. assert(total_coeff<=16);
  3828. for(i=0; i<trailing_ones; i++){
  3829. level[i]= 1 - 2*get_bits1(gb);
  3830. }
  3831. if(i<total_coeff) {
  3832. int level_code, mask;
  3833. int suffix_length = total_coeff > 10 && trailing_ones < 3;
  3834. int prefix= get_level_prefix(gb);
  3835. //first coefficient has suffix_length equal to 0 or 1
  3836. if(prefix<14){ //FIXME try to build a large unified VLC table for all this
  3837. if(suffix_length)
  3838. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3839. else
  3840. level_code= (prefix<<suffix_length); //part
  3841. }else if(prefix==14){
  3842. if(suffix_length)
  3843. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3844. else
  3845. level_code= prefix + get_bits(gb, 4); //part
  3846. }else if(prefix==15){
  3847. level_code= (prefix<<suffix_length) + get_bits(gb, 12); //part
  3848. if(suffix_length==0) level_code+=15; //FIXME doesn't make (much)sense
  3849. }else{
  3850. av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
  3851. return -1;
  3852. }
  3853. if(trailing_ones < 3) level_code += 2;
  3854. suffix_length = 1;
  3855. if(level_code > 5)
  3856. suffix_length++;
  3857. mask= -(level_code&1);
  3858. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3859. i++;
  3860. //remaining coefficients have suffix_length > 0
  3861. for(;i<total_coeff;i++) {
  3862. static const int suffix_limit[7] = {0,5,11,23,47,95,INT_MAX };
  3863. prefix = get_level_prefix(gb);
  3864. if(prefix<15){
  3865. level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);
  3866. }else if(prefix==15){
  3867. level_code = (prefix<<suffix_length) + get_bits(gb, 12);
  3868. }else{
  3869. av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
  3870. return -1;
  3871. }
  3872. mask= -(level_code&1);
  3873. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3874. if(level_code > suffix_limit[suffix_length])
  3875. suffix_length++;
  3876. }
  3877. }
  3878. if(total_coeff == max_coeff)
  3879. zeros_left=0;
  3880. else{
  3881. if(n == CHROMA_DC_BLOCK_INDEX)
  3882. zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
  3883. else
  3884. zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
  3885. }
  3886. coeff_num = zeros_left + total_coeff - 1;
  3887. j = scantable[coeff_num];
  3888. if(n > 24){
  3889. block[j] = level[0];
  3890. for(i=1;i<total_coeff;i++) {
  3891. if(zeros_left <= 0)
  3892. run_before = 0;
  3893. else if(zeros_left < 7){
  3894. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3895. }else{
  3896. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3897. }
  3898. zeros_left -= run_before;
  3899. coeff_num -= 1 + run_before;
  3900. j= scantable[ coeff_num ];
  3901. block[j]= level[i];
  3902. }
  3903. }else{
  3904. block[j] = (level[0] * qmul[j] + 32)>>6;
  3905. for(i=1;i<total_coeff;i++) {
  3906. if(zeros_left <= 0)
  3907. run_before = 0;
  3908. else if(zeros_left < 7){
  3909. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3910. }else{
  3911. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3912. }
  3913. zeros_left -= run_before;
  3914. coeff_num -= 1 + run_before;
  3915. j= scantable[ coeff_num ];
  3916. block[j]= (level[i] * qmul[j] + 32)>>6;
  3917. }
  3918. }
  3919. if(zeros_left<0){
  3920. av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
  3921. return -1;
  3922. }
  3923. return 0;
  3924. }
  3925. static void predict_field_decoding_flag(H264Context *h){
  3926. MpegEncContext * const s = &h->s;
  3927. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3928. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  3929. ? s->current_picture.mb_type[mb_xy-1]
  3930. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  3931. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  3932. : 0;
  3933. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3934. }
  3935. /**
  3936. * decodes a P_SKIP or B_SKIP macroblock
  3937. */
  3938. static void decode_mb_skip(H264Context *h){
  3939. MpegEncContext * const s = &h->s;
  3940. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3941. int mb_type=0;
  3942. memset(h->non_zero_count[mb_xy], 0, 16);
  3943. memset(h->non_zero_count_cache + 8, 0, 8*5); //FIXME ugly, remove pfui
  3944. if(MB_FIELD)
  3945. mb_type|= MB_TYPE_INTERLACED;
  3946. if( h->slice_type == B_TYPE )
  3947. {
  3948. // just for fill_caches. pred_direct_motion will set the real mb_type
  3949. mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
  3950. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3951. pred_direct_motion(h, &mb_type);
  3952. mb_type|= MB_TYPE_SKIP;
  3953. }
  3954. else
  3955. {
  3956. int mx, my;
  3957. mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
  3958. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3959. pred_pskip_motion(h, &mx, &my);
  3960. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
  3961. fill_rectangle( h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
  3962. }
  3963. write_back_motion(h, mb_type);
  3964. s->current_picture.mb_type[mb_xy]= mb_type;
  3965. s->current_picture.qscale_table[mb_xy]= s->qscale;
  3966. h->slice_table[ mb_xy ]= h->slice_num;
  3967. h->prev_mb_skipped= 1;
  3968. }
  3969. /**
  3970. * decodes a macroblock
  3971. * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  3972. */
  3973. static int decode_mb_cavlc(H264Context *h){
  3974. MpegEncContext * const s = &h->s;
  3975. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3976. int partition_count;
  3977. unsigned int mb_type, cbp;
  3978. int dct8x8_allowed= h->pps.transform_8x8_mode;
  3979. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?
  3980. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  3981. cbp = 0; /* avoid warning. FIXME: find a solution without slowing
  3982. down the code */
  3983. if(h->slice_type != I_TYPE && h->slice_type != SI_TYPE){
  3984. if(s->mb_skip_run==-1)
  3985. s->mb_skip_run= get_ue_golomb(&s->gb);
  3986. if (s->mb_skip_run--) {
  3987. if(FRAME_MBAFF && (s->mb_y&1) == 0){
  3988. if(s->mb_skip_run==0)
  3989. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3990. else
  3991. predict_field_decoding_flag(h);
  3992. }
  3993. decode_mb_skip(h);
  3994. return 0;
  3995. }
  3996. }
  3997. if(FRAME_MBAFF){
  3998. if( (s->mb_y&1) == 0 )
  3999. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  4000. }else
  4001. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  4002. h->prev_mb_skipped= 0;
  4003. mb_type= get_ue_golomb(&s->gb);
  4004. if(h->slice_type == B_TYPE){
  4005. if(mb_type < 23){
  4006. partition_count= b_mb_type_info[mb_type].partition_count;
  4007. mb_type= b_mb_type_info[mb_type].type;
  4008. }else{
  4009. mb_type -= 23;
  4010. goto decode_intra_mb;
  4011. }
  4012. }else if(h->slice_type == P_TYPE /*|| h->slice_type == SP_TYPE */){
  4013. if(mb_type < 5){
  4014. partition_count= p_mb_type_info[mb_type].partition_count;
  4015. mb_type= p_mb_type_info[mb_type].type;
  4016. }else{
  4017. mb_type -= 5;
  4018. goto decode_intra_mb;
  4019. }
  4020. }else{
  4021. assert(h->slice_type == I_TYPE);
  4022. decode_intra_mb:
  4023. if(mb_type > 25){
  4024. av_log(h->s.avctx, AV_LOG_ERROR, "mb_type %d in %c slice too large at %d %d\n", mb_type, av_get_pict_type_char(h->slice_type), s->mb_x, s->mb_y);
  4025. return -1;
  4026. }
  4027. partition_count=0;
  4028. cbp= i_mb_type_info[mb_type].cbp;
  4029. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  4030. mb_type= i_mb_type_info[mb_type].type;
  4031. }
  4032. if(MB_FIELD)
  4033. mb_type |= MB_TYPE_INTERLACED;
  4034. h->slice_table[ mb_xy ]= h->slice_num;
  4035. if(IS_INTRA_PCM(mb_type)){
  4036. unsigned int x, y;
  4037. // We assume these blocks are very rare so we do not optimize it.
  4038. align_get_bits(&s->gb);
  4039. // The pixels are stored in the same order as levels in h->mb array.
  4040. for(y=0; y<16; y++){
  4041. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  4042. for(x=0; x<16; x++){
  4043. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  4044. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= get_bits(&s->gb, 8);
  4045. }
  4046. }
  4047. for(y=0; y<8; y++){
  4048. const int index= 256 + 4*(y&3) + 32*(y>>2);
  4049. for(x=0; x<8; x++){
  4050. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  4051. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  4052. }
  4053. }
  4054. for(y=0; y<8; y++){
  4055. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  4056. for(x=0; x<8; x++){
  4057. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  4058. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  4059. }
  4060. }
  4061. // In deblocking, the quantizer is 0
  4062. s->current_picture.qscale_table[mb_xy]= 0;
  4063. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  4064. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  4065. // All coeffs are present
  4066. memset(h->non_zero_count[mb_xy], 16, 16);
  4067. s->current_picture.mb_type[mb_xy]= mb_type;
  4068. return 0;
  4069. }
  4070. if(MB_MBAFF){
  4071. h->ref_count[0] <<= 1;
  4072. h->ref_count[1] <<= 1;
  4073. }
  4074. fill_caches(h, mb_type, 0);
  4075. //mb_pred
  4076. if(IS_INTRA(mb_type)){
  4077. int pred_mode;
  4078. // init_top_left_availability(h);
  4079. if(IS_INTRA4x4(mb_type)){
  4080. int i;
  4081. int di = 1;
  4082. if(dct8x8_allowed && get_bits1(&s->gb)){
  4083. mb_type |= MB_TYPE_8x8DCT;
  4084. di = 4;
  4085. }
  4086. // fill_intra4x4_pred_table(h);
  4087. for(i=0; i<16; i+=di){
  4088. int mode= pred_intra_mode(h, i);
  4089. if(!get_bits1(&s->gb)){
  4090. const int rem_mode= get_bits(&s->gb, 3);
  4091. mode = rem_mode + (rem_mode >= mode);
  4092. }
  4093. if(di==4)
  4094. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  4095. else
  4096. h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
  4097. }
  4098. write_back_intra_pred_mode(h);
  4099. if( check_intra4x4_pred_mode(h) < 0)
  4100. return -1;
  4101. }else{
  4102. h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
  4103. if(h->intra16x16_pred_mode < 0)
  4104. return -1;
  4105. }
  4106. pred_mode= check_intra_pred_mode(h, get_ue_golomb(&s->gb));
  4107. if(pred_mode < 0)
  4108. return -1;
  4109. h->chroma_pred_mode= pred_mode;
  4110. }else if(partition_count==4){
  4111. int i, j, sub_partition_count[4], list, ref[2][4];
  4112. if(h->slice_type == B_TYPE){
  4113. for(i=0; i<4; i++){
  4114. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4115. if(h->sub_mb_type[i] >=13){
  4116. av_log(h->s.avctx, AV_LOG_ERROR, "B sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
  4117. return -1;
  4118. }
  4119. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4120. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4121. }
  4122. if( IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])
  4123. || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3])) {
  4124. pred_direct_motion(h, &mb_type);
  4125. h->ref_cache[0][scan8[4]] =
  4126. h->ref_cache[1][scan8[4]] =
  4127. h->ref_cache[0][scan8[12]] =
  4128. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  4129. }
  4130. }else{
  4131. assert(h->slice_type == P_TYPE || h->slice_type == SP_TYPE); //FIXME SP correct ?
  4132. for(i=0; i<4; i++){
  4133. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4134. if(h->sub_mb_type[i] >=4){
  4135. av_log(h->s.avctx, AV_LOG_ERROR, "P sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
  4136. return -1;
  4137. }
  4138. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4139. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4140. }
  4141. }
  4142. for(list=0; list<h->list_count; list++){
  4143. int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
  4144. for(i=0; i<4; i++){
  4145. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  4146. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4147. unsigned int tmp = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?
  4148. if(tmp>=ref_count){
  4149. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);
  4150. return -1;
  4151. }
  4152. ref[list][i]= tmp;
  4153. }else{
  4154. //FIXME
  4155. ref[list][i] = -1;
  4156. }
  4157. }
  4158. }
  4159. if(dct8x8_allowed)
  4160. dct8x8_allowed = get_dct8x8_allowed(h);
  4161. for(list=0; list<h->list_count; list++){
  4162. for(i=0; i<4; i++){
  4163. if(IS_DIRECT(h->sub_mb_type[i])) {
  4164. h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];
  4165. continue;
  4166. }
  4167. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ]=
  4168. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  4169. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4170. const int sub_mb_type= h->sub_mb_type[i];
  4171. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  4172. for(j=0; j<sub_partition_count[i]; j++){
  4173. int mx, my;
  4174. const int index= 4*i + block_width*j;
  4175. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  4176. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
  4177. mx += get_se_golomb(&s->gb);
  4178. my += get_se_golomb(&s->gb);
  4179. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4180. if(IS_SUB_8X8(sub_mb_type)){
  4181. mv_cache[ 1 ][0]=
  4182. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  4183. mv_cache[ 1 ][1]=
  4184. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  4185. }else if(IS_SUB_8X4(sub_mb_type)){
  4186. mv_cache[ 1 ][0]= mx;
  4187. mv_cache[ 1 ][1]= my;
  4188. }else if(IS_SUB_4X8(sub_mb_type)){
  4189. mv_cache[ 8 ][0]= mx;
  4190. mv_cache[ 8 ][1]= my;
  4191. }
  4192. mv_cache[ 0 ][0]= mx;
  4193. mv_cache[ 0 ][1]= my;
  4194. }
  4195. }else{
  4196. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  4197. p[0] = p[1]=
  4198. p[8] = p[9]= 0;
  4199. }
  4200. }
  4201. }
  4202. }else if(IS_DIRECT(mb_type)){
  4203. pred_direct_motion(h, &mb_type);
  4204. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  4205. }else{
  4206. int list, mx, my, i;
  4207. //FIXME we should set ref_idx_l? to 0 if we use that later ...
  4208. if(IS_16X16(mb_type)){
  4209. for(list=0; list<h->list_count; list++){
  4210. unsigned int val;
  4211. if(IS_DIR(mb_type, 0, list)){
  4212. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4213. if(val >= h->ref_count[list]){
  4214. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4215. return -1;
  4216. }
  4217. }else
  4218. val= LIST_NOT_USED&0xFF;
  4219. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
  4220. }
  4221. for(list=0; list<h->list_count; list++){
  4222. unsigned int val;
  4223. if(IS_DIR(mb_type, 0, list)){
  4224. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
  4225. mx += get_se_golomb(&s->gb);
  4226. my += get_se_golomb(&s->gb);
  4227. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4228. val= pack16to32(mx,my);
  4229. }else
  4230. val=0;
  4231. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, val, 4);
  4232. }
  4233. }
  4234. else if(IS_16X8(mb_type)){
  4235. for(list=0; list<h->list_count; list++){
  4236. for(i=0; i<2; i++){
  4237. unsigned int val;
  4238. if(IS_DIR(mb_type, i, list)){
  4239. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4240. if(val >= h->ref_count[list]){
  4241. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4242. return -1;
  4243. }
  4244. }else
  4245. val= LIST_NOT_USED&0xFF;
  4246. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
  4247. }
  4248. }
  4249. for(list=0; list<h->list_count; list++){
  4250. for(i=0; i<2; i++){
  4251. unsigned int val;
  4252. if(IS_DIR(mb_type, i, list)){
  4253. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
  4254. mx += get_se_golomb(&s->gb);
  4255. my += get_se_golomb(&s->gb);
  4256. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4257. val= pack16to32(mx,my);
  4258. }else
  4259. val=0;
  4260. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
  4261. }
  4262. }
  4263. }else{
  4264. assert(IS_8X16(mb_type));
  4265. for(list=0; list<h->list_count; list++){
  4266. for(i=0; i<2; i++){
  4267. unsigned int val;
  4268. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  4269. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4270. if(val >= h->ref_count[list]){
  4271. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4272. return -1;
  4273. }
  4274. }else
  4275. val= LIST_NOT_USED&0xFF;
  4276. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
  4277. }
  4278. }
  4279. for(list=0; list<h->list_count; list++){
  4280. for(i=0; i<2; i++){
  4281. unsigned int val;
  4282. if(IS_DIR(mb_type, i, list)){
  4283. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
  4284. mx += get_se_golomb(&s->gb);
  4285. my += get_se_golomb(&s->gb);
  4286. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4287. val= pack16to32(mx,my);
  4288. }else
  4289. val=0;
  4290. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
  4291. }
  4292. }
  4293. }
  4294. }
  4295. if(IS_INTER(mb_type))
  4296. write_back_motion(h, mb_type);
  4297. if(!IS_INTRA16x16(mb_type)){
  4298. cbp= get_ue_golomb(&s->gb);
  4299. if(cbp > 47){
  4300. av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, s->mb_x, s->mb_y);
  4301. return -1;
  4302. }
  4303. if(IS_INTRA4x4(mb_type))
  4304. cbp= golomb_to_intra4x4_cbp[cbp];
  4305. else
  4306. cbp= golomb_to_inter_cbp[cbp];
  4307. }
  4308. h->cbp = cbp;
  4309. if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
  4310. if(get_bits1(&s->gb))
  4311. mb_type |= MB_TYPE_8x8DCT;
  4312. }
  4313. s->current_picture.mb_type[mb_xy]= mb_type;
  4314. if(cbp || IS_INTRA16x16(mb_type)){
  4315. int i8x8, i4x4, chroma_idx;
  4316. int dquant;
  4317. GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
  4318. const uint8_t *scan, *scan8x8, *dc_scan;
  4319. // fill_non_zero_count_cache(h);
  4320. if(IS_INTERLACED(mb_type)){
  4321. scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
  4322. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  4323. dc_scan= luma_dc_field_scan;
  4324. }else{
  4325. scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
  4326. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  4327. dc_scan= luma_dc_zigzag_scan;
  4328. }
  4329. dquant= get_se_golomb(&s->gb);
  4330. if( dquant > 25 || dquant < -26 ){
  4331. av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);
  4332. return -1;
  4333. }
  4334. s->qscale += dquant;
  4335. if(((unsigned)s->qscale) > 51){
  4336. if(s->qscale<0) s->qscale+= 52;
  4337. else s->qscale-= 52;
  4338. }
  4339. h->chroma_qp[0]= get_chroma_qp(h, 0, s->qscale);
  4340. h->chroma_qp[1]= get_chroma_qp(h, 1, s->qscale);
  4341. if(IS_INTRA16x16(mb_type)){
  4342. if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
  4343. return -1; //FIXME continue if partitioned and other return -1 too
  4344. }
  4345. assert((cbp&15) == 0 || (cbp&15) == 15);
  4346. if(cbp&15){
  4347. for(i8x8=0; i8x8<4; i8x8++){
  4348. for(i4x4=0; i4x4<4; i4x4++){
  4349. const int index= i4x4 + 4*i8x8;
  4350. if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, h->dequant4_coeff[0][s->qscale], 15) < 0 ){
  4351. return -1;
  4352. }
  4353. }
  4354. }
  4355. }else{
  4356. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  4357. }
  4358. }else{
  4359. for(i8x8=0; i8x8<4; i8x8++){
  4360. if(cbp & (1<<i8x8)){
  4361. if(IS_8x8DCT(mb_type)){
  4362. DCTELEM *buf = &h->mb[64*i8x8];
  4363. uint8_t *nnz;
  4364. for(i4x4=0; i4x4<4; i4x4++){
  4365. if( decode_residual(h, gb, buf, i4x4+4*i8x8, scan8x8+16*i4x4,
  4366. h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 16) <0 )
  4367. return -1;
  4368. }
  4369. nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4370. nnz[0] += nnz[1] + nnz[8] + nnz[9];
  4371. }else{
  4372. for(i4x4=0; i4x4<4; i4x4++){
  4373. const int index= i4x4 + 4*i8x8;
  4374. if( decode_residual(h, gb, h->mb + 16*index, index, scan, h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale], 16) <0 ){
  4375. return -1;
  4376. }
  4377. }
  4378. }
  4379. }else{
  4380. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4381. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  4382. }
  4383. }
  4384. }
  4385. if(cbp&0x30){
  4386. for(chroma_idx=0; chroma_idx<2; chroma_idx++)
  4387. if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){
  4388. return -1;
  4389. }
  4390. }
  4391. if(cbp&0x20){
  4392. for(chroma_idx=0; chroma_idx<2; chroma_idx++){
  4393. const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[chroma_idx]];
  4394. for(i4x4=0; i4x4<4; i4x4++){
  4395. const int index= 16 + 4*chroma_idx + i4x4;
  4396. if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, qmul, 15) < 0){
  4397. return -1;
  4398. }
  4399. }
  4400. }
  4401. }else{
  4402. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4403. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4404. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4405. }
  4406. }else{
  4407. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4408. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  4409. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4410. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4411. }
  4412. s->current_picture.qscale_table[mb_xy]= s->qscale;
  4413. write_back_non_zero_count(h);
  4414. if(MB_MBAFF){
  4415. h->ref_count[0] >>= 1;
  4416. h->ref_count[1] >>= 1;
  4417. }
  4418. return 0;
  4419. }
  4420. static int decode_cabac_field_decoding_flag(H264Context *h) {
  4421. MpegEncContext * const s = &h->s;
  4422. const int mb_x = s->mb_x;
  4423. const int mb_y = s->mb_y & ~1;
  4424. const int mba_xy = mb_x - 1 + mb_y *s->mb_stride;
  4425. const int mbb_xy = mb_x + (mb_y-2)*s->mb_stride;
  4426. unsigned int ctx = 0;
  4427. if( h->slice_table[mba_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) ) {
  4428. ctx += 1;
  4429. }
  4430. if( h->slice_table[mbb_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) ) {
  4431. ctx += 1;
  4432. }
  4433. return get_cabac_noinline( &h->cabac, &h->cabac_state[70 + ctx] );
  4434. }
  4435. static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {
  4436. uint8_t *state= &h->cabac_state[ctx_base];
  4437. int mb_type;
  4438. if(intra_slice){
  4439. MpegEncContext * const s = &h->s;
  4440. const int mba_xy = h->left_mb_xy[0];
  4441. const int mbb_xy = h->top_mb_xy;
  4442. int ctx=0;
  4443. if( h->slice_table[mba_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mba_xy] ) )
  4444. ctx++;
  4445. if( h->slice_table[mbb_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mbb_xy] ) )
  4446. ctx++;
  4447. if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )
  4448. return 0; /* I4x4 */
  4449. state += 2;
  4450. }else{
  4451. if( get_cabac_noinline( &h->cabac, &state[0] ) == 0 )
  4452. return 0; /* I4x4 */
  4453. }
  4454. if( get_cabac_terminate( &h->cabac ) )
  4455. return 25; /* PCM */
  4456. mb_type = 1; /* I16x16 */
  4457. mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */
  4458. if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */
  4459. mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );
  4460. mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );
  4461. mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );
  4462. return mb_type;
  4463. }
  4464. static int decode_cabac_mb_type( H264Context *h ) {
  4465. MpegEncContext * const s = &h->s;
  4466. if( h->slice_type == I_TYPE ) {
  4467. return decode_cabac_intra_mb_type(h, 3, 1);
  4468. } else if( h->slice_type == P_TYPE ) {
  4469. if( get_cabac_noinline( &h->cabac, &h->cabac_state[14] ) == 0 ) {
  4470. /* P-type */
  4471. if( get_cabac_noinline( &h->cabac, &h->cabac_state[15] ) == 0 ) {
  4472. /* P_L0_D16x16, P_8x8 */
  4473. return 3 * get_cabac_noinline( &h->cabac, &h->cabac_state[16] );
  4474. } else {
  4475. /* P_L0_D8x16, P_L0_D16x8 */
  4476. return 2 - get_cabac_noinline( &h->cabac, &h->cabac_state[17] );
  4477. }
  4478. } else {
  4479. return decode_cabac_intra_mb_type(h, 17, 0) + 5;
  4480. }
  4481. } else if( h->slice_type == B_TYPE ) {
  4482. const int mba_xy = h->left_mb_xy[0];
  4483. const int mbb_xy = h->top_mb_xy;
  4484. int ctx = 0;
  4485. int bits;
  4486. if( h->slice_table[mba_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mba_xy] ) )
  4487. ctx++;
  4488. if( h->slice_table[mbb_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mbb_xy] ) )
  4489. ctx++;
  4490. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+ctx] ) )
  4491. return 0; /* B_Direct_16x16 */
  4492. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+3] ) ) {
  4493. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ); /* B_L[01]_16x16 */
  4494. }
  4495. bits = get_cabac_noinline( &h->cabac, &h->cabac_state[27+4] ) << 3;
  4496. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 2;
  4497. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 1;
  4498. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4499. if( bits < 8 )
  4500. return bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */
  4501. else if( bits == 13 ) {
  4502. return decode_cabac_intra_mb_type(h, 32, 0) + 23;
  4503. } else if( bits == 14 )
  4504. return 11; /* B_L1_L0_8x16 */
  4505. else if( bits == 15 )
  4506. return 22; /* B_8x8 */
  4507. bits= ( bits<<1 ) | get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4508. return bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */
  4509. } else {
  4510. /* TODO SI/SP frames? */
  4511. return -1;
  4512. }
  4513. }
  4514. static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {
  4515. MpegEncContext * const s = &h->s;
  4516. int mba_xy, mbb_xy;
  4517. int ctx = 0;
  4518. if(FRAME_MBAFF){ //FIXME merge with the stuff in fill_caches?
  4519. int mb_xy = mb_x + (mb_y&~1)*s->mb_stride;
  4520. mba_xy = mb_xy - 1;
  4521. if( (mb_y&1)
  4522. && h->slice_table[mba_xy] == h->slice_num
  4523. && MB_FIELD == !!IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) )
  4524. mba_xy += s->mb_stride;
  4525. if( MB_FIELD ){
  4526. mbb_xy = mb_xy - s->mb_stride;
  4527. if( !(mb_y&1)
  4528. && h->slice_table[mbb_xy] == h->slice_num
  4529. && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) )
  4530. mbb_xy -= s->mb_stride;
  4531. }else
  4532. mbb_xy = mb_x + (mb_y-1)*s->mb_stride;
  4533. }else{
  4534. int mb_xy = mb_x + mb_y*s->mb_stride;
  4535. mba_xy = mb_xy - 1;
  4536. mbb_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
  4537. }
  4538. if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mba_xy] ))
  4539. ctx++;
  4540. if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mbb_xy] ))
  4541. ctx++;
  4542. if( h->slice_type == B_TYPE )
  4543. ctx += 13;
  4544. return get_cabac_noinline( &h->cabac, &h->cabac_state[11+ctx] );
  4545. }
  4546. static int decode_cabac_mb_intra4x4_pred_mode( H264Context *h, int pred_mode ) {
  4547. int mode = 0;
  4548. if( get_cabac( &h->cabac, &h->cabac_state[68] ) )
  4549. return pred_mode;
  4550. mode += 1 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4551. mode += 2 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4552. mode += 4 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4553. if( mode >= pred_mode )
  4554. return mode + 1;
  4555. else
  4556. return mode;
  4557. }
  4558. static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {
  4559. const int mba_xy = h->left_mb_xy[0];
  4560. const int mbb_xy = h->top_mb_xy;
  4561. int ctx = 0;
  4562. /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */
  4563. if( h->slice_table[mba_xy] == h->slice_num && h->chroma_pred_mode_table[mba_xy] != 0 )
  4564. ctx++;
  4565. if( h->slice_table[mbb_xy] == h->slice_num && h->chroma_pred_mode_table[mbb_xy] != 0 )
  4566. ctx++;
  4567. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )
  4568. return 0;
  4569. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4570. return 1;
  4571. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4572. return 2;
  4573. else
  4574. return 3;
  4575. }
  4576. static int decode_cabac_mb_cbp_luma( H264Context *h) {
  4577. int cbp_b, cbp_a, ctx, cbp = 0;
  4578. cbp_a = h->slice_table[h->left_mb_xy[0]] == h->slice_num ? h->left_cbp : -1;
  4579. cbp_b = h->slice_table[h->top_mb_xy] == h->slice_num ? h->top_cbp : -1;
  4580. ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);
  4581. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);
  4582. ctx = !(cbp & 0x01) + 2 * !(cbp_b & 0x08);
  4583. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;
  4584. ctx = !(cbp_a & 0x08) + 2 * !(cbp & 0x01);
  4585. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;
  4586. ctx = !(cbp & 0x04) + 2 * !(cbp & 0x02);
  4587. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;
  4588. return cbp;
  4589. }
  4590. static int decode_cabac_mb_cbp_chroma( H264Context *h) {
  4591. int ctx;
  4592. int cbp_a, cbp_b;
  4593. cbp_a = (h->left_cbp>>4)&0x03;
  4594. cbp_b = (h-> top_cbp>>4)&0x03;
  4595. ctx = 0;
  4596. if( cbp_a > 0 ) ctx++;
  4597. if( cbp_b > 0 ) ctx += 2;
  4598. if( get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] ) == 0 )
  4599. return 0;
  4600. ctx = 4;
  4601. if( cbp_a == 2 ) ctx++;
  4602. if( cbp_b == 2 ) ctx += 2;
  4603. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] );
  4604. }
  4605. static int decode_cabac_mb_dqp( H264Context *h) {
  4606. int ctx = 0;
  4607. int val = 0;
  4608. if( h->last_qscale_diff != 0 )
  4609. ctx++;
  4610. while( get_cabac_noinline( &h->cabac, &h->cabac_state[60 + ctx] ) ) {
  4611. if( ctx < 2 )
  4612. ctx = 2;
  4613. else
  4614. ctx = 3;
  4615. val++;
  4616. if(val > 102) //prevent infinite loop
  4617. return INT_MIN;
  4618. }
  4619. if( val&0x01 )
  4620. return (val + 1)/2;
  4621. else
  4622. return -(val + 1)/2;
  4623. }
  4624. static int decode_cabac_p_mb_sub_type( H264Context *h ) {
  4625. if( get_cabac( &h->cabac, &h->cabac_state[21] ) )
  4626. return 0; /* 8x8 */
  4627. if( !get_cabac( &h->cabac, &h->cabac_state[22] ) )
  4628. return 1; /* 8x4 */
  4629. if( get_cabac( &h->cabac, &h->cabac_state[23] ) )
  4630. return 2; /* 4x8 */
  4631. return 3; /* 4x4 */
  4632. }
  4633. static int decode_cabac_b_mb_sub_type( H264Context *h ) {
  4634. int type;
  4635. if( !get_cabac( &h->cabac, &h->cabac_state[36] ) )
  4636. return 0; /* B_Direct_8x8 */
  4637. if( !get_cabac( &h->cabac, &h->cabac_state[37] ) )
  4638. return 1 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */
  4639. type = 3;
  4640. if( get_cabac( &h->cabac, &h->cabac_state[38] ) ) {
  4641. if( get_cabac( &h->cabac, &h->cabac_state[39] ) )
  4642. return 11 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */
  4643. type += 4;
  4644. }
  4645. type += 2*get_cabac( &h->cabac, &h->cabac_state[39] );
  4646. type += get_cabac( &h->cabac, &h->cabac_state[39] );
  4647. return type;
  4648. }
  4649. static inline int decode_cabac_mb_transform_size( H264Context *h ) {
  4650. return get_cabac_noinline( &h->cabac, &h->cabac_state[399 + h->neighbor_transform_size] );
  4651. }
  4652. static int decode_cabac_mb_ref( H264Context *h, int list, int n ) {
  4653. int refa = h->ref_cache[list][scan8[n] - 1];
  4654. int refb = h->ref_cache[list][scan8[n] - 8];
  4655. int ref = 0;
  4656. int ctx = 0;
  4657. if( h->slice_type == B_TYPE) {
  4658. if( refa > 0 && !h->direct_cache[scan8[n] - 1] )
  4659. ctx++;
  4660. if( refb > 0 && !h->direct_cache[scan8[n] - 8] )
  4661. ctx += 2;
  4662. } else {
  4663. if( refa > 0 )
  4664. ctx++;
  4665. if( refb > 0 )
  4666. ctx += 2;
  4667. }
  4668. while( get_cabac( &h->cabac, &h->cabac_state[54+ctx] ) ) {
  4669. ref++;
  4670. if( ctx < 4 )
  4671. ctx = 4;
  4672. else
  4673. ctx = 5;
  4674. if(ref >= 32 /*h->ref_list[list]*/){
  4675. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_ref\n");
  4676. return 0; //FIXME we should return -1 and check the return everywhere
  4677. }
  4678. }
  4679. return ref;
  4680. }
  4681. static int decode_cabac_mb_mvd( H264Context *h, int list, int n, int l ) {
  4682. int amvd = abs( h->mvd_cache[list][scan8[n] - 1][l] ) +
  4683. abs( h->mvd_cache[list][scan8[n] - 8][l] );
  4684. int ctxbase = (l == 0) ? 40 : 47;
  4685. int ctx, mvd;
  4686. if( amvd < 3 )
  4687. ctx = 0;
  4688. else if( amvd > 32 )
  4689. ctx = 2;
  4690. else
  4691. ctx = 1;
  4692. if(!get_cabac(&h->cabac, &h->cabac_state[ctxbase+ctx]))
  4693. return 0;
  4694. mvd= 1;
  4695. ctx= 3;
  4696. while( mvd < 9 && get_cabac( &h->cabac, &h->cabac_state[ctxbase+ctx] ) ) {
  4697. mvd++;
  4698. if( ctx < 6 )
  4699. ctx++;
  4700. }
  4701. if( mvd >= 9 ) {
  4702. int k = 3;
  4703. while( get_cabac_bypass( &h->cabac ) ) {
  4704. mvd += 1 << k;
  4705. k++;
  4706. if(k>24){
  4707. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n");
  4708. return INT_MIN;
  4709. }
  4710. }
  4711. while( k-- ) {
  4712. if( get_cabac_bypass( &h->cabac ) )
  4713. mvd += 1 << k;
  4714. }
  4715. }
  4716. return get_cabac_bypass_sign( &h->cabac, -mvd );
  4717. }
  4718. static inline int get_cabac_cbf_ctx( H264Context *h, int cat, int idx ) {
  4719. int nza, nzb;
  4720. int ctx = 0;
  4721. if( cat == 0 ) {
  4722. nza = h->left_cbp&0x100;
  4723. nzb = h-> top_cbp&0x100;
  4724. } else if( cat == 1 || cat == 2 ) {
  4725. nza = h->non_zero_count_cache[scan8[idx] - 1];
  4726. nzb = h->non_zero_count_cache[scan8[idx] - 8];
  4727. } else if( cat == 3 ) {
  4728. nza = (h->left_cbp>>(6+idx))&0x01;
  4729. nzb = (h-> top_cbp>>(6+idx))&0x01;
  4730. } else {
  4731. assert(cat == 4);
  4732. nza = h->non_zero_count_cache[scan8[16+idx] - 1];
  4733. nzb = h->non_zero_count_cache[scan8[16+idx] - 8];
  4734. }
  4735. if( nza > 0 )
  4736. ctx++;
  4737. if( nzb > 0 )
  4738. ctx += 2;
  4739. return ctx + 4 * cat;
  4740. }
  4741. static const attribute_used uint8_t last_coeff_flag_offset_8x8[63] = {
  4742. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  4743. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  4744. 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  4745. 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8
  4746. };
  4747. static void decode_cabac_residual( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff) {
  4748. const int mb_xy = h->s.mb_x + h->s.mb_y*h->s.mb_stride;
  4749. static const int significant_coeff_flag_offset[2][6] = {
  4750. { 105+0, 105+15, 105+29, 105+44, 105+47, 402 },
  4751. { 277+0, 277+15, 277+29, 277+44, 277+47, 436 }
  4752. };
  4753. static const int last_coeff_flag_offset[2][6] = {
  4754. { 166+0, 166+15, 166+29, 166+44, 166+47, 417 },
  4755. { 338+0, 338+15, 338+29, 338+44, 338+47, 451 }
  4756. };
  4757. static const int coeff_abs_level_m1_offset[6] = {
  4758. 227+0, 227+10, 227+20, 227+30, 227+39, 426
  4759. };
  4760. static const uint8_t significant_coeff_flag_offset_8x8[2][63] = {
  4761. { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5,
  4762. 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9,10, 9, 8, 7,
  4763. 7, 6,11,12,13,11, 6, 7, 8, 9,14,10, 9, 8, 6,11,
  4764. 12,13,11, 6, 9,14,10, 9,11,12,13,11,14,10,12 },
  4765. { 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5,
  4766. 6, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11,
  4767. 9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,13,13, 9,
  4768. 9,10,10, 8,13,13, 9, 9,10,10,14,14,14,14,14 }
  4769. };
  4770. int index[64];
  4771. int av_unused last;
  4772. int coeff_count = 0;
  4773. int abslevel1 = 1;
  4774. int abslevelgt1 = 0;
  4775. uint8_t *significant_coeff_ctx_base;
  4776. uint8_t *last_coeff_ctx_base;
  4777. uint8_t *abs_level_m1_ctx_base;
  4778. #ifndef ARCH_X86
  4779. #define CABAC_ON_STACK
  4780. #endif
  4781. #ifdef CABAC_ON_STACK
  4782. #define CC &cc
  4783. CABACContext cc;
  4784. cc.range = h->cabac.range;
  4785. cc.low = h->cabac.low;
  4786. cc.bytestream= h->cabac.bytestream;
  4787. #else
  4788. #define CC &h->cabac
  4789. #endif
  4790. /* cat: 0-> DC 16x16 n = 0
  4791. * 1-> AC 16x16 n = luma4x4idx
  4792. * 2-> Luma4x4 n = luma4x4idx
  4793. * 3-> DC Chroma n = iCbCr
  4794. * 4-> AC Chroma n = 4 * iCbCr + chroma4x4idx
  4795. * 5-> Luma8x8 n = 4 * luma8x8idx
  4796. */
  4797. /* read coded block flag */
  4798. if( cat != 5 ) {
  4799. if( get_cabac( CC, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n ) ] ) == 0 ) {
  4800. if( cat == 1 || cat == 2 )
  4801. h->non_zero_count_cache[scan8[n]] = 0;
  4802. else if( cat == 4 )
  4803. h->non_zero_count_cache[scan8[16+n]] = 0;
  4804. #ifdef CABAC_ON_STACK
  4805. h->cabac.range = cc.range ;
  4806. h->cabac.low = cc.low ;
  4807. h->cabac.bytestream= cc.bytestream;
  4808. #endif
  4809. return;
  4810. }
  4811. }
  4812. significant_coeff_ctx_base = h->cabac_state
  4813. + significant_coeff_flag_offset[MB_FIELD][cat];
  4814. last_coeff_ctx_base = h->cabac_state
  4815. + last_coeff_flag_offset[MB_FIELD][cat];
  4816. abs_level_m1_ctx_base = h->cabac_state
  4817. + coeff_abs_level_m1_offset[cat];
  4818. if( cat == 5 ) {
  4819. #define DECODE_SIGNIFICANCE( coefs, sig_off, last_off ) \
  4820. for(last= 0; last < coefs; last++) { \
  4821. uint8_t *sig_ctx = significant_coeff_ctx_base + sig_off; \
  4822. if( get_cabac( CC, sig_ctx )) { \
  4823. uint8_t *last_ctx = last_coeff_ctx_base + last_off; \
  4824. index[coeff_count++] = last; \
  4825. if( get_cabac( CC, last_ctx ) ) { \
  4826. last= max_coeff; \
  4827. break; \
  4828. } \
  4829. } \
  4830. }\
  4831. if( last == max_coeff -1 ) {\
  4832. index[coeff_count++] = last;\
  4833. }
  4834. const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD];
  4835. #if defined(ARCH_X86) && defined(HAVE_7REGS) && defined(HAVE_EBX_AVAILABLE) && !defined(BROKEN_RELOCATIONS)
  4836. coeff_count= decode_significance_8x8_x86(CC, significant_coeff_ctx_base, index, sig_off);
  4837. } else {
  4838. coeff_count= decode_significance_x86(CC, max_coeff, significant_coeff_ctx_base, index);
  4839. #else
  4840. DECODE_SIGNIFICANCE( 63, sig_off[last], last_coeff_flag_offset_8x8[last] );
  4841. } else {
  4842. DECODE_SIGNIFICANCE( max_coeff - 1, last, last );
  4843. #endif
  4844. }
  4845. assert(coeff_count > 0);
  4846. if( cat == 0 )
  4847. h->cbp_table[mb_xy] |= 0x100;
  4848. else if( cat == 1 || cat == 2 )
  4849. h->non_zero_count_cache[scan8[n]] = coeff_count;
  4850. else if( cat == 3 )
  4851. h->cbp_table[mb_xy] |= 0x40 << n;
  4852. else if( cat == 4 )
  4853. h->non_zero_count_cache[scan8[16+n]] = coeff_count;
  4854. else {
  4855. assert( cat == 5 );
  4856. fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
  4857. }
  4858. for( coeff_count--; coeff_count >= 0; coeff_count-- ) {
  4859. uint8_t *ctx = (abslevelgt1 != 0 ? 0 : FFMIN( 4, abslevel1 )) + abs_level_m1_ctx_base;
  4860. int j= scantable[index[coeff_count]];
  4861. if( get_cabac( CC, ctx ) == 0 ) {
  4862. if( !qmul ) {
  4863. block[j] = get_cabac_bypass_sign( CC, -1);
  4864. }else{
  4865. block[j] = (get_cabac_bypass_sign( CC, -qmul[j]) + 32) >> 6;;
  4866. }
  4867. abslevel1++;
  4868. } else {
  4869. int coeff_abs = 2;
  4870. ctx = 5 + FFMIN( 4, abslevelgt1 ) + abs_level_m1_ctx_base;
  4871. while( coeff_abs < 15 && get_cabac( CC, ctx ) ) {
  4872. coeff_abs++;
  4873. }
  4874. if( coeff_abs >= 15 ) {
  4875. int j = 0;
  4876. while( get_cabac_bypass( CC ) ) {
  4877. j++;
  4878. }
  4879. coeff_abs=1;
  4880. while( j-- ) {
  4881. coeff_abs += coeff_abs + get_cabac_bypass( CC );
  4882. }
  4883. coeff_abs+= 14;
  4884. }
  4885. if( !qmul ) {
  4886. if( get_cabac_bypass( CC ) ) block[j] = -coeff_abs;
  4887. else block[j] = coeff_abs;
  4888. }else{
  4889. if( get_cabac_bypass( CC ) ) block[j] = (-coeff_abs * qmul[j] + 32) >> 6;
  4890. else block[j] = ( coeff_abs * qmul[j] + 32) >> 6;
  4891. }
  4892. abslevelgt1++;
  4893. }
  4894. }
  4895. #ifdef CABAC_ON_STACK
  4896. h->cabac.range = cc.range ;
  4897. h->cabac.low = cc.low ;
  4898. h->cabac.bytestream= cc.bytestream;
  4899. #endif
  4900. }
  4901. static inline void compute_mb_neighbors(H264Context *h)
  4902. {
  4903. MpegEncContext * const s = &h->s;
  4904. const int mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  4905. h->top_mb_xy = mb_xy - s->mb_stride;
  4906. h->left_mb_xy[0] = mb_xy - 1;
  4907. if(FRAME_MBAFF){
  4908. const int pair_xy = s->mb_x + (s->mb_y & ~1)*s->mb_stride;
  4909. const int top_pair_xy = pair_xy - s->mb_stride;
  4910. const int top_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
  4911. const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
  4912. const int curr_mb_frame_flag = !MB_FIELD;
  4913. const int bottom = (s->mb_y & 1);
  4914. if (bottom
  4915. ? !curr_mb_frame_flag // bottom macroblock
  4916. : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
  4917. ) {
  4918. h->top_mb_xy -= s->mb_stride;
  4919. }
  4920. if (left_mb_frame_flag != curr_mb_frame_flag) {
  4921. h->left_mb_xy[0] = pair_xy - 1;
  4922. }
  4923. } else if (FIELD_PICTURE) {
  4924. h->top_mb_xy -= s->mb_stride;
  4925. }
  4926. return;
  4927. }
  4928. /**
  4929. * decodes a macroblock
  4930. * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  4931. */
  4932. static int decode_mb_cabac(H264Context *h) {
  4933. MpegEncContext * const s = &h->s;
  4934. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  4935. int mb_type, partition_count, cbp = 0;
  4936. int dct8x8_allowed= h->pps.transform_8x8_mode;
  4937. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?)
  4938. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  4939. if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE ) {
  4940. int skip;
  4941. /* a skipped mb needs the aff flag from the following mb */
  4942. if( FRAME_MBAFF && s->mb_x==0 && (s->mb_y&1)==0 )
  4943. predict_field_decoding_flag(h);
  4944. if( FRAME_MBAFF && (s->mb_y&1)==1 && h->prev_mb_skipped )
  4945. skip = h->next_mb_skipped;
  4946. else
  4947. skip = decode_cabac_mb_skip( h, s->mb_x, s->mb_y );
  4948. /* read skip flags */
  4949. if( skip ) {
  4950. if( FRAME_MBAFF && (s->mb_y&1)==0 ){
  4951. s->current_picture.mb_type[mb_xy] = MB_TYPE_SKIP;
  4952. h->next_mb_skipped = decode_cabac_mb_skip( h, s->mb_x, s->mb_y+1 );
  4953. if(h->next_mb_skipped)
  4954. predict_field_decoding_flag(h);
  4955. else
  4956. h->mb_mbaff = h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4957. }
  4958. decode_mb_skip(h);
  4959. h->cbp_table[mb_xy] = 0;
  4960. h->chroma_pred_mode_table[mb_xy] = 0;
  4961. h->last_qscale_diff = 0;
  4962. return 0;
  4963. }
  4964. }
  4965. if(FRAME_MBAFF){
  4966. if( (s->mb_y&1) == 0 )
  4967. h->mb_mbaff =
  4968. h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4969. }else
  4970. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  4971. h->prev_mb_skipped = 0;
  4972. compute_mb_neighbors(h);
  4973. if( ( mb_type = decode_cabac_mb_type( h ) ) < 0 ) {
  4974. av_log( h->s.avctx, AV_LOG_ERROR, "decode_cabac_mb_type failed\n" );
  4975. return -1;
  4976. }
  4977. if( h->slice_type == B_TYPE ) {
  4978. if( mb_type < 23 ){
  4979. partition_count= b_mb_type_info[mb_type].partition_count;
  4980. mb_type= b_mb_type_info[mb_type].type;
  4981. }else{
  4982. mb_type -= 23;
  4983. goto decode_intra_mb;
  4984. }
  4985. } else if( h->slice_type == P_TYPE ) {
  4986. if( mb_type < 5) {
  4987. partition_count= p_mb_type_info[mb_type].partition_count;
  4988. mb_type= p_mb_type_info[mb_type].type;
  4989. } else {
  4990. mb_type -= 5;
  4991. goto decode_intra_mb;
  4992. }
  4993. } else {
  4994. assert(h->slice_type == I_TYPE);
  4995. decode_intra_mb:
  4996. partition_count = 0;
  4997. cbp= i_mb_type_info[mb_type].cbp;
  4998. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  4999. mb_type= i_mb_type_info[mb_type].type;
  5000. }
  5001. if(MB_FIELD)
  5002. mb_type |= MB_TYPE_INTERLACED;
  5003. h->slice_table[ mb_xy ]= h->slice_num;
  5004. if(IS_INTRA_PCM(mb_type)) {
  5005. const uint8_t *ptr;
  5006. unsigned int x, y;
  5007. // We assume these blocks are very rare so we do not optimize it.
  5008. // FIXME The two following lines get the bitstream position in the cabac
  5009. // decode, I think it should be done by a function in cabac.h (or cabac.c).
  5010. ptr= h->cabac.bytestream;
  5011. if(h->cabac.low&0x1) ptr--;
  5012. if(CABAC_BITS==16){
  5013. if(h->cabac.low&0x1FF) ptr--;
  5014. }
  5015. // The pixels are stored in the same order as levels in h->mb array.
  5016. for(y=0; y<16; y++){
  5017. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  5018. for(x=0; x<16; x++){
  5019. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", *ptr);
  5020. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= *ptr++;
  5021. }
  5022. }
  5023. for(y=0; y<8; y++){
  5024. const int index= 256 + 4*(y&3) + 32*(y>>2);
  5025. for(x=0; x<8; x++){
  5026. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", *ptr);
  5027. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  5028. }
  5029. }
  5030. for(y=0; y<8; y++){
  5031. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  5032. for(x=0; x<8; x++){
  5033. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", *ptr);
  5034. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  5035. }
  5036. }
  5037. ff_init_cabac_decoder(&h->cabac, ptr, h->cabac.bytestream_end - ptr);
  5038. // All blocks are present
  5039. h->cbp_table[mb_xy] = 0x1ef;
  5040. h->chroma_pred_mode_table[mb_xy] = 0;
  5041. // In deblocking, the quantizer is 0
  5042. s->current_picture.qscale_table[mb_xy]= 0;
  5043. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  5044. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  5045. // All coeffs are present
  5046. memset(h->non_zero_count[mb_xy], 16, 16);
  5047. s->current_picture.mb_type[mb_xy]= mb_type;
  5048. return 0;
  5049. }
  5050. if(MB_MBAFF){
  5051. h->ref_count[0] <<= 1;
  5052. h->ref_count[1] <<= 1;
  5053. }
  5054. fill_caches(h, mb_type, 0);
  5055. if( IS_INTRA( mb_type ) ) {
  5056. int i, pred_mode;
  5057. if( IS_INTRA4x4( mb_type ) ) {
  5058. if( dct8x8_allowed && decode_cabac_mb_transform_size( h ) ) {
  5059. mb_type |= MB_TYPE_8x8DCT;
  5060. for( i = 0; i < 16; i+=4 ) {
  5061. int pred = pred_intra_mode( h, i );
  5062. int mode = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5063. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  5064. }
  5065. } else {
  5066. for( i = 0; i < 16; i++ ) {
  5067. int pred = pred_intra_mode( h, i );
  5068. h->intra4x4_pred_mode_cache[ scan8[i] ] = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5069. //av_log( s->avctx, AV_LOG_ERROR, "i4x4 pred=%d mode=%d\n", pred, h->intra4x4_pred_mode_cache[ scan8[i] ] );
  5070. }
  5071. }
  5072. write_back_intra_pred_mode(h);
  5073. if( check_intra4x4_pred_mode(h) < 0 ) return -1;
  5074. } else {
  5075. h->intra16x16_pred_mode= check_intra_pred_mode( h, h->intra16x16_pred_mode );
  5076. if( h->intra16x16_pred_mode < 0 ) return -1;
  5077. }
  5078. h->chroma_pred_mode_table[mb_xy] =
  5079. pred_mode = decode_cabac_mb_chroma_pre_mode( h );
  5080. pred_mode= check_intra_pred_mode( h, pred_mode );
  5081. if( pred_mode < 0 ) return -1;
  5082. h->chroma_pred_mode= pred_mode;
  5083. } else if( partition_count == 4 ) {
  5084. int i, j, sub_partition_count[4], list, ref[2][4];
  5085. if( h->slice_type == B_TYPE ) {
  5086. for( i = 0; i < 4; i++ ) {
  5087. h->sub_mb_type[i] = decode_cabac_b_mb_sub_type( h );
  5088. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5089. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5090. }
  5091. if( IS_DIRECT(h->sub_mb_type[0] | h->sub_mb_type[1] |
  5092. h->sub_mb_type[2] | h->sub_mb_type[3]) ) {
  5093. pred_direct_motion(h, &mb_type);
  5094. h->ref_cache[0][scan8[4]] =
  5095. h->ref_cache[1][scan8[4]] =
  5096. h->ref_cache[0][scan8[12]] =
  5097. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  5098. if( h->ref_count[0] > 1 || h->ref_count[1] > 1 ) {
  5099. for( i = 0; i < 4; i++ )
  5100. if( IS_DIRECT(h->sub_mb_type[i]) )
  5101. fill_rectangle( &h->direct_cache[scan8[4*i]], 2, 2, 8, 1, 1 );
  5102. }
  5103. }
  5104. } else {
  5105. for( i = 0; i < 4; i++ ) {
  5106. h->sub_mb_type[i] = decode_cabac_p_mb_sub_type( h );
  5107. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5108. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5109. }
  5110. }
  5111. for( list = 0; list < h->list_count; list++ ) {
  5112. for( i = 0; i < 4; i++ ) {
  5113. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  5114. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  5115. if( h->ref_count[list] > 1 )
  5116. ref[list][i] = decode_cabac_mb_ref( h, list, 4*i );
  5117. else
  5118. ref[list][i] = 0;
  5119. } else {
  5120. ref[list][i] = -1;
  5121. }
  5122. h->ref_cache[list][ scan8[4*i]+1 ]=
  5123. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  5124. }
  5125. }
  5126. if(dct8x8_allowed)
  5127. dct8x8_allowed = get_dct8x8_allowed(h);
  5128. for(list=0; list<h->list_count; list++){
  5129. for(i=0; i<4; i++){
  5130. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ];
  5131. if(IS_DIRECT(h->sub_mb_type[i])){
  5132. fill_rectangle(h->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 4);
  5133. continue;
  5134. }
  5135. if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
  5136. const int sub_mb_type= h->sub_mb_type[i];
  5137. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  5138. for(j=0; j<sub_partition_count[i]; j++){
  5139. int mpx, mpy;
  5140. int mx, my;
  5141. const int index= 4*i + block_width*j;
  5142. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  5143. int16_t (* mvd_cache)[2]= &h->mvd_cache[list][ scan8[index] ];
  5144. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mpx, &mpy);
  5145. mx = mpx + decode_cabac_mb_mvd( h, list, index, 0 );
  5146. my = mpy + decode_cabac_mb_mvd( h, list, index, 1 );
  5147. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5148. if(IS_SUB_8X8(sub_mb_type)){
  5149. mv_cache[ 1 ][0]=
  5150. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  5151. mv_cache[ 1 ][1]=
  5152. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  5153. mvd_cache[ 1 ][0]=
  5154. mvd_cache[ 8 ][0]= mvd_cache[ 9 ][0]= mx - mpx;
  5155. mvd_cache[ 1 ][1]=
  5156. mvd_cache[ 8 ][1]= mvd_cache[ 9 ][1]= my - mpy;
  5157. }else if(IS_SUB_8X4(sub_mb_type)){
  5158. mv_cache[ 1 ][0]= mx;
  5159. mv_cache[ 1 ][1]= my;
  5160. mvd_cache[ 1 ][0]= mx - mpx;
  5161. mvd_cache[ 1 ][1]= my - mpy;
  5162. }else if(IS_SUB_4X8(sub_mb_type)){
  5163. mv_cache[ 8 ][0]= mx;
  5164. mv_cache[ 8 ][1]= my;
  5165. mvd_cache[ 8 ][0]= mx - mpx;
  5166. mvd_cache[ 8 ][1]= my - mpy;
  5167. }
  5168. mv_cache[ 0 ][0]= mx;
  5169. mv_cache[ 0 ][1]= my;
  5170. mvd_cache[ 0 ][0]= mx - mpx;
  5171. mvd_cache[ 0 ][1]= my - mpy;
  5172. }
  5173. }else{
  5174. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  5175. uint32_t *pd= (uint32_t *)&h->mvd_cache[list][ scan8[4*i] ][0];
  5176. p[0] = p[1] = p[8] = p[9] = 0;
  5177. pd[0]= pd[1]= pd[8]= pd[9]= 0;
  5178. }
  5179. }
  5180. }
  5181. } else if( IS_DIRECT(mb_type) ) {
  5182. pred_direct_motion(h, &mb_type);
  5183. fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 4);
  5184. fill_rectangle(h->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 4);
  5185. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  5186. } else {
  5187. int list, mx, my, i, mpx, mpy;
  5188. if(IS_16X16(mb_type)){
  5189. for(list=0; list<h->list_count; list++){
  5190. if(IS_DIR(mb_type, 0, list)){
  5191. const int ref = h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 0 ) : 0;
  5192. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);
  5193. }else
  5194. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1); //FIXME factorize and the other fill_rect below too
  5195. }
  5196. for(list=0; list<h->list_count; list++){
  5197. if(IS_DIR(mb_type, 0, list)){
  5198. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mpx, &mpy);
  5199. mx = mpx + decode_cabac_mb_mvd( h, list, 0, 0 );
  5200. my = mpy + decode_cabac_mb_mvd( h, list, 0, 1 );
  5201. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5202. fill_rectangle(h->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5203. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
  5204. }else
  5205. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, 0, 4);
  5206. }
  5207. }
  5208. else if(IS_16X8(mb_type)){
  5209. for(list=0; list<h->list_count; list++){
  5210. for(i=0; i<2; i++){
  5211. if(IS_DIR(mb_type, i, list)){
  5212. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 8*i ) : 0;
  5213. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);
  5214. }else
  5215. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);
  5216. }
  5217. }
  5218. for(list=0; list<h->list_count; list++){
  5219. for(i=0; i<2; i++){
  5220. if(IS_DIR(mb_type, i, list)){
  5221. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mpx, &mpy);
  5222. mx = mpx + decode_cabac_mb_mvd( h, list, 8*i, 0 );
  5223. my = mpy + decode_cabac_mb_mvd( h, list, 8*i, 1 );
  5224. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5225. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx-mpx,my-mpy), 4);
  5226. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
  5227. }else{
  5228. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5229. fill_rectangle(h-> mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5230. }
  5231. }
  5232. }
  5233. }else{
  5234. assert(IS_8X16(mb_type));
  5235. for(list=0; list<h->list_count; list++){
  5236. for(i=0; i<2; i++){
  5237. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  5238. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 4*i ) : 0;
  5239. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);
  5240. }else
  5241. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);
  5242. }
  5243. }
  5244. for(list=0; list<h->list_count; list++){
  5245. for(i=0; i<2; i++){
  5246. if(IS_DIR(mb_type, i, list)){
  5247. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mpx, &mpy);
  5248. mx = mpx + decode_cabac_mb_mvd( h, list, 4*i, 0 );
  5249. my = mpy + decode_cabac_mb_mvd( h, list, 4*i, 1 );
  5250. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5251. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5252. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
  5253. }else{
  5254. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5255. fill_rectangle(h-> mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5256. }
  5257. }
  5258. }
  5259. }
  5260. }
  5261. if( IS_INTER( mb_type ) ) {
  5262. h->chroma_pred_mode_table[mb_xy] = 0;
  5263. write_back_motion( h, mb_type );
  5264. }
  5265. if( !IS_INTRA16x16( mb_type ) ) {
  5266. cbp = decode_cabac_mb_cbp_luma( h );
  5267. cbp |= decode_cabac_mb_cbp_chroma( h ) << 4;
  5268. }
  5269. h->cbp_table[mb_xy] = h->cbp = cbp;
  5270. if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) {
  5271. if( decode_cabac_mb_transform_size( h ) )
  5272. mb_type |= MB_TYPE_8x8DCT;
  5273. }
  5274. s->current_picture.mb_type[mb_xy]= mb_type;
  5275. if( cbp || IS_INTRA16x16( mb_type ) ) {
  5276. const uint8_t *scan, *scan8x8, *dc_scan;
  5277. const uint32_t *qmul;
  5278. int dqp;
  5279. if(IS_INTERLACED(mb_type)){
  5280. scan8x8= s->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
  5281. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  5282. dc_scan= luma_dc_field_scan;
  5283. }else{
  5284. scan8x8= s->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
  5285. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  5286. dc_scan= luma_dc_zigzag_scan;
  5287. }
  5288. h->last_qscale_diff = dqp = decode_cabac_mb_dqp( h );
  5289. if( dqp == INT_MIN ){
  5290. av_log(h->s.avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", s->mb_x, s->mb_y);
  5291. return -1;
  5292. }
  5293. s->qscale += dqp;
  5294. if(((unsigned)s->qscale) > 51){
  5295. if(s->qscale<0) s->qscale+= 52;
  5296. else s->qscale-= 52;
  5297. }
  5298. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  5299. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  5300. if( IS_INTRA16x16( mb_type ) ) {
  5301. int i;
  5302. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 DC\n" );
  5303. decode_cabac_residual( h, h->mb, 0, 0, dc_scan, NULL, 16);
  5304. if( cbp&15 ) {
  5305. qmul = h->dequant4_coeff[0][s->qscale];
  5306. for( i = 0; i < 16; i++ ) {
  5307. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 AC:%d\n", i );
  5308. decode_cabac_residual(h, h->mb + 16*i, 1, i, scan + 1, qmul, 15);
  5309. }
  5310. } else {
  5311. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  5312. }
  5313. } else {
  5314. int i8x8, i4x4;
  5315. for( i8x8 = 0; i8x8 < 4; i8x8++ ) {
  5316. if( cbp & (1<<i8x8) ) {
  5317. if( IS_8x8DCT(mb_type) ) {
  5318. decode_cabac_residual(h, h->mb + 64*i8x8, 5, 4*i8x8,
  5319. scan8x8, h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 64);
  5320. } else {
  5321. qmul = h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale];
  5322. for( i4x4 = 0; i4x4 < 4; i4x4++ ) {
  5323. const int index = 4*i8x8 + i4x4;
  5324. //av_log( s->avctx, AV_LOG_ERROR, "Luma4x4: %d\n", index );
  5325. //START_TIMER
  5326. decode_cabac_residual(h, h->mb + 16*index, 2, index, scan, qmul, 16);
  5327. //STOP_TIMER("decode_residual")
  5328. }
  5329. }
  5330. } else {
  5331. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  5332. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  5333. }
  5334. }
  5335. }
  5336. if( cbp&0x30 ){
  5337. int c;
  5338. for( c = 0; c < 2; c++ ) {
  5339. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-DC\n",c );
  5340. decode_cabac_residual(h, h->mb + 256 + 16*4*c, 3, c, chroma_dc_scan, NULL, 4);
  5341. }
  5342. }
  5343. if( cbp&0x20 ) {
  5344. int c, i;
  5345. for( c = 0; c < 2; c++ ) {
  5346. qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[c]];
  5347. for( i = 0; i < 4; i++ ) {
  5348. const int index = 16 + 4 * c + i;
  5349. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-AC %d\n",c, index - 16 );
  5350. decode_cabac_residual(h, h->mb + 16*index, 4, index - 16, scan + 1, qmul, 15);
  5351. }
  5352. }
  5353. } else {
  5354. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5355. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5356. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5357. }
  5358. } else {
  5359. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5360. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  5361. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5362. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5363. h->last_qscale_diff = 0;
  5364. }
  5365. s->current_picture.qscale_table[mb_xy]= s->qscale;
  5366. write_back_non_zero_count(h);
  5367. if(MB_MBAFF){
  5368. h->ref_count[0] >>= 1;
  5369. h->ref_count[1] >>= 1;
  5370. }
  5371. return 0;
  5372. }
  5373. static void filter_mb_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5374. int i, d;
  5375. const int index_a = qp + h->slice_alpha_c0_offset;
  5376. const int alpha = (alpha_table+52)[index_a];
  5377. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5378. if( bS[0] < 4 ) {
  5379. int8_t tc[4];
  5380. for(i=0; i<4; i++)
  5381. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5382. h->s.dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);
  5383. } else {
  5384. /* 16px edge length, because bS=4 is triggered by being at
  5385. * the edge of an intra MB, so all 4 bS are the same */
  5386. for( d = 0; d < 16; d++ ) {
  5387. const int p0 = pix[-1];
  5388. const int p1 = pix[-2];
  5389. const int p2 = pix[-3];
  5390. const int q0 = pix[0];
  5391. const int q1 = pix[1];
  5392. const int q2 = pix[2];
  5393. if( FFABS( p0 - q0 ) < alpha &&
  5394. FFABS( p1 - p0 ) < beta &&
  5395. FFABS( q1 - q0 ) < beta ) {
  5396. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5397. if( FFABS( p2 - p0 ) < beta)
  5398. {
  5399. const int p3 = pix[-4];
  5400. /* p0', p1', p2' */
  5401. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5402. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5403. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5404. } else {
  5405. /* p0' */
  5406. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5407. }
  5408. if( FFABS( q2 - q0 ) < beta)
  5409. {
  5410. const int q3 = pix[3];
  5411. /* q0', q1', q2' */
  5412. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5413. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5414. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5415. } else {
  5416. /* q0' */
  5417. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5418. }
  5419. }else{
  5420. /* p0', q0' */
  5421. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5422. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5423. }
  5424. tprintf(h->s.avctx, "filter_mb_edgev i:%d d:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, d, p2, p1, p0, q0, q1, q2, pix[-2], pix[-1], pix[0], pix[1]);
  5425. }
  5426. pix += stride;
  5427. }
  5428. }
  5429. }
  5430. static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5431. int i;
  5432. const int index_a = qp + h->slice_alpha_c0_offset;
  5433. const int alpha = (alpha_table+52)[index_a];
  5434. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5435. if( bS[0] < 4 ) {
  5436. int8_t tc[4];
  5437. for(i=0; i<4; i++)
  5438. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5439. h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5440. } else {
  5441. h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5442. }
  5443. }
  5444. static void filter_mb_mbaff_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5445. int i;
  5446. for( i = 0; i < 16; i++, pix += stride) {
  5447. int index_a;
  5448. int alpha;
  5449. int beta;
  5450. int qp_index;
  5451. int bS_index = (i >> 1);
  5452. if (!MB_FIELD) {
  5453. bS_index &= ~1;
  5454. bS_index |= (i & 1);
  5455. }
  5456. if( bS[bS_index] == 0 ) {
  5457. continue;
  5458. }
  5459. qp_index = MB_FIELD ? (i >> 3) : (i & 1);
  5460. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5461. alpha = (alpha_table+52)[index_a];
  5462. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5463. if( bS[bS_index] < 4 ) {
  5464. const int tc0 = (tc0_table+52)[index_a][bS[bS_index] - 1];
  5465. const int p0 = pix[-1];
  5466. const int p1 = pix[-2];
  5467. const int p2 = pix[-3];
  5468. const int q0 = pix[0];
  5469. const int q1 = pix[1];
  5470. const int q2 = pix[2];
  5471. if( FFABS( p0 - q0 ) < alpha &&
  5472. FFABS( p1 - p0 ) < beta &&
  5473. FFABS( q1 - q0 ) < beta ) {
  5474. int tc = tc0;
  5475. int i_delta;
  5476. if( FFABS( p2 - p0 ) < beta ) {
  5477. pix[-2] = p1 + av_clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );
  5478. tc++;
  5479. }
  5480. if( FFABS( q2 - q0 ) < beta ) {
  5481. pix[1] = q1 + av_clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );
  5482. tc++;
  5483. }
  5484. i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5485. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5486. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5487. tprintf(h->s.avctx, "filter_mb_mbaff_edgev i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d, tc:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, tc, bS[bS_index], pix[-3], p1, p0, q0, q1, pix[2], p1, pix[-1], pix[0], q1);
  5488. }
  5489. }else{
  5490. const int p0 = pix[-1];
  5491. const int p1 = pix[-2];
  5492. const int p2 = pix[-3];
  5493. const int q0 = pix[0];
  5494. const int q1 = pix[1];
  5495. const int q2 = pix[2];
  5496. if( FFABS( p0 - q0 ) < alpha &&
  5497. FFABS( p1 - p0 ) < beta &&
  5498. FFABS( q1 - q0 ) < beta ) {
  5499. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5500. if( FFABS( p2 - p0 ) < beta)
  5501. {
  5502. const int p3 = pix[-4];
  5503. /* p0', p1', p2' */
  5504. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5505. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5506. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5507. } else {
  5508. /* p0' */
  5509. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5510. }
  5511. if( FFABS( q2 - q0 ) < beta)
  5512. {
  5513. const int q3 = pix[3];
  5514. /* q0', q1', q2' */
  5515. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5516. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5517. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5518. } else {
  5519. /* q0' */
  5520. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5521. }
  5522. }else{
  5523. /* p0', q0' */
  5524. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5525. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5526. }
  5527. tprintf(h->s.avctx, "filter_mb_mbaff_edgev i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, p2, p1, p0, q0, q1, q2, pix[-3], pix[-2], pix[-1], pix[0], pix[1], pix[2]);
  5528. }
  5529. }
  5530. }
  5531. }
  5532. static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5533. int i;
  5534. for( i = 0; i < 8; i++, pix += stride) {
  5535. int index_a;
  5536. int alpha;
  5537. int beta;
  5538. int qp_index;
  5539. int bS_index = i;
  5540. if( bS[bS_index] == 0 ) {
  5541. continue;
  5542. }
  5543. qp_index = MB_FIELD ? (i >> 2) : (i & 1);
  5544. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5545. alpha = (alpha_table+52)[index_a];
  5546. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5547. if( bS[bS_index] < 4 ) {
  5548. const int tc = (tc0_table+52)[index_a][bS[bS_index] - 1] + 1;
  5549. const int p0 = pix[-1];
  5550. const int p1 = pix[-2];
  5551. const int q0 = pix[0];
  5552. const int q1 = pix[1];
  5553. if( FFABS( p0 - q0 ) < alpha &&
  5554. FFABS( p1 - p0 ) < beta &&
  5555. FFABS( q1 - q0 ) < beta ) {
  5556. const int i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5557. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5558. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5559. tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d, tc:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, tc, bS[bS_index], pix[-3], p1, p0, q0, q1, pix[2], p1, pix[-1], pix[0], q1);
  5560. }
  5561. }else{
  5562. const int p0 = pix[-1];
  5563. const int p1 = pix[-2];
  5564. const int q0 = pix[0];
  5565. const int q1 = pix[1];
  5566. if( FFABS( p0 - q0 ) < alpha &&
  5567. FFABS( p1 - p0 ) < beta &&
  5568. FFABS( q1 - q0 ) < beta ) {
  5569. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2; /* p0' */
  5570. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2; /* q0' */
  5571. tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x, %02x, %02x]\n", i, pix[-3], p1, p0, q0, q1, pix[2], pix[-3], pix[-2], pix[-1], pix[0], pix[1], pix[2]);
  5572. }
  5573. }
  5574. }
  5575. }
  5576. static void filter_mb_edgeh( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5577. int i, d;
  5578. const int index_a = qp + h->slice_alpha_c0_offset;
  5579. const int alpha = (alpha_table+52)[index_a];
  5580. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5581. const int pix_next = stride;
  5582. if( bS[0] < 4 ) {
  5583. int8_t tc[4];
  5584. for(i=0; i<4; i++)
  5585. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5586. h->s.dsp.h264_v_loop_filter_luma(pix, stride, alpha, beta, tc);
  5587. } else {
  5588. /* 16px edge length, see filter_mb_edgev */
  5589. for( d = 0; d < 16; d++ ) {
  5590. const int p0 = pix[-1*pix_next];
  5591. const int p1 = pix[-2*pix_next];
  5592. const int p2 = pix[-3*pix_next];
  5593. const int q0 = pix[0];
  5594. const int q1 = pix[1*pix_next];
  5595. const int q2 = pix[2*pix_next];
  5596. if( FFABS( p0 - q0 ) < alpha &&
  5597. FFABS( p1 - p0 ) < beta &&
  5598. FFABS( q1 - q0 ) < beta ) {
  5599. const int p3 = pix[-4*pix_next];
  5600. const int q3 = pix[ 3*pix_next];
  5601. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5602. if( FFABS( p2 - p0 ) < beta) {
  5603. /* p0', p1', p2' */
  5604. pix[-1*pix_next] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5605. pix[-2*pix_next] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5606. pix[-3*pix_next] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5607. } else {
  5608. /* p0' */
  5609. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5610. }
  5611. if( FFABS( q2 - q0 ) < beta) {
  5612. /* q0', q1', q2' */
  5613. pix[0*pix_next] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5614. pix[1*pix_next] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5615. pix[2*pix_next] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5616. } else {
  5617. /* q0' */
  5618. pix[0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5619. }
  5620. }else{
  5621. /* p0', q0' */
  5622. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5623. pix[ 0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5624. }
  5625. tprintf(h->s.avctx, "filter_mb_edgeh i:%d d:%d, qp:%d, indexA:%d, alpha:%d, beta:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, d, qp, index_a, alpha, beta, bS[i], p2, p1, p0, q0, q1, q2, pix[-2*pix_next], pix[-pix_next], pix[0], pix[pix_next]);
  5626. }
  5627. pix++;
  5628. }
  5629. }
  5630. }
  5631. static void filter_mb_edgech( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5632. int i;
  5633. const int index_a = qp + h->slice_alpha_c0_offset;
  5634. const int alpha = (alpha_table+52)[index_a];
  5635. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5636. if( bS[0] < 4 ) {
  5637. int8_t tc[4];
  5638. for(i=0; i<4; i++)
  5639. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5640. h->s.dsp.h264_v_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5641. } else {
  5642. h->s.dsp.h264_v_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5643. }
  5644. }
  5645. static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
  5646. MpegEncContext * const s = &h->s;
  5647. int mb_xy, mb_type;
  5648. int qp, qp0, qp1, qpc, qpc0, qpc1, qp_thresh;
  5649. mb_xy = mb_x + mb_y*s->mb_stride;
  5650. if(mb_x==0 || mb_y==0 || !s->dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff ||
  5651. (h->deblocking_filter == 2 && (h->slice_table[mb_xy] != h->slice_table[h->top_mb_xy] ||
  5652. h->slice_table[mb_xy] != h->slice_table[mb_xy - 1]))) {
  5653. filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
  5654. return;
  5655. }
  5656. assert(!FRAME_MBAFF);
  5657. mb_type = s->current_picture.mb_type[mb_xy];
  5658. qp = s->current_picture.qscale_table[mb_xy];
  5659. qp0 = s->current_picture.qscale_table[mb_xy-1];
  5660. qp1 = s->current_picture.qscale_table[h->top_mb_xy];
  5661. qpc = get_chroma_qp( h, 0, qp );
  5662. qpc0 = get_chroma_qp( h, 0, qp0 );
  5663. qpc1 = get_chroma_qp( h, 0, qp1 );
  5664. qp0 = (qp + qp0 + 1) >> 1;
  5665. qp1 = (qp + qp1 + 1) >> 1;
  5666. qpc0 = (qpc + qpc0 + 1) >> 1;
  5667. qpc1 = (qpc + qpc1 + 1) >> 1;
  5668. qp_thresh = 15 - h->slice_alpha_c0_offset;
  5669. if(qp <= qp_thresh && qp0 <= qp_thresh && qp1 <= qp_thresh &&
  5670. qpc <= qp_thresh && qpc0 <= qp_thresh && qpc1 <= qp_thresh)
  5671. return;
  5672. if( IS_INTRA(mb_type) ) {
  5673. int16_t bS4[4] = {4,4,4,4};
  5674. int16_t bS3[4] = {3,3,3,3};
  5675. int16_t *bSH = FIELD_PICTURE ? bS3 : bS4;
  5676. if( IS_8x8DCT(mb_type) ) {
  5677. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5678. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5679. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5680. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5681. } else {
  5682. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5683. filter_mb_edgev( h, &img_y[4*1], linesize, bS3, qp );
  5684. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5685. filter_mb_edgev( h, &img_y[4*3], linesize, bS3, qp );
  5686. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5687. filter_mb_edgeh( h, &img_y[4*1*linesize], linesize, bS3, qp );
  5688. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5689. filter_mb_edgeh( h, &img_y[4*3*linesize], linesize, bS3, qp );
  5690. }
  5691. filter_mb_edgecv( h, &img_cb[2*0], uvlinesize, bS4, qpc0 );
  5692. filter_mb_edgecv( h, &img_cb[2*2], uvlinesize, bS3, qpc );
  5693. filter_mb_edgecv( h, &img_cr[2*0], uvlinesize, bS4, qpc0 );
  5694. filter_mb_edgecv( h, &img_cr[2*2], uvlinesize, bS3, qpc );
  5695. filter_mb_edgech( h, &img_cb[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5696. filter_mb_edgech( h, &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5697. filter_mb_edgech( h, &img_cr[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5698. filter_mb_edgech( h, &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5699. return;
  5700. } else {
  5701. DECLARE_ALIGNED_8(int16_t, bS[2][4][4]);
  5702. uint64_t (*bSv)[4] = (uint64_t(*)[4])bS;
  5703. int edges;
  5704. if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 ) {
  5705. edges = 4;
  5706. bSv[0][0] = bSv[0][2] = bSv[1][0] = bSv[1][2] = 0x0002000200020002ULL;
  5707. } else {
  5708. int mask_edge1 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 :
  5709. (mb_type & MB_TYPE_16x8) ? 1 : 0;
  5710. int mask_edge0 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5711. && (s->current_picture.mb_type[mb_xy-1] & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5712. ? 3 : 0;
  5713. int step = IS_8x8DCT(mb_type) ? 2 : 1;
  5714. edges = (mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
  5715. s->dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,
  5716. (h->slice_type == B_TYPE), edges, step, mask_edge0, mask_edge1 );
  5717. }
  5718. if( IS_INTRA(s->current_picture.mb_type[mb_xy-1]) )
  5719. bSv[0][0] = 0x0004000400040004ULL;
  5720. if( IS_INTRA(s->current_picture.mb_type[h->top_mb_xy]) )
  5721. bSv[1][0] = FIELD_PICTURE ? 0x0003000300030003ULL : 0x0004000400040004ULL;
  5722. #define FILTER(hv,dir,edge)\
  5723. if(bSv[dir][edge]) {\
  5724. filter_mb_edge##hv( h, &img_y[4*edge*(dir?linesize:1)], linesize, bS[dir][edge], edge ? qp : qp##dir );\
  5725. if(!(edge&1)) {\
  5726. filter_mb_edgec##hv( h, &img_cb[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5727. filter_mb_edgec##hv( h, &img_cr[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5728. }\
  5729. }
  5730. if( edges == 1 ) {
  5731. FILTER(v,0,0);
  5732. FILTER(h,1,0);
  5733. } else if( IS_8x8DCT(mb_type) ) {
  5734. FILTER(v,0,0);
  5735. FILTER(v,0,2);
  5736. FILTER(h,1,0);
  5737. FILTER(h,1,2);
  5738. } else {
  5739. FILTER(v,0,0);
  5740. FILTER(v,0,1);
  5741. FILTER(v,0,2);
  5742. FILTER(v,0,3);
  5743. FILTER(h,1,0);
  5744. FILTER(h,1,1);
  5745. FILTER(h,1,2);
  5746. FILTER(h,1,3);
  5747. }
  5748. #undef FILTER
  5749. }
  5750. }
  5751. static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
  5752. MpegEncContext * const s = &h->s;
  5753. const int mb_xy= mb_x + mb_y*s->mb_stride;
  5754. const int mb_type = s->current_picture.mb_type[mb_xy];
  5755. const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;
  5756. int first_vertical_edge_done = 0;
  5757. int dir;
  5758. /* FIXME: A given frame may occupy more than one position in
  5759. * the reference list. So ref2frm should be populated with
  5760. * frame numbers, not indices. */
  5761. static const int ref2frm[34] = {-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  5762. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
  5763. //for sufficiently low qp, filtering wouldn't do anything
  5764. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  5765. if(!FRAME_MBAFF){
  5766. int qp_thresh = 15 - h->slice_alpha_c0_offset - FFMAX(0, FFMAX(h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]));
  5767. int qp = s->current_picture.qscale_table[mb_xy];
  5768. if(qp <= qp_thresh
  5769. && (mb_x == 0 || ((qp + s->current_picture.qscale_table[mb_xy-1] + 1)>>1) <= qp_thresh)
  5770. && (mb_y == 0 || ((qp + s->current_picture.qscale_table[h->top_mb_xy] + 1)>>1) <= qp_thresh)){
  5771. return;
  5772. }
  5773. }
  5774. if (FRAME_MBAFF
  5775. // left mb is in picture
  5776. && h->slice_table[mb_xy-1] != 255
  5777. // and current and left pair do not have the same interlaced type
  5778. && (IS_INTERLACED(mb_type) != IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]))
  5779. // and left mb is in the same slice if deblocking_filter == 2
  5780. && (h->deblocking_filter!=2 || h->slice_table[mb_xy-1] == h->slice_table[mb_xy])) {
  5781. /* First vertical edge is different in MBAFF frames
  5782. * There are 8 different bS to compute and 2 different Qp
  5783. */
  5784. const int pair_xy = mb_x + (mb_y&~1)*s->mb_stride;
  5785. const int left_mb_xy[2] = { pair_xy-1, pair_xy-1+s->mb_stride };
  5786. int16_t bS[8];
  5787. int qp[2];
  5788. int bqp[2];
  5789. int rqp[2];
  5790. int mb_qp, mbn0_qp, mbn1_qp;
  5791. int i;
  5792. first_vertical_edge_done = 1;
  5793. if( IS_INTRA(mb_type) )
  5794. bS[0] = bS[1] = bS[2] = bS[3] = bS[4] = bS[5] = bS[6] = bS[7] = 4;
  5795. else {
  5796. for( i = 0; i < 8; i++ ) {
  5797. int mbn_xy = MB_FIELD ? left_mb_xy[i>>2] : left_mb_xy[i&1];
  5798. if( IS_INTRA( s->current_picture.mb_type[mbn_xy] ) )
  5799. bS[i] = 4;
  5800. else if( h->non_zero_count_cache[12+8*(i>>1)] != 0 ||
  5801. /* FIXME: with 8x8dct + cavlc, should check cbp instead of nnz */
  5802. h->non_zero_count[mbn_xy][MB_FIELD ? i&3 : (i>>2)+(mb_y&1)*2] )
  5803. bS[i] = 2;
  5804. else
  5805. bS[i] = 1;
  5806. }
  5807. }
  5808. mb_qp = s->current_picture.qscale_table[mb_xy];
  5809. mbn0_qp = s->current_picture.qscale_table[left_mb_xy[0]];
  5810. mbn1_qp = s->current_picture.qscale_table[left_mb_xy[1]];
  5811. qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;
  5812. bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +
  5813. get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;
  5814. rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +
  5815. get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;
  5816. qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;
  5817. bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +
  5818. get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;
  5819. rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +
  5820. get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;
  5821. /* Filter edge */
  5822. tprintf(s->avctx, "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d", mb_x, mb_y, qp[0], qp[1], bqp[0], bqp[1], rqp[0], rqp[1], linesize, uvlinesize);
  5823. { int i; for (i = 0; i < 8; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5824. filter_mb_mbaff_edgev ( h, &img_y [0], linesize, bS, qp );
  5825. filter_mb_mbaff_edgecv( h, &img_cb[0], uvlinesize, bS, bqp );
  5826. filter_mb_mbaff_edgecv( h, &img_cr[0], uvlinesize, bS, rqp );
  5827. }
  5828. /* dir : 0 -> vertical edge, 1 -> horizontal edge */
  5829. for( dir = 0; dir < 2; dir++ )
  5830. {
  5831. int edge;
  5832. const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
  5833. const int mbm_type = s->current_picture.mb_type[mbm_xy];
  5834. int start = h->slice_table[mbm_xy] == 255 ? 1 : 0;
  5835. const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))
  5836. == (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;
  5837. // how often to recheck mv-based bS when iterating between edges
  5838. const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :
  5839. (mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;
  5840. // how often to recheck mv-based bS when iterating along each edge
  5841. const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
  5842. if (first_vertical_edge_done) {
  5843. start = 1;
  5844. first_vertical_edge_done = 0;
  5845. }
  5846. if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])
  5847. start = 1;
  5848. if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0
  5849. && !IS_INTERLACED(mb_type)
  5850. && IS_INTERLACED(mbm_type)
  5851. ) {
  5852. // This is a special case in the norm where the filtering must
  5853. // be done twice (one each of the field) even if we are in a
  5854. // frame macroblock.
  5855. //
  5856. static const int nnz_idx[4] = {4,5,6,3};
  5857. unsigned int tmp_linesize = 2 * linesize;
  5858. unsigned int tmp_uvlinesize = 2 * uvlinesize;
  5859. int mbn_xy = mb_xy - 2 * s->mb_stride;
  5860. int qp;
  5861. int i, j;
  5862. int16_t bS[4];
  5863. for(j=0; j<2; j++, mbn_xy += s->mb_stride){
  5864. if( IS_INTRA(mb_type) ||
  5865. IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {
  5866. bS[0] = bS[1] = bS[2] = bS[3] = 3;
  5867. } else {
  5868. const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];
  5869. for( i = 0; i < 4; i++ ) {
  5870. if( h->non_zero_count_cache[scan8[0]+i] != 0 ||
  5871. mbn_nnz[nnz_idx[i]] != 0 )
  5872. bS[i] = 2;
  5873. else
  5874. bS[i] = 1;
  5875. }
  5876. }
  5877. // Do not use s->qscale as luma quantizer because it has not the same
  5878. // value in IPCM macroblocks.
  5879. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5880. tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, tmp_linesize, tmp_uvlinesize);
  5881. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5882. filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );
  5883. filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,
  5884. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5885. filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,
  5886. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5887. }
  5888. start = 1;
  5889. }
  5890. /* Calculate bS */
  5891. for( edge = start; edge < edges; edge++ ) {
  5892. /* mbn_xy: neighbor macroblock */
  5893. const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;
  5894. const int mbn_type = s->current_picture.mb_type[mbn_xy];
  5895. int16_t bS[4];
  5896. int qp;
  5897. if( (edge&1) && IS_8x8DCT(mb_type) )
  5898. continue;
  5899. if( IS_INTRA(mb_type) ||
  5900. IS_INTRA(mbn_type) ) {
  5901. int value;
  5902. if (edge == 0) {
  5903. if ( (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))
  5904. || ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))
  5905. ) {
  5906. value = 4;
  5907. } else {
  5908. value = 3;
  5909. }
  5910. } else {
  5911. value = 3;
  5912. }
  5913. bS[0] = bS[1] = bS[2] = bS[3] = value;
  5914. } else {
  5915. int i, l;
  5916. int mv_done;
  5917. if( edge & mask_edge ) {
  5918. bS[0] = bS[1] = bS[2] = bS[3] = 0;
  5919. mv_done = 1;
  5920. }
  5921. else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {
  5922. bS[0] = bS[1] = bS[2] = bS[3] = 1;
  5923. mv_done = 1;
  5924. }
  5925. else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {
  5926. int b_idx= 8 + 4 + edge * (dir ? 8:1);
  5927. int bn_idx= b_idx - (dir ? 8:1);
  5928. int v = 0;
  5929. for( l = 0; !v && l < 1 + (h->slice_type == B_TYPE); l++ ) {
  5930. v |= ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5931. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5932. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit;
  5933. }
  5934. bS[0] = bS[1] = bS[2] = bS[3] = v;
  5935. mv_done = 1;
  5936. }
  5937. else
  5938. mv_done = 0;
  5939. for( i = 0; i < 4; i++ ) {
  5940. int x = dir == 0 ? edge : i;
  5941. int y = dir == 0 ? i : edge;
  5942. int b_idx= 8 + 4 + x + 8*y;
  5943. int bn_idx= b_idx - (dir ? 8:1);
  5944. if( h->non_zero_count_cache[b_idx] != 0 ||
  5945. h->non_zero_count_cache[bn_idx] != 0 ) {
  5946. bS[i] = 2;
  5947. }
  5948. else if(!mv_done)
  5949. {
  5950. bS[i] = 0;
  5951. for( l = 0; l < 1 + (h->slice_type == B_TYPE); l++ ) {
  5952. if( ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5953. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5954. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit ) {
  5955. bS[i] = 1;
  5956. break;
  5957. }
  5958. }
  5959. }
  5960. }
  5961. if(bS[0]+bS[1]+bS[2]+bS[3] == 0)
  5962. continue;
  5963. }
  5964. /* Filter edge */
  5965. // Do not use s->qscale as luma quantizer because it has not the same
  5966. // value in IPCM macroblocks.
  5967. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5968. //tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp, s->current_picture.qscale_table[mbn_xy]);
  5969. tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);
  5970. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5971. if( dir == 0 ) {
  5972. filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );
  5973. if( (edge&1) == 0 ) {
  5974. filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,
  5975. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5976. filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,
  5977. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5978. }
  5979. } else {
  5980. filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );
  5981. if( (edge&1) == 0 ) {
  5982. filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,
  5983. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5984. filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,
  5985. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5986. }
  5987. }
  5988. }
  5989. }
  5990. }
  5991. static int decode_slice(struct AVCodecContext *avctx, H264Context *h){
  5992. MpegEncContext * const s = &h->s;
  5993. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  5994. s->mb_skip_run= -1;
  5995. if( h->pps.cabac ) {
  5996. int i;
  5997. /* realign */
  5998. align_get_bits( &s->gb );
  5999. /* init cabac */
  6000. ff_init_cabac_states( &h->cabac);
  6001. ff_init_cabac_decoder( &h->cabac,
  6002. s->gb.buffer + get_bits_count(&s->gb)/8,
  6003. ( s->gb.size_in_bits - get_bits_count(&s->gb) + 7)/8);
  6004. /* calculate pre-state */
  6005. for( i= 0; i < 460; i++ ) {
  6006. int pre;
  6007. if( h->slice_type == I_TYPE )
  6008. pre = av_clip( ((cabac_context_init_I[i][0] * s->qscale) >>4 ) + cabac_context_init_I[i][1], 1, 126 );
  6009. else
  6010. pre = av_clip( ((cabac_context_init_PB[h->cabac_init_idc][i][0] * s->qscale) >>4 ) + cabac_context_init_PB[h->cabac_init_idc][i][1], 1, 126 );
  6011. if( pre <= 63 )
  6012. h->cabac_state[i] = 2 * ( 63 - pre ) + 0;
  6013. else
  6014. h->cabac_state[i] = 2 * ( pre - 64 ) + 1;
  6015. }
  6016. for(;;){
  6017. //START_TIMER
  6018. int ret = decode_mb_cabac(h);
  6019. int eos;
  6020. //STOP_TIMER("decode_mb_cabac")
  6021. if(ret>=0) hl_decode_mb(h);
  6022. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  6023. s->mb_y++;
  6024. if(ret>=0) ret = decode_mb_cabac(h);
  6025. if(ret>=0) hl_decode_mb(h);
  6026. s->mb_y--;
  6027. }
  6028. eos = get_cabac_terminate( &h->cabac );
  6029. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  6030. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream (%td)\n", s->mb_x, s->mb_y, h->cabac.bytestream_end - h->cabac.bytestream);
  6031. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6032. return -1;
  6033. }
  6034. if( ++s->mb_x >= s->mb_width ) {
  6035. s->mb_x = 0;
  6036. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6037. ++s->mb_y;
  6038. if(FIELD_OR_MBAFF_PICTURE) {
  6039. ++s->mb_y;
  6040. }
  6041. }
  6042. if( eos || s->mb_y >= s->mb_height ) {
  6043. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6044. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6045. return 0;
  6046. }
  6047. }
  6048. } else {
  6049. for(;;){
  6050. int ret = decode_mb_cavlc(h);
  6051. if(ret>=0) hl_decode_mb(h);
  6052. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  6053. s->mb_y++;
  6054. ret = decode_mb_cavlc(h);
  6055. if(ret>=0) hl_decode_mb(h);
  6056. s->mb_y--;
  6057. }
  6058. if(ret<0){
  6059. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  6060. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6061. return -1;
  6062. }
  6063. if(++s->mb_x >= s->mb_width){
  6064. s->mb_x=0;
  6065. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6066. ++s->mb_y;
  6067. if(FIELD_OR_MBAFF_PICTURE) {
  6068. ++s->mb_y;
  6069. }
  6070. if(s->mb_y >= s->mb_height){
  6071. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6072. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  6073. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6074. return 0;
  6075. }else{
  6076. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6077. return -1;
  6078. }
  6079. }
  6080. }
  6081. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  6082. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6083. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  6084. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6085. return 0;
  6086. }else{
  6087. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6088. return -1;
  6089. }
  6090. }
  6091. }
  6092. }
  6093. #if 0
  6094. for(;s->mb_y < s->mb_height; s->mb_y++){
  6095. for(;s->mb_x < s->mb_width; s->mb_x++){
  6096. int ret= decode_mb(h);
  6097. hl_decode_mb(h);
  6098. if(ret<0){
  6099. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  6100. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6101. return -1;
  6102. }
  6103. if(++s->mb_x >= s->mb_width){
  6104. s->mb_x=0;
  6105. if(++s->mb_y >= s->mb_height){
  6106. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6107. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6108. return 0;
  6109. }else{
  6110. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6111. return -1;
  6112. }
  6113. }
  6114. }
  6115. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  6116. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6117. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6118. return 0;
  6119. }else{
  6120. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6121. return -1;
  6122. }
  6123. }
  6124. }
  6125. s->mb_x=0;
  6126. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6127. }
  6128. #endif
  6129. return -1; //not reached
  6130. }
  6131. static int decode_unregistered_user_data(H264Context *h, int size){
  6132. MpegEncContext * const s = &h->s;
  6133. uint8_t user_data[16+256];
  6134. int e, build, i;
  6135. if(size<16)
  6136. return -1;
  6137. for(i=0; i<sizeof(user_data)-1 && i<size; i++){
  6138. user_data[i]= get_bits(&s->gb, 8);
  6139. }
  6140. user_data[i]= 0;
  6141. e= sscanf(user_data+16, "x264 - core %d"/*%s - H.264/MPEG-4 AVC codec - Copyleft 2005 - http://www.videolan.org/x264.html*/, &build);
  6142. if(e==1 && build>=0)
  6143. h->x264_build= build;
  6144. if(s->avctx->debug & FF_DEBUG_BUGS)
  6145. av_log(s->avctx, AV_LOG_DEBUG, "user data:\"%s\"\n", user_data+16);
  6146. for(; i<size; i++)
  6147. skip_bits(&s->gb, 8);
  6148. return 0;
  6149. }
  6150. static int decode_sei(H264Context *h){
  6151. MpegEncContext * const s = &h->s;
  6152. while(get_bits_count(&s->gb) + 16 < s->gb.size_in_bits){
  6153. int size, type;
  6154. type=0;
  6155. do{
  6156. type+= show_bits(&s->gb, 8);
  6157. }while(get_bits(&s->gb, 8) == 255);
  6158. size=0;
  6159. do{
  6160. size+= show_bits(&s->gb, 8);
  6161. }while(get_bits(&s->gb, 8) == 255);
  6162. switch(type){
  6163. case 5:
  6164. if(decode_unregistered_user_data(h, size) < 0)
  6165. return -1;
  6166. break;
  6167. default:
  6168. skip_bits(&s->gb, 8*size);
  6169. }
  6170. //FIXME check bits here
  6171. align_get_bits(&s->gb);
  6172. }
  6173. return 0;
  6174. }
  6175. static inline void decode_hrd_parameters(H264Context *h, SPS *sps){
  6176. MpegEncContext * const s = &h->s;
  6177. int cpb_count, i;
  6178. cpb_count = get_ue_golomb(&s->gb) + 1;
  6179. get_bits(&s->gb, 4); /* bit_rate_scale */
  6180. get_bits(&s->gb, 4); /* cpb_size_scale */
  6181. for(i=0; i<cpb_count; i++){
  6182. get_ue_golomb(&s->gb); /* bit_rate_value_minus1 */
  6183. get_ue_golomb(&s->gb); /* cpb_size_value_minus1 */
  6184. get_bits1(&s->gb); /* cbr_flag */
  6185. }
  6186. get_bits(&s->gb, 5); /* initial_cpb_removal_delay_length_minus1 */
  6187. get_bits(&s->gb, 5); /* cpb_removal_delay_length_minus1 */
  6188. get_bits(&s->gb, 5); /* dpb_output_delay_length_minus1 */
  6189. get_bits(&s->gb, 5); /* time_offset_length */
  6190. }
  6191. static inline int decode_vui_parameters(H264Context *h, SPS *sps){
  6192. MpegEncContext * const s = &h->s;
  6193. int aspect_ratio_info_present_flag;
  6194. unsigned int aspect_ratio_idc;
  6195. int nal_hrd_parameters_present_flag, vcl_hrd_parameters_present_flag;
  6196. aspect_ratio_info_present_flag= get_bits1(&s->gb);
  6197. if( aspect_ratio_info_present_flag ) {
  6198. aspect_ratio_idc= get_bits(&s->gb, 8);
  6199. if( aspect_ratio_idc == EXTENDED_SAR ) {
  6200. sps->sar.num= get_bits(&s->gb, 16);
  6201. sps->sar.den= get_bits(&s->gb, 16);
  6202. }else if(aspect_ratio_idc < 14){
  6203. sps->sar= pixel_aspect[aspect_ratio_idc];
  6204. }else{
  6205. av_log(h->s.avctx, AV_LOG_ERROR, "illegal aspect ratio\n");
  6206. return -1;
  6207. }
  6208. }else{
  6209. sps->sar.num=
  6210. sps->sar.den= 0;
  6211. }
  6212. // s->avctx->aspect_ratio= sar_width*s->width / (float)(s->height*sar_height);
  6213. if(get_bits1(&s->gb)){ /* overscan_info_present_flag */
  6214. get_bits1(&s->gb); /* overscan_appropriate_flag */
  6215. }
  6216. if(get_bits1(&s->gb)){ /* video_signal_type_present_flag */
  6217. get_bits(&s->gb, 3); /* video_format */
  6218. get_bits1(&s->gb); /* video_full_range_flag */
  6219. if(get_bits1(&s->gb)){ /* colour_description_present_flag */
  6220. get_bits(&s->gb, 8); /* colour_primaries */
  6221. get_bits(&s->gb, 8); /* transfer_characteristics */
  6222. get_bits(&s->gb, 8); /* matrix_coefficients */
  6223. }
  6224. }
  6225. if(get_bits1(&s->gb)){ /* chroma_location_info_present_flag */
  6226. get_ue_golomb(&s->gb); /* chroma_sample_location_type_top_field */
  6227. get_ue_golomb(&s->gb); /* chroma_sample_location_type_bottom_field */
  6228. }
  6229. sps->timing_info_present_flag = get_bits1(&s->gb);
  6230. if(sps->timing_info_present_flag){
  6231. sps->num_units_in_tick = get_bits_long(&s->gb, 32);
  6232. sps->time_scale = get_bits_long(&s->gb, 32);
  6233. sps->fixed_frame_rate_flag = get_bits1(&s->gb);
  6234. }
  6235. nal_hrd_parameters_present_flag = get_bits1(&s->gb);
  6236. if(nal_hrd_parameters_present_flag)
  6237. decode_hrd_parameters(h, sps);
  6238. vcl_hrd_parameters_present_flag = get_bits1(&s->gb);
  6239. if(vcl_hrd_parameters_present_flag)
  6240. decode_hrd_parameters(h, sps);
  6241. if(nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag)
  6242. get_bits1(&s->gb); /* low_delay_hrd_flag */
  6243. get_bits1(&s->gb); /* pic_struct_present_flag */
  6244. sps->bitstream_restriction_flag = get_bits1(&s->gb);
  6245. if(sps->bitstream_restriction_flag){
  6246. unsigned int num_reorder_frames;
  6247. get_bits1(&s->gb); /* motion_vectors_over_pic_boundaries_flag */
  6248. get_ue_golomb(&s->gb); /* max_bytes_per_pic_denom */
  6249. get_ue_golomb(&s->gb); /* max_bits_per_mb_denom */
  6250. get_ue_golomb(&s->gb); /* log2_max_mv_length_horizontal */
  6251. get_ue_golomb(&s->gb); /* log2_max_mv_length_vertical */
  6252. num_reorder_frames= get_ue_golomb(&s->gb);
  6253. get_ue_golomb(&s->gb); /*max_dec_frame_buffering*/
  6254. if(num_reorder_frames > 16 /*max_dec_frame_buffering || max_dec_frame_buffering > 16*/){
  6255. av_log(h->s.avctx, AV_LOG_ERROR, "illegal num_reorder_frames %d\n", num_reorder_frames);
  6256. return -1;
  6257. }
  6258. sps->num_reorder_frames= num_reorder_frames;
  6259. }
  6260. return 0;
  6261. }
  6262. static void decode_scaling_list(H264Context *h, uint8_t *factors, int size,
  6263. const uint8_t *jvt_list, const uint8_t *fallback_list){
  6264. MpegEncContext * const s = &h->s;
  6265. int i, last = 8, next = 8;
  6266. const uint8_t *scan = size == 16 ? zigzag_scan : zigzag_scan8x8;
  6267. if(!get_bits1(&s->gb)) /* matrix not written, we use the predicted one */
  6268. memcpy(factors, fallback_list, size*sizeof(uint8_t));
  6269. else
  6270. for(i=0;i<size;i++){
  6271. if(next)
  6272. next = (last + get_se_golomb(&s->gb)) & 0xff;
  6273. if(!i && !next){ /* matrix not written, we use the preset one */
  6274. memcpy(factors, jvt_list, size*sizeof(uint8_t));
  6275. break;
  6276. }
  6277. last = factors[scan[i]] = next ? next : last;
  6278. }
  6279. }
  6280. static void decode_scaling_matrices(H264Context *h, SPS *sps, PPS *pps, int is_sps,
  6281. uint8_t (*scaling_matrix4)[16], uint8_t (*scaling_matrix8)[64]){
  6282. MpegEncContext * const s = &h->s;
  6283. int fallback_sps = !is_sps && sps->scaling_matrix_present;
  6284. const uint8_t *fallback[4] = {
  6285. fallback_sps ? sps->scaling_matrix4[0] : default_scaling4[0],
  6286. fallback_sps ? sps->scaling_matrix4[3] : default_scaling4[1],
  6287. fallback_sps ? sps->scaling_matrix8[0] : default_scaling8[0],
  6288. fallback_sps ? sps->scaling_matrix8[1] : default_scaling8[1]
  6289. };
  6290. if(get_bits1(&s->gb)){
  6291. sps->scaling_matrix_present |= is_sps;
  6292. decode_scaling_list(h,scaling_matrix4[0],16,default_scaling4[0],fallback[0]); // Intra, Y
  6293. decode_scaling_list(h,scaling_matrix4[1],16,default_scaling4[0],scaling_matrix4[0]); // Intra, Cr
  6294. decode_scaling_list(h,scaling_matrix4[2],16,default_scaling4[0],scaling_matrix4[1]); // Intra, Cb
  6295. decode_scaling_list(h,scaling_matrix4[3],16,default_scaling4[1],fallback[1]); // Inter, Y
  6296. decode_scaling_list(h,scaling_matrix4[4],16,default_scaling4[1],scaling_matrix4[3]); // Inter, Cr
  6297. decode_scaling_list(h,scaling_matrix4[5],16,default_scaling4[1],scaling_matrix4[4]); // Inter, Cb
  6298. if(is_sps || pps->transform_8x8_mode){
  6299. decode_scaling_list(h,scaling_matrix8[0],64,default_scaling8[0],fallback[2]); // Intra, Y
  6300. decode_scaling_list(h,scaling_matrix8[1],64,default_scaling8[1],fallback[3]); // Inter, Y
  6301. }
  6302. } else if(fallback_sps) {
  6303. memcpy(scaling_matrix4, sps->scaling_matrix4, 6*16*sizeof(uint8_t));
  6304. memcpy(scaling_matrix8, sps->scaling_matrix8, 2*64*sizeof(uint8_t));
  6305. }
  6306. }
  6307. /**
  6308. * Returns and optionally allocates SPS / PPS structures in the supplied array 'vec'
  6309. */
  6310. static void *
  6311. alloc_parameter_set(H264Context *h, void **vec, const unsigned int id, const unsigned int max,
  6312. const size_t size, const char *name)
  6313. {
  6314. if(id>=max) {
  6315. av_log(h->s.avctx, AV_LOG_ERROR, "%s_id (%d) out of range\n", name, id);
  6316. return NULL;
  6317. }
  6318. if(!vec[id]) {
  6319. vec[id] = av_mallocz(size);
  6320. if(vec[id] == NULL)
  6321. av_log(h->s.avctx, AV_LOG_ERROR, "cannot allocate memory for %s\n", name);
  6322. }
  6323. return vec[id];
  6324. }
  6325. static inline int decode_seq_parameter_set(H264Context *h){
  6326. MpegEncContext * const s = &h->s;
  6327. int profile_idc, level_idc;
  6328. unsigned int sps_id, tmp, mb_width, mb_height;
  6329. int i;
  6330. SPS *sps;
  6331. profile_idc= get_bits(&s->gb, 8);
  6332. get_bits1(&s->gb); //constraint_set0_flag
  6333. get_bits1(&s->gb); //constraint_set1_flag
  6334. get_bits1(&s->gb); //constraint_set2_flag
  6335. get_bits1(&s->gb); //constraint_set3_flag
  6336. get_bits(&s->gb, 4); // reserved
  6337. level_idc= get_bits(&s->gb, 8);
  6338. sps_id= get_ue_golomb(&s->gb);
  6339. sps = alloc_parameter_set(h, (void **)h->sps_buffers, sps_id, MAX_SPS_COUNT, sizeof(SPS), "sps");
  6340. if(sps == NULL)
  6341. return -1;
  6342. sps->profile_idc= profile_idc;
  6343. sps->level_idc= level_idc;
  6344. if(sps->profile_idc >= 100){ //high profile
  6345. if(get_ue_golomb(&s->gb) == 3) //chroma_format_idc
  6346. get_bits1(&s->gb); //residual_color_transform_flag
  6347. get_ue_golomb(&s->gb); //bit_depth_luma_minus8
  6348. get_ue_golomb(&s->gb); //bit_depth_chroma_minus8
  6349. sps->transform_bypass = get_bits1(&s->gb);
  6350. decode_scaling_matrices(h, sps, NULL, 1, sps->scaling_matrix4, sps->scaling_matrix8);
  6351. }else
  6352. sps->scaling_matrix_present = 0;
  6353. sps->log2_max_frame_num= get_ue_golomb(&s->gb) + 4;
  6354. sps->poc_type= get_ue_golomb(&s->gb);
  6355. if(sps->poc_type == 0){ //FIXME #define
  6356. sps->log2_max_poc_lsb= get_ue_golomb(&s->gb) + 4;
  6357. } else if(sps->poc_type == 1){//FIXME #define
  6358. sps->delta_pic_order_always_zero_flag= get_bits1(&s->gb);
  6359. sps->offset_for_non_ref_pic= get_se_golomb(&s->gb);
  6360. sps->offset_for_top_to_bottom_field= get_se_golomb(&s->gb);
  6361. tmp= get_ue_golomb(&s->gb);
  6362. if(tmp >= sizeof(sps->offset_for_ref_frame) / sizeof(sps->offset_for_ref_frame[0])){
  6363. av_log(h->s.avctx, AV_LOG_ERROR, "poc_cycle_length overflow %u\n", tmp);
  6364. return -1;
  6365. }
  6366. sps->poc_cycle_length= tmp;
  6367. for(i=0; i<sps->poc_cycle_length; i++)
  6368. sps->offset_for_ref_frame[i]= get_se_golomb(&s->gb);
  6369. }else if(sps->poc_type != 2){
  6370. av_log(h->s.avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);
  6371. return -1;
  6372. }
  6373. tmp= get_ue_golomb(&s->gb);
  6374. if(tmp > MAX_PICTURE_COUNT-2){
  6375. av_log(h->s.avctx, AV_LOG_ERROR, "too many reference frames\n");
  6376. }
  6377. sps->ref_frame_count= tmp;
  6378. sps->gaps_in_frame_num_allowed_flag= get_bits1(&s->gb);
  6379. mb_width= get_ue_golomb(&s->gb) + 1;
  6380. mb_height= get_ue_golomb(&s->gb) + 1;
  6381. if(mb_width >= INT_MAX/16 || mb_height >= INT_MAX/16 ||
  6382. avcodec_check_dimensions(NULL, 16*mb_width, 16*mb_height)){
  6383. av_log(h->s.avctx, AV_LOG_ERROR, "mb_width/height overflow\n");
  6384. return -1;
  6385. }
  6386. sps->mb_width = mb_width;
  6387. sps->mb_height= mb_height;
  6388. sps->frame_mbs_only_flag= get_bits1(&s->gb);
  6389. if(!sps->frame_mbs_only_flag)
  6390. sps->mb_aff= get_bits1(&s->gb);
  6391. else
  6392. sps->mb_aff= 0;
  6393. sps->direct_8x8_inference_flag= get_bits1(&s->gb);
  6394. #ifndef ALLOW_INTERLACE
  6395. if(sps->mb_aff)
  6396. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF support not included; enable it at compile-time.\n");
  6397. #endif
  6398. if(!sps->direct_8x8_inference_flag && sps->mb_aff)
  6399. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF + !direct_8x8_inference is not implemented\n");
  6400. sps->crop= get_bits1(&s->gb);
  6401. if(sps->crop){
  6402. sps->crop_left = get_ue_golomb(&s->gb);
  6403. sps->crop_right = get_ue_golomb(&s->gb);
  6404. sps->crop_top = get_ue_golomb(&s->gb);
  6405. sps->crop_bottom= get_ue_golomb(&s->gb);
  6406. if(sps->crop_left || sps->crop_top){
  6407. av_log(h->s.avctx, AV_LOG_ERROR, "insane cropping not completely supported, this could look slightly wrong ...\n");
  6408. }
  6409. }else{
  6410. sps->crop_left =
  6411. sps->crop_right =
  6412. sps->crop_top =
  6413. sps->crop_bottom= 0;
  6414. }
  6415. sps->vui_parameters_present_flag= get_bits1(&s->gb);
  6416. if( sps->vui_parameters_present_flag )
  6417. decode_vui_parameters(h, sps);
  6418. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6419. av_log(h->s.avctx, AV_LOG_DEBUG, "sps:%u profile:%d/%d poc:%d ref:%d %dx%d %s %s crop:%d/%d/%d/%d %s\n",
  6420. sps_id, sps->profile_idc, sps->level_idc,
  6421. sps->poc_type,
  6422. sps->ref_frame_count,
  6423. sps->mb_width, sps->mb_height,
  6424. sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),
  6425. sps->direct_8x8_inference_flag ? "8B8" : "",
  6426. sps->crop_left, sps->crop_right,
  6427. sps->crop_top, sps->crop_bottom,
  6428. sps->vui_parameters_present_flag ? "VUI" : ""
  6429. );
  6430. }
  6431. return 0;
  6432. }
  6433. static void
  6434. build_qp_table(PPS *pps, int t, int index)
  6435. {
  6436. int i;
  6437. for(i = 0; i < 255; i++)
  6438. pps->chroma_qp_table[t][i & 0xff] = chroma_qp[av_clip(i + index, 0, 51)];
  6439. }
  6440. static inline int decode_picture_parameter_set(H264Context *h, int bit_length){
  6441. MpegEncContext * const s = &h->s;
  6442. unsigned int tmp, pps_id= get_ue_golomb(&s->gb);
  6443. PPS *pps;
  6444. pps = alloc_parameter_set(h, (void **)h->pps_buffers, pps_id, MAX_PPS_COUNT, sizeof(PPS), "pps");
  6445. if(pps == NULL)
  6446. return -1;
  6447. tmp= get_ue_golomb(&s->gb);
  6448. if(tmp>=MAX_SPS_COUNT || h->sps_buffers[tmp] == NULL){
  6449. av_log(h->s.avctx, AV_LOG_ERROR, "sps_id out of range\n");
  6450. return -1;
  6451. }
  6452. pps->sps_id= tmp;
  6453. pps->cabac= get_bits1(&s->gb);
  6454. pps->pic_order_present= get_bits1(&s->gb);
  6455. pps->slice_group_count= get_ue_golomb(&s->gb) + 1;
  6456. if(pps->slice_group_count > 1 ){
  6457. pps->mb_slice_group_map_type= get_ue_golomb(&s->gb);
  6458. av_log(h->s.avctx, AV_LOG_ERROR, "FMO not supported\n");
  6459. switch(pps->mb_slice_group_map_type){
  6460. case 0:
  6461. #if 0
  6462. | for( i = 0; i <= num_slice_groups_minus1; i++ ) | | |
  6463. | run_length[ i ] |1 |ue(v) |
  6464. #endif
  6465. break;
  6466. case 2:
  6467. #if 0
  6468. | for( i = 0; i < num_slice_groups_minus1; i++ ) | | |
  6469. |{ | | |
  6470. | top_left_mb[ i ] |1 |ue(v) |
  6471. | bottom_right_mb[ i ] |1 |ue(v) |
  6472. | } | | |
  6473. #endif
  6474. break;
  6475. case 3:
  6476. case 4:
  6477. case 5:
  6478. #if 0
  6479. | slice_group_change_direction_flag |1 |u(1) |
  6480. | slice_group_change_rate_minus1 |1 |ue(v) |
  6481. #endif
  6482. break;
  6483. case 6:
  6484. #if 0
  6485. | slice_group_id_cnt_minus1 |1 |ue(v) |
  6486. | for( i = 0; i <= slice_group_id_cnt_minus1; i++ | | |
  6487. |) | | |
  6488. | slice_group_id[ i ] |1 |u(v) |
  6489. #endif
  6490. break;
  6491. }
  6492. }
  6493. pps->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  6494. pps->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  6495. if(pps->ref_count[0]-1 > 32-1 || pps->ref_count[1]-1 > 32-1){
  6496. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow (pps)\n");
  6497. pps->ref_count[0]= pps->ref_count[1]= 1;
  6498. return -1;
  6499. }
  6500. pps->weighted_pred= get_bits1(&s->gb);
  6501. pps->weighted_bipred_idc= get_bits(&s->gb, 2);
  6502. pps->init_qp= get_se_golomb(&s->gb) + 26;
  6503. pps->init_qs= get_se_golomb(&s->gb) + 26;
  6504. pps->chroma_qp_index_offset[0]= get_se_golomb(&s->gb);
  6505. pps->deblocking_filter_parameters_present= get_bits1(&s->gb);
  6506. pps->constrained_intra_pred= get_bits1(&s->gb);
  6507. pps->redundant_pic_cnt_present = get_bits1(&s->gb);
  6508. pps->transform_8x8_mode= 0;
  6509. h->dequant_coeff_pps= -1; //contents of sps/pps can change even if id doesn't, so reinit
  6510. memset(pps->scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  6511. memset(pps->scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  6512. if(get_bits_count(&s->gb) < bit_length){
  6513. pps->transform_8x8_mode= get_bits1(&s->gb);
  6514. decode_scaling_matrices(h, h->sps_buffers[pps->sps_id], pps, 0, pps->scaling_matrix4, pps->scaling_matrix8);
  6515. pps->chroma_qp_index_offset[1]= get_se_golomb(&s->gb); //second_chroma_qp_index_offset
  6516. } else {
  6517. pps->chroma_qp_index_offset[1]= pps->chroma_qp_index_offset[0];
  6518. }
  6519. build_qp_table(pps, 0, pps->chroma_qp_index_offset[0]);
  6520. if(pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1]) {
  6521. build_qp_table(pps, 1, pps->chroma_qp_index_offset[1]);
  6522. h->pps.chroma_qp_diff= 1;
  6523. } else
  6524. memcpy(pps->chroma_qp_table[1], pps->chroma_qp_table[0], 256);
  6525. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6526. av_log(h->s.avctx, AV_LOG_DEBUG, "pps:%u sps:%u %s slice_groups:%d ref:%d/%d %s qp:%d/%d/%d/%d %s %s %s %s\n",
  6527. pps_id, pps->sps_id,
  6528. pps->cabac ? "CABAC" : "CAVLC",
  6529. pps->slice_group_count,
  6530. pps->ref_count[0], pps->ref_count[1],
  6531. pps->weighted_pred ? "weighted" : "",
  6532. pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1],
  6533. pps->deblocking_filter_parameters_present ? "LPAR" : "",
  6534. pps->constrained_intra_pred ? "CONSTR" : "",
  6535. pps->redundant_pic_cnt_present ? "REDU" : "",
  6536. pps->transform_8x8_mode ? "8x8DCT" : ""
  6537. );
  6538. }
  6539. return 0;
  6540. }
  6541. /**
  6542. * Call decode_slice() for each context.
  6543. *
  6544. * @param h h264 master context
  6545. * @param context_count number of contexts to execute
  6546. */
  6547. static void execute_decode_slices(H264Context *h, int context_count){
  6548. MpegEncContext * const s = &h->s;
  6549. AVCodecContext * const avctx= s->avctx;
  6550. H264Context *hx;
  6551. int i;
  6552. if(context_count == 1) {
  6553. decode_slice(avctx, h);
  6554. } else {
  6555. for(i = 1; i < context_count; i++) {
  6556. hx = h->thread_context[i];
  6557. hx->s.error_resilience = avctx->error_resilience;
  6558. hx->s.error_count = 0;
  6559. }
  6560. avctx->execute(avctx, (void *)decode_slice,
  6561. (void **)h->thread_context, NULL, context_count);
  6562. /* pull back stuff from slices to master context */
  6563. hx = h->thread_context[context_count - 1];
  6564. s->mb_x = hx->s.mb_x;
  6565. s->mb_y = hx->s.mb_y;
  6566. s->dropable = hx->s.dropable;
  6567. s->picture_structure = hx->s.picture_structure;
  6568. for(i = 1; i < context_count; i++)
  6569. h->s.error_count += h->thread_context[i]->s.error_count;
  6570. }
  6571. }
  6572. static int decode_nal_units(H264Context *h, uint8_t *buf, int buf_size){
  6573. MpegEncContext * const s = &h->s;
  6574. AVCodecContext * const avctx= s->avctx;
  6575. int buf_index=0;
  6576. H264Context *hx; ///< thread context
  6577. int context_count = 0;
  6578. h->max_contexts = avctx->thread_count;
  6579. #if 0
  6580. int i;
  6581. for(i=0; i<50; i++){
  6582. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  6583. }
  6584. #endif
  6585. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  6586. h->current_slice = 0;
  6587. if (!s->first_field)
  6588. s->current_picture_ptr= NULL;
  6589. }
  6590. for(;;){
  6591. int consumed;
  6592. int dst_length;
  6593. int bit_length;
  6594. uint8_t *ptr;
  6595. int i, nalsize = 0;
  6596. int err;
  6597. if(h->is_avc) {
  6598. if(buf_index >= buf_size) break;
  6599. nalsize = 0;
  6600. for(i = 0; i < h->nal_length_size; i++)
  6601. nalsize = (nalsize << 8) | buf[buf_index++];
  6602. if(nalsize <= 1 || (nalsize+buf_index > buf_size)){
  6603. if(nalsize == 1){
  6604. buf_index++;
  6605. continue;
  6606. }else{
  6607. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  6608. break;
  6609. }
  6610. }
  6611. } else {
  6612. // start code prefix search
  6613. for(; buf_index + 3 < buf_size; buf_index++){
  6614. // This should always succeed in the first iteration.
  6615. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  6616. break;
  6617. }
  6618. if(buf_index+3 >= buf_size) break;
  6619. buf_index+=3;
  6620. }
  6621. hx = h->thread_context[context_count];
  6622. ptr= decode_nal(hx, buf + buf_index, &dst_length, &consumed, h->is_avc ? nalsize : buf_size - buf_index);
  6623. if (ptr==NULL || dst_length < 0){
  6624. return -1;
  6625. }
  6626. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  6627. dst_length--;
  6628. bit_length= !dst_length ? 0 : (8*dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1));
  6629. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  6630. av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d at %d/%d length %d\n", hx->nal_unit_type, buf_index, buf_size, dst_length);
  6631. }
  6632. if (h->is_avc && (nalsize != consumed))
  6633. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  6634. buf_index += consumed;
  6635. if( (s->hurry_up == 1 && h->nal_ref_idc == 0) //FIXME do not discard SEI id
  6636. ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  6637. continue;
  6638. again:
  6639. err = 0;
  6640. switch(hx->nal_unit_type){
  6641. case NAL_IDR_SLICE:
  6642. if (h->nal_unit_type != NAL_IDR_SLICE) {
  6643. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  6644. return -1;
  6645. }
  6646. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  6647. case NAL_SLICE:
  6648. init_get_bits(&hx->s.gb, ptr, bit_length);
  6649. hx->intra_gb_ptr=
  6650. hx->inter_gb_ptr= &hx->s.gb;
  6651. hx->s.data_partitioning = 0;
  6652. if((err = decode_slice_header(hx, h)))
  6653. break;
  6654. s->current_picture_ptr->key_frame|= (hx->nal_unit_type == NAL_IDR_SLICE);
  6655. if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
  6656. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6657. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=B_TYPE)
  6658. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==I_TYPE)
  6659. && avctx->skip_frame < AVDISCARD_ALL)
  6660. context_count++;
  6661. break;
  6662. case NAL_DPA:
  6663. init_get_bits(&hx->s.gb, ptr, bit_length);
  6664. hx->intra_gb_ptr=
  6665. hx->inter_gb_ptr= NULL;
  6666. hx->s.data_partitioning = 1;
  6667. err = decode_slice_header(hx, h);
  6668. break;
  6669. case NAL_DPB:
  6670. init_get_bits(&hx->intra_gb, ptr, bit_length);
  6671. hx->intra_gb_ptr= &hx->intra_gb;
  6672. break;
  6673. case NAL_DPC:
  6674. init_get_bits(&hx->inter_gb, ptr, bit_length);
  6675. hx->inter_gb_ptr= &hx->inter_gb;
  6676. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  6677. && s->context_initialized
  6678. && s->hurry_up < 5
  6679. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6680. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=B_TYPE)
  6681. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==I_TYPE)
  6682. && avctx->skip_frame < AVDISCARD_ALL)
  6683. context_count++;
  6684. break;
  6685. case NAL_SEI:
  6686. init_get_bits(&s->gb, ptr, bit_length);
  6687. decode_sei(h);
  6688. break;
  6689. case NAL_SPS:
  6690. init_get_bits(&s->gb, ptr, bit_length);
  6691. decode_seq_parameter_set(h);
  6692. if(s->flags& CODEC_FLAG_LOW_DELAY)
  6693. s->low_delay=1;
  6694. if(avctx->has_b_frames < 2)
  6695. avctx->has_b_frames= !s->low_delay;
  6696. break;
  6697. case NAL_PPS:
  6698. init_get_bits(&s->gb, ptr, bit_length);
  6699. decode_picture_parameter_set(h, bit_length);
  6700. break;
  6701. case NAL_AUD:
  6702. case NAL_END_SEQUENCE:
  6703. case NAL_END_STREAM:
  6704. case NAL_FILLER_DATA:
  6705. case NAL_SPS_EXT:
  6706. case NAL_AUXILIARY_SLICE:
  6707. break;
  6708. default:
  6709. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", h->nal_unit_type, bit_length);
  6710. }
  6711. if(context_count == h->max_contexts) {
  6712. execute_decode_slices(h, context_count);
  6713. context_count = 0;
  6714. }
  6715. if (err < 0)
  6716. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  6717. else if(err == 1) {
  6718. /* Slice could not be decoded in parallel mode, copy down
  6719. * NAL unit stuff to context 0 and restart. Note that
  6720. * rbsp_buffer is not transfered, but since we no longer
  6721. * run in parallel mode this should not be an issue. */
  6722. h->nal_unit_type = hx->nal_unit_type;
  6723. h->nal_ref_idc = hx->nal_ref_idc;
  6724. hx = h;
  6725. goto again;
  6726. }
  6727. }
  6728. if(context_count)
  6729. execute_decode_slices(h, context_count);
  6730. return buf_index;
  6731. }
  6732. /**
  6733. * returns the number of bytes consumed for building the current frame
  6734. */
  6735. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  6736. if(s->flags&CODEC_FLAG_TRUNCATED){
  6737. pos -= s->parse_context.last_index;
  6738. if(pos<0) pos=0; // FIXME remove (unneeded?)
  6739. return pos;
  6740. }else{
  6741. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  6742. if(pos+10>buf_size) pos=buf_size; // oops ;)
  6743. return pos;
  6744. }
  6745. }
  6746. static int decode_frame(AVCodecContext *avctx,
  6747. void *data, int *data_size,
  6748. uint8_t *buf, int buf_size)
  6749. {
  6750. H264Context *h = avctx->priv_data;
  6751. MpegEncContext *s = &h->s;
  6752. AVFrame *pict = data;
  6753. int buf_index;
  6754. s->flags= avctx->flags;
  6755. s->flags2= avctx->flags2;
  6756. /* no supplementary picture */
  6757. if (buf_size == 0) {
  6758. Picture *out;
  6759. int i, out_idx;
  6760. //FIXME factorize this with the output code below
  6761. out = h->delayed_pic[0];
  6762. out_idx = 0;
  6763. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6764. if(h->delayed_pic[i]->poc < out->poc){
  6765. out = h->delayed_pic[i];
  6766. out_idx = i;
  6767. }
  6768. for(i=out_idx; h->delayed_pic[i]; i++)
  6769. h->delayed_pic[i] = h->delayed_pic[i+1];
  6770. if(out){
  6771. *data_size = sizeof(AVFrame);
  6772. *pict= *(AVFrame*)out;
  6773. }
  6774. return 0;
  6775. }
  6776. if(s->flags&CODEC_FLAG_TRUNCATED){
  6777. int next= ff_h264_find_frame_end(h, buf, buf_size);
  6778. if( ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )
  6779. return buf_size;
  6780. //printf("next:%d buf_size:%d last_index:%d\n", next, buf_size, s->parse_context.last_index);
  6781. }
  6782. if(h->is_avc && !h->got_avcC) {
  6783. int i, cnt, nalsize;
  6784. unsigned char *p = avctx->extradata;
  6785. if(avctx->extradata_size < 7) {
  6786. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  6787. return -1;
  6788. }
  6789. if(*p != 1) {
  6790. av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);
  6791. return -1;
  6792. }
  6793. /* sps and pps in the avcC always have length coded with 2 bytes,
  6794. so put a fake nal_length_size = 2 while parsing them */
  6795. h->nal_length_size = 2;
  6796. // Decode sps from avcC
  6797. cnt = *(p+5) & 0x1f; // Number of sps
  6798. p += 6;
  6799. for (i = 0; i < cnt; i++) {
  6800. nalsize = AV_RB16(p) + 2;
  6801. if(decode_nal_units(h, p, nalsize) < 0) {
  6802. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  6803. return -1;
  6804. }
  6805. p += nalsize;
  6806. }
  6807. // Decode pps from avcC
  6808. cnt = *(p++); // Number of pps
  6809. for (i = 0; i < cnt; i++) {
  6810. nalsize = AV_RB16(p) + 2;
  6811. if(decode_nal_units(h, p, nalsize) != nalsize) {
  6812. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  6813. return -1;
  6814. }
  6815. p += nalsize;
  6816. }
  6817. // Now store right nal length size, that will be use to parse all other nals
  6818. h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
  6819. // Do not reparse avcC
  6820. h->got_avcC = 1;
  6821. }
  6822. if(avctx->frame_number==0 && !h->is_avc && s->avctx->extradata_size){
  6823. if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)
  6824. return -1;
  6825. }
  6826. buf_index=decode_nal_units(h, buf, buf_size);
  6827. if(buf_index < 0)
  6828. return -1;
  6829. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  6830. if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
  6831. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  6832. return -1;
  6833. }
  6834. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  6835. Picture *out = s->current_picture_ptr;
  6836. Picture *cur = s->current_picture_ptr;
  6837. Picture *prev = h->delayed_output_pic;
  6838. int i, pics, cross_idr, out_of_order, out_idx;
  6839. s->mb_y= 0;
  6840. s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
  6841. s->current_picture_ptr->pict_type= s->pict_type;
  6842. h->prev_frame_num_offset= h->frame_num_offset;
  6843. h->prev_frame_num= h->frame_num;
  6844. if(!s->dropable) {
  6845. h->prev_poc_msb= h->poc_msb;
  6846. h->prev_poc_lsb= h->poc_lsb;
  6847. execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  6848. }
  6849. /*
  6850. * FIXME: Error handling code does not seem to support interlaced
  6851. * when slices span multiple rows
  6852. * The ff_er_add_slice calls don't work right for bottom
  6853. * fields; they cause massive erroneous error concealing
  6854. * Error marking covers both fields (top and bottom).
  6855. * This causes a mismatched s->error_count
  6856. * and a bad error table. Further, the error count goes to
  6857. * INT_MAX when called for bottom field, because mb_y is
  6858. * past end by one (callers fault) and resync_mb_y != 0
  6859. * causes problems for the first MB line, too.
  6860. */
  6861. if (!FIELD_PICTURE)
  6862. ff_er_frame_end(s);
  6863. MPV_frame_end(s);
  6864. if (s->first_field) {
  6865. /* Wait for second field. */
  6866. *data_size = 0;
  6867. } else {
  6868. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  6869. //FIXME do something with unavailable reference frames
  6870. #if 0 //decode order
  6871. *data_size = sizeof(AVFrame);
  6872. #else
  6873. /* Sort B-frames into display order */
  6874. if(h->sps.bitstream_restriction_flag
  6875. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  6876. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  6877. s->low_delay = 0;
  6878. }
  6879. pics = 0;
  6880. while(h->delayed_pic[pics]) pics++;
  6881. assert(pics+1 < sizeof(h->delayed_pic) / sizeof(h->delayed_pic[0]));
  6882. h->delayed_pic[pics++] = cur;
  6883. if(cur->reference == 0)
  6884. cur->reference = DELAYED_PIC_REF;
  6885. cross_idr = 0;
  6886. for(i=0; h->delayed_pic[i]; i++)
  6887. if(h->delayed_pic[i]->key_frame || h->delayed_pic[i]->poc==0)
  6888. cross_idr = 1;
  6889. out = h->delayed_pic[0];
  6890. out_idx = 0;
  6891. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6892. if(h->delayed_pic[i]->poc < out->poc){
  6893. out = h->delayed_pic[i];
  6894. out_idx = i;
  6895. }
  6896. out_of_order = !cross_idr && prev && out->poc < prev->poc;
  6897. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  6898. { }
  6899. else if(prev && pics <= s->avctx->has_b_frames)
  6900. out = prev;
  6901. else if((out_of_order && pics-1 == s->avctx->has_b_frames && pics < 15)
  6902. || (s->low_delay &&
  6903. ((!cross_idr && prev && out->poc > prev->poc + 2)
  6904. || cur->pict_type == B_TYPE)))
  6905. {
  6906. s->low_delay = 0;
  6907. s->avctx->has_b_frames++;
  6908. out = prev;
  6909. }
  6910. else if(out_of_order)
  6911. out = prev;
  6912. if(out_of_order || pics > s->avctx->has_b_frames){
  6913. for(i=out_idx; h->delayed_pic[i]; i++)
  6914. h->delayed_pic[i] = h->delayed_pic[i+1];
  6915. }
  6916. if(prev == out)
  6917. *data_size = 0;
  6918. else
  6919. *data_size = sizeof(AVFrame);
  6920. if(prev && prev != out && prev->reference == DELAYED_PIC_REF)
  6921. prev->reference = 0;
  6922. h->delayed_output_pic = out;
  6923. #endif
  6924. if(out)
  6925. *pict= *(AVFrame*)out;
  6926. else
  6927. av_log(avctx, AV_LOG_DEBUG, "no picture\n");
  6928. }
  6929. }
  6930. assert(pict->data[0] || !*data_size);
  6931. ff_print_debug_info(s, pict);
  6932. //printf("out %d\n", (int)pict->data[0]);
  6933. #if 0 //?
  6934. /* Return the Picture timestamp as the frame number */
  6935. /* we substract 1 because it is added on utils.c */
  6936. avctx->frame_number = s->picture_number - 1;
  6937. #endif
  6938. return get_consumed_bytes(s, buf_index, buf_size);
  6939. }
  6940. #if 0
  6941. static inline void fill_mb_avail(H264Context *h){
  6942. MpegEncContext * const s = &h->s;
  6943. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  6944. if(s->mb_y){
  6945. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  6946. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  6947. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  6948. }else{
  6949. h->mb_avail[0]=
  6950. h->mb_avail[1]=
  6951. h->mb_avail[2]= 0;
  6952. }
  6953. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  6954. h->mb_avail[4]= 1; //FIXME move out
  6955. h->mb_avail[5]= 0; //FIXME move out
  6956. }
  6957. #endif
  6958. #if 0 //selftest
  6959. #undef random
  6960. #define COUNT 8000
  6961. #define SIZE (COUNT*40)
  6962. int main(){
  6963. int i;
  6964. uint8_t temp[SIZE];
  6965. PutBitContext pb;
  6966. GetBitContext gb;
  6967. // int int_temp[10000];
  6968. DSPContext dsp;
  6969. AVCodecContext avctx;
  6970. dsputil_init(&dsp, &avctx);
  6971. init_put_bits(&pb, temp, SIZE);
  6972. printf("testing unsigned exp golomb\n");
  6973. for(i=0; i<COUNT; i++){
  6974. START_TIMER
  6975. set_ue_golomb(&pb, i);
  6976. STOP_TIMER("set_ue_golomb");
  6977. }
  6978. flush_put_bits(&pb);
  6979. init_get_bits(&gb, temp, 8*SIZE);
  6980. for(i=0; i<COUNT; i++){
  6981. int j, s;
  6982. s= show_bits(&gb, 24);
  6983. START_TIMER
  6984. j= get_ue_golomb(&gb);
  6985. if(j != i){
  6986. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6987. // return -1;
  6988. }
  6989. STOP_TIMER("get_ue_golomb");
  6990. }
  6991. init_put_bits(&pb, temp, SIZE);
  6992. printf("testing signed exp golomb\n");
  6993. for(i=0; i<COUNT; i++){
  6994. START_TIMER
  6995. set_se_golomb(&pb, i - COUNT/2);
  6996. STOP_TIMER("set_se_golomb");
  6997. }
  6998. flush_put_bits(&pb);
  6999. init_get_bits(&gb, temp, 8*SIZE);
  7000. for(i=0; i<COUNT; i++){
  7001. int j, s;
  7002. s= show_bits(&gb, 24);
  7003. START_TIMER
  7004. j= get_se_golomb(&gb);
  7005. if(j != i - COUNT/2){
  7006. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  7007. // return -1;
  7008. }
  7009. STOP_TIMER("get_se_golomb");
  7010. }
  7011. printf("testing 4x4 (I)DCT\n");
  7012. DCTELEM block[16];
  7013. uint8_t src[16], ref[16];
  7014. uint64_t error= 0, max_error=0;
  7015. for(i=0; i<COUNT; i++){
  7016. int j;
  7017. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  7018. for(j=0; j<16; j++){
  7019. ref[j]= random()%255;
  7020. src[j]= random()%255;
  7021. }
  7022. h264_diff_dct_c(block, src, ref, 4);
  7023. //normalize
  7024. for(j=0; j<16; j++){
  7025. // printf("%d ", block[j]);
  7026. block[j]= block[j]*4;
  7027. if(j&1) block[j]= (block[j]*4 + 2)/5;
  7028. if(j&4) block[j]= (block[j]*4 + 2)/5;
  7029. }
  7030. // printf("\n");
  7031. s->dsp.h264_idct_add(ref, block, 4);
  7032. /* for(j=0; j<16; j++){
  7033. printf("%d ", ref[j]);
  7034. }
  7035. printf("\n");*/
  7036. for(j=0; j<16; j++){
  7037. int diff= FFABS(src[j] - ref[j]);
  7038. error+= diff*diff;
  7039. max_error= FFMAX(max_error, diff);
  7040. }
  7041. }
  7042. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  7043. #if 0
  7044. printf("testing quantizer\n");
  7045. for(qp=0; qp<52; qp++){
  7046. for(i=0; i<16; i++)
  7047. src1_block[i]= src2_block[i]= random()%255;
  7048. }
  7049. #endif
  7050. printf("Testing NAL layer\n");
  7051. uint8_t bitstream[COUNT];
  7052. uint8_t nal[COUNT*2];
  7053. H264Context h;
  7054. memset(&h, 0, sizeof(H264Context));
  7055. for(i=0; i<COUNT; i++){
  7056. int zeros= i;
  7057. int nal_length;
  7058. int consumed;
  7059. int out_length;
  7060. uint8_t *out;
  7061. int j;
  7062. for(j=0; j<COUNT; j++){
  7063. bitstream[j]= (random() % 255) + 1;
  7064. }
  7065. for(j=0; j<zeros; j++){
  7066. int pos= random() % COUNT;
  7067. while(bitstream[pos] == 0){
  7068. pos++;
  7069. pos %= COUNT;
  7070. }
  7071. bitstream[pos]=0;
  7072. }
  7073. START_TIMER
  7074. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  7075. if(nal_length<0){
  7076. printf("encoding failed\n");
  7077. return -1;
  7078. }
  7079. out= decode_nal(&h, nal, &out_length, &consumed, nal_length);
  7080. STOP_TIMER("NAL")
  7081. if(out_length != COUNT){
  7082. printf("incorrect length %d %d\n", out_length, COUNT);
  7083. return -1;
  7084. }
  7085. if(consumed != nal_length){
  7086. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  7087. return -1;
  7088. }
  7089. if(memcmp(bitstream, out, COUNT)){
  7090. printf("mismatch\n");
  7091. return -1;
  7092. }
  7093. }
  7094. printf("Testing RBSP\n");
  7095. return 0;
  7096. }
  7097. #endif
  7098. static int decode_end(AVCodecContext *avctx)
  7099. {
  7100. H264Context *h = avctx->priv_data;
  7101. MpegEncContext *s = &h->s;
  7102. av_freep(&h->rbsp_buffer[0]);
  7103. av_freep(&h->rbsp_buffer[1]);
  7104. free_tables(h); //FIXME cleanup init stuff perhaps
  7105. MPV_common_end(s);
  7106. // memset(h, 0, sizeof(H264Context));
  7107. return 0;
  7108. }
  7109. AVCodec h264_decoder = {
  7110. "h264",
  7111. CODEC_TYPE_VIDEO,
  7112. CODEC_ID_H264,
  7113. sizeof(H264Context),
  7114. decode_init,
  7115. NULL,
  7116. decode_end,
  7117. decode_frame,
  7118. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
  7119. .flush= flush_dpb,
  7120. };
  7121. #include "svq3.c"