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.

8121 lines
314KB

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