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.

7962 lines
308KB

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