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.

8042 lines
311KB

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