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.

8009 lines
310KB

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