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.

8059 lines
312KB

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