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.

7988 lines
309KB

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