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.

7903 lines
306KB

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