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.

7923 lines
305KB

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