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.

8193 lines
316KB

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