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.

7975 lines
308KB

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