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.

8077 lines
312KB

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