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.

8168 lines
315KB

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