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.

7884 lines
303KB

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