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.

7910 lines
304KB

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