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.

8127 lines
314KB

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