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.

8046 lines
311KB

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