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.

8039 lines
311KB

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