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.

7909 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 int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);
  2145. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  2146. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  2147. dest_y = s->current_picture.data[0] + (mb_y * 16* s->linesize ) + mb_x * 16;
  2148. dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2149. dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2150. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
  2151. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
  2152. if (!simple && MB_FIELD) {
  2153. linesize = h->mb_linesize = s->linesize * 2;
  2154. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2155. block_offset = &h->block_offset[24];
  2156. if(mb_y&1){ //FIXME move out of this function?
  2157. dest_y -= s->linesize*15;
  2158. dest_cb-= s->uvlinesize*7;
  2159. dest_cr-= s->uvlinesize*7;
  2160. }
  2161. if(FRAME_MBAFF) {
  2162. int list;
  2163. for(list=0; list<h->list_count; list++){
  2164. if(!USES_LIST(mb_type, list))
  2165. continue;
  2166. if(IS_16X16(mb_type)){
  2167. int8_t *ref = &h->ref_cache[list][scan8[0]];
  2168. fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
  2169. }else{
  2170. for(i=0; i<16; i+=4){
  2171. //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?
  2172. int ref = h->ref_cache[list][scan8[i]];
  2173. if(ref >= 0)
  2174. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
  2175. }
  2176. }
  2177. }
  2178. }
  2179. } else {
  2180. linesize = h->mb_linesize = s->linesize;
  2181. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2182. // dct_offset = s->linesize * 16;
  2183. }
  2184. if(transform_bypass){
  2185. idct_dc_add =
  2186. idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  2187. }else if(IS_8x8DCT(mb_type)){
  2188. idct_dc_add = s->dsp.h264_idct8_dc_add;
  2189. idct_add = s->dsp.h264_idct8_add;
  2190. }else{
  2191. idct_dc_add = s->dsp.h264_idct_dc_add;
  2192. idct_add = s->dsp.h264_idct_add;
  2193. }
  2194. if (!simple && IS_INTRA_PCM(mb_type)) {
  2195. for (i=0; i<16; i++) {
  2196. memcpy(dest_y + i* linesize, h->mb + i*8, 16);
  2197. }
  2198. for (i=0; i<8; i++) {
  2199. memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4, 8);
  2200. memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4, 8);
  2201. }
  2202. } else {
  2203. if(IS_INTRA(mb_type)){
  2204. if(h->deblocking_filter)
  2205. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
  2206. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2207. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  2208. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  2209. }
  2210. if(IS_INTRA4x4(mb_type)){
  2211. if(simple || !s->encoding){
  2212. if(IS_8x8DCT(mb_type)){
  2213. for(i=0; i<16; i+=4){
  2214. uint8_t * const ptr= dest_y + block_offset[i];
  2215. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2216. const int nnz = h->non_zero_count_cache[ scan8[i] ];
  2217. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  2218. (h->topright_samples_available<<i)&0x4000, linesize);
  2219. if(nnz){
  2220. if(nnz == 1 && h->mb[i*16])
  2221. idct_dc_add(ptr, h->mb + i*16, linesize);
  2222. else
  2223. idct_add(ptr, h->mb + i*16, linesize);
  2224. }
  2225. }
  2226. }else
  2227. for(i=0; i<16; i++){
  2228. uint8_t * const ptr= dest_y + block_offset[i];
  2229. uint8_t *topright;
  2230. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2231. int nnz, tr;
  2232. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  2233. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  2234. assert(mb_y || linesize <= block_offset[i]);
  2235. if(!topright_avail){
  2236. tr= ptr[3 - linesize]*0x01010101;
  2237. topright= (uint8_t*) &tr;
  2238. }else
  2239. topright= ptr + 4 - linesize;
  2240. }else
  2241. topright= NULL;
  2242. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  2243. nnz = h->non_zero_count_cache[ scan8[i] ];
  2244. if(nnz){
  2245. if(is_h264){
  2246. if(nnz == 1 && h->mb[i*16])
  2247. idct_dc_add(ptr, h->mb + i*16, linesize);
  2248. else
  2249. idct_add(ptr, h->mb + i*16, linesize);
  2250. }else
  2251. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
  2252. }
  2253. }
  2254. }
  2255. }else{
  2256. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  2257. if(is_h264){
  2258. if(!transform_bypass)
  2259. h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
  2260. }else
  2261. svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
  2262. }
  2263. if(h->deblocking_filter)
  2264. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
  2265. }else if(is_h264){
  2266. hl_motion(h, dest_y, dest_cb, dest_cr,
  2267. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  2268. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  2269. s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
  2270. }
  2271. if(!IS_INTRA4x4(mb_type)){
  2272. if(is_h264){
  2273. if(IS_INTRA16x16(mb_type)){
  2274. for(i=0; i<16; i++){
  2275. if(h->non_zero_count_cache[ scan8[i] ])
  2276. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2277. else if(h->mb[i*16])
  2278. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2279. }
  2280. }else{
  2281. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2282. for(i=0; i<16; i+=di){
  2283. int nnz = h->non_zero_count_cache[ scan8[i] ];
  2284. if(nnz){
  2285. if(nnz==1 && h->mb[i*16])
  2286. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2287. else
  2288. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2289. }
  2290. }
  2291. }
  2292. }else{
  2293. for(i=0; i<16; i++){
  2294. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
  2295. uint8_t * const ptr= dest_y + block_offset[i];
  2296. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2297. }
  2298. }
  2299. }
  2300. }
  2301. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2302. uint8_t *dest[2] = {dest_cb, dest_cr};
  2303. if(transform_bypass){
  2304. idct_add = idct_dc_add = s->dsp.add_pixels4;
  2305. }else{
  2306. idct_add = s->dsp.h264_idct_add;
  2307. idct_dc_add = s->dsp.h264_idct_dc_add;
  2308. 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]);
  2309. 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]);
  2310. }
  2311. if(is_h264){
  2312. for(i=16; i<16+8; i++){
  2313. if(h->non_zero_count_cache[ scan8[i] ])
  2314. idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2315. else if(h->mb[i*16])
  2316. idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2317. }
  2318. }else{
  2319. for(i=16; i<16+8; i++){
  2320. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  2321. uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
  2322. svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
  2323. }
  2324. }
  2325. }
  2326. }
  2327. }
  2328. if(h->deblocking_filter) {
  2329. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
  2330. fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2331. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2332. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2333. if (!simple && FRAME_MBAFF) {
  2334. filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2335. } else {
  2336. filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2337. }
  2338. }
  2339. }
  2340. /**
  2341. * Process a macroblock; this case avoids checks for expensive uncommon cases.
  2342. */
  2343. static void hl_decode_mb_simple(H264Context *h){
  2344. hl_decode_mb_internal(h, 1);
  2345. }
  2346. /**
  2347. * Process a macroblock; this handles edge cases, such as interlacing.
  2348. */
  2349. static void av_noinline hl_decode_mb_complex(H264Context *h){
  2350. hl_decode_mb_internal(h, 0);
  2351. }
  2352. static void hl_decode_mb(H264Context *h){
  2353. MpegEncContext * const s = &h->s;
  2354. const int mb_xy= h->mb_xy;
  2355. const int mb_type= s->current_picture.mb_type[mb_xy];
  2356. int is_complex = FRAME_MBAFF || MB_FIELD || IS_INTRA_PCM(mb_type) || s->codec_id != CODEC_ID_H264 ||
  2357. (ENABLE_GRAY && (s->flags&CODEC_FLAG_GRAY)) || (ENABLE_H264_ENCODER && s->encoding) || ENABLE_SMALL;
  2358. if(ENABLE_H264_ENCODER && !s->decode)
  2359. return;
  2360. if (is_complex)
  2361. hl_decode_mb_complex(h);
  2362. else hl_decode_mb_simple(h);
  2363. }
  2364. static void pic_as_field(Picture *pic, const int parity){
  2365. int i;
  2366. for (i = 0; i < 4; ++i) {
  2367. if (parity == PICT_BOTTOM_FIELD)
  2368. pic->data[i] += pic->linesize[i];
  2369. pic->reference = parity;
  2370. pic->linesize[i] *= 2;
  2371. }
  2372. pic->poc= pic->field_poc[parity == PICT_BOTTOM_FIELD];
  2373. }
  2374. static int split_field_copy(Picture *dest, Picture *src,
  2375. int parity, int id_add){
  2376. int match = !!(src->reference & parity);
  2377. if (match) {
  2378. *dest = *src;
  2379. if(parity != PICT_FRAME){
  2380. pic_as_field(dest, parity);
  2381. dest->pic_id *= 2;
  2382. dest->pic_id += id_add;
  2383. }
  2384. }
  2385. return match;
  2386. }
  2387. static int build_def_list(Picture *def, Picture **in, int len, int is_long, int sel){
  2388. int i[2]={0};
  2389. int index=0;
  2390. while(i[0]<len || i[1]<len){
  2391. while(i[0]<len && !(in[ i[0] ] && (in[ i[0] ]->reference & sel)))
  2392. i[0]++;
  2393. while(i[1]<len && !(in[ i[1] ] && (in[ i[1] ]->reference & (sel^3))))
  2394. i[1]++;
  2395. if(i[0] < len){
  2396. in[ i[0] ]->pic_id= is_long ? i[0] : in[ i[0] ]->frame_num;
  2397. split_field_copy(&def[index++], in[ i[0]++ ], sel , 1);
  2398. }
  2399. if(i[1] < len){
  2400. in[ i[1] ]->pic_id= is_long ? i[1] : in[ i[1] ]->frame_num;
  2401. split_field_copy(&def[index++], in[ i[1]++ ], sel^3, 0);
  2402. }
  2403. }
  2404. return index;
  2405. }
  2406. static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir){
  2407. int i, best_poc;
  2408. int out_i= 0;
  2409. for(;;){
  2410. best_poc= dir ? INT_MIN : INT_MAX;
  2411. for(i=0; i<len; i++){
  2412. const int poc= src[i]->poc;
  2413. if(((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)){
  2414. best_poc= poc;
  2415. sorted[out_i]= src[i];
  2416. }
  2417. }
  2418. if(best_poc == (dir ? INT_MIN : INT_MAX))
  2419. break;
  2420. limit= sorted[out_i++]->poc - dir;
  2421. }
  2422. return out_i;
  2423. }
  2424. /**
  2425. * fills the default_ref_list.
  2426. */
  2427. static int fill_default_ref_list(H264Context *h){
  2428. MpegEncContext * const s = &h->s;
  2429. int i, len;
  2430. if(h->slice_type_nos==FF_B_TYPE){
  2431. Picture *sorted[32];
  2432. int cur_poc, list;
  2433. int lens[2];
  2434. if(FIELD_PICTURE)
  2435. cur_poc= s->current_picture_ptr->field_poc[ s->picture_structure == PICT_BOTTOM_FIELD ];
  2436. else
  2437. cur_poc= s->current_picture_ptr->poc;
  2438. for(list= 0; list<2; list++){
  2439. len= add_sorted(sorted , h->short_ref, h->short_ref_count, cur_poc, 1^list);
  2440. len+=add_sorted(sorted+len, h->short_ref, h->short_ref_count, cur_poc, 0^list);
  2441. assert(len<=32);
  2442. len= build_def_list(h->default_ref_list[list] , sorted , len, 0, s->picture_structure);
  2443. len+=build_def_list(h->default_ref_list[list]+len, h->long_ref, 16 , 1, s->picture_structure);
  2444. assert(len<=32);
  2445. if(len < h->ref_count[list])
  2446. memset(&h->default_ref_list[list][len], 0, sizeof(Picture)*(h->ref_count[list] - len));
  2447. lens[list]= len;
  2448. }
  2449. if(lens[0] == lens[1] && lens[1] > 1){
  2450. for(i=0; h->default_ref_list[0][i].data[0] == h->default_ref_list[1][i].data[0] && i<lens[0]; i++);
  2451. if(i == lens[0])
  2452. FFSWAP(Picture, h->default_ref_list[1][0], h->default_ref_list[1][1]);
  2453. }
  2454. }else{
  2455. len = build_def_list(h->default_ref_list[0] , h->short_ref, h->short_ref_count, 0, s->picture_structure);
  2456. len+= build_def_list(h->default_ref_list[0]+len, h-> long_ref, 16 , 1, s->picture_structure);
  2457. assert(len <= 32);
  2458. if(len < h->ref_count[0])
  2459. memset(&h->default_ref_list[0][len], 0, sizeof(Picture)*(h->ref_count[0] - len));
  2460. }
  2461. #ifdef TRACE
  2462. for (i=0; i<h->ref_count[0]; i++) {
  2463. 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]);
  2464. }
  2465. if(h->slice_type_nos==FF_B_TYPE){
  2466. for (i=0; i<h->ref_count[1]; i++) {
  2467. 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]);
  2468. }
  2469. }
  2470. #endif
  2471. return 0;
  2472. }
  2473. static void print_short_term(H264Context *h);
  2474. static void print_long_term(H264Context *h);
  2475. /**
  2476. * Extract structure information about the picture described by pic_num in
  2477. * the current decoding context (frame or field). Note that pic_num is
  2478. * picture number without wrapping (so, 0<=pic_num<max_pic_num).
  2479. * @param pic_num picture number for which to extract structure information
  2480. * @param structure one of PICT_XXX describing structure of picture
  2481. * with pic_num
  2482. * @return frame number (short term) or long term index of picture
  2483. * described by pic_num
  2484. */
  2485. static int pic_num_extract(H264Context *h, int pic_num, int *structure){
  2486. MpegEncContext * const s = &h->s;
  2487. *structure = s->picture_structure;
  2488. if(FIELD_PICTURE){
  2489. if (!(pic_num & 1))
  2490. /* opposite field */
  2491. *structure ^= PICT_FRAME;
  2492. pic_num >>= 1;
  2493. }
  2494. return pic_num;
  2495. }
  2496. static int decode_ref_pic_list_reordering(H264Context *h){
  2497. MpegEncContext * const s = &h->s;
  2498. int list, index, pic_structure;
  2499. print_short_term(h);
  2500. print_long_term(h);
  2501. for(list=0; list<h->list_count; list++){
  2502. memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
  2503. if(get_bits1(&s->gb)){
  2504. int pred= h->curr_pic_num;
  2505. for(index=0; ; index++){
  2506. unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
  2507. unsigned int pic_id;
  2508. int i;
  2509. Picture *ref = NULL;
  2510. if(reordering_of_pic_nums_idc==3)
  2511. break;
  2512. if(index >= h->ref_count[list]){
  2513. av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
  2514. return -1;
  2515. }
  2516. if(reordering_of_pic_nums_idc<3){
  2517. if(reordering_of_pic_nums_idc<2){
  2518. const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
  2519. int frame_num;
  2520. if(abs_diff_pic_num > h->max_pic_num){
  2521. av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
  2522. return -1;
  2523. }
  2524. if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
  2525. else pred+= abs_diff_pic_num;
  2526. pred &= h->max_pic_num - 1;
  2527. frame_num = pic_num_extract(h, pred, &pic_structure);
  2528. for(i= h->short_ref_count-1; i>=0; i--){
  2529. ref = h->short_ref[i];
  2530. assert(ref->reference);
  2531. assert(!ref->long_ref);
  2532. if(
  2533. ref->frame_num == frame_num &&
  2534. (ref->reference & pic_structure)
  2535. )
  2536. break;
  2537. }
  2538. if(i>=0)
  2539. ref->pic_id= pred;
  2540. }else{
  2541. int long_idx;
  2542. pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
  2543. long_idx= pic_num_extract(h, pic_id, &pic_structure);
  2544. if(long_idx>31){
  2545. av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
  2546. return -1;
  2547. }
  2548. ref = h->long_ref[long_idx];
  2549. assert(!(ref && !ref->reference));
  2550. if(ref && (ref->reference & pic_structure)){
  2551. ref->pic_id= pic_id;
  2552. assert(ref->long_ref);
  2553. i=0;
  2554. }else{
  2555. i=-1;
  2556. }
  2557. }
  2558. if (i < 0) {
  2559. av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
  2560. memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
  2561. } else {
  2562. for(i=index; i+1<h->ref_count[list]; i++){
  2563. if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
  2564. break;
  2565. }
  2566. for(; i > index; i--){
  2567. h->ref_list[list][i]= h->ref_list[list][i-1];
  2568. }
  2569. h->ref_list[list][index]= *ref;
  2570. if (FIELD_PICTURE){
  2571. pic_as_field(&h->ref_list[list][index], pic_structure);
  2572. }
  2573. }
  2574. }else{
  2575. av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
  2576. return -1;
  2577. }
  2578. }
  2579. }
  2580. }
  2581. for(list=0; list<h->list_count; list++){
  2582. for(index= 0; index < h->ref_count[list]; index++){
  2583. if(!h->ref_list[list][index].data[0]){
  2584. av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture\n");
  2585. h->ref_list[list][index]= s->current_picture; //FIXME this is not a sensible solution
  2586. }
  2587. }
  2588. }
  2589. if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
  2590. direct_dist_scale_factor(h);
  2591. direct_ref_list_init(h);
  2592. return 0;
  2593. }
  2594. static void fill_mbaff_ref_list(H264Context *h){
  2595. int list, i, j;
  2596. for(list=0; list<2; list++){ //FIXME try list_count
  2597. for(i=0; i<h->ref_count[list]; i++){
  2598. Picture *frame = &h->ref_list[list][i];
  2599. Picture *field = &h->ref_list[list][16+2*i];
  2600. field[0] = *frame;
  2601. for(j=0; j<3; j++)
  2602. field[0].linesize[j] <<= 1;
  2603. field[0].reference = PICT_TOP_FIELD;
  2604. field[1] = field[0];
  2605. for(j=0; j<3; j++)
  2606. field[1].data[j] += frame->linesize[j];
  2607. field[1].reference = PICT_BOTTOM_FIELD;
  2608. h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
  2609. h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
  2610. for(j=0; j<2; j++){
  2611. h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
  2612. h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
  2613. }
  2614. }
  2615. }
  2616. for(j=0; j<h->ref_count[1]; j++){
  2617. for(i=0; i<h->ref_count[0]; i++)
  2618. h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
  2619. memcpy(h->implicit_weight[16+2*j], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2620. memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2621. }
  2622. }
  2623. static int pred_weight_table(H264Context *h){
  2624. MpegEncContext * const s = &h->s;
  2625. int list, i;
  2626. int luma_def, chroma_def;
  2627. h->use_weight= 0;
  2628. h->use_weight_chroma= 0;
  2629. h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
  2630. h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
  2631. luma_def = 1<<h->luma_log2_weight_denom;
  2632. chroma_def = 1<<h->chroma_log2_weight_denom;
  2633. for(list=0; list<2; list++){
  2634. for(i=0; i<h->ref_count[list]; i++){
  2635. int luma_weight_flag, chroma_weight_flag;
  2636. luma_weight_flag= get_bits1(&s->gb);
  2637. if(luma_weight_flag){
  2638. h->luma_weight[list][i]= get_se_golomb(&s->gb);
  2639. h->luma_offset[list][i]= get_se_golomb(&s->gb);
  2640. if( h->luma_weight[list][i] != luma_def
  2641. || h->luma_offset[list][i] != 0)
  2642. h->use_weight= 1;
  2643. }else{
  2644. h->luma_weight[list][i]= luma_def;
  2645. h->luma_offset[list][i]= 0;
  2646. }
  2647. if(CHROMA){
  2648. chroma_weight_flag= get_bits1(&s->gb);
  2649. if(chroma_weight_flag){
  2650. int j;
  2651. for(j=0; j<2; j++){
  2652. h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
  2653. h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
  2654. if( h->chroma_weight[list][i][j] != chroma_def
  2655. || h->chroma_offset[list][i][j] != 0)
  2656. h->use_weight_chroma= 1;
  2657. }
  2658. }else{
  2659. int j;
  2660. for(j=0; j<2; j++){
  2661. h->chroma_weight[list][i][j]= chroma_def;
  2662. h->chroma_offset[list][i][j]= 0;
  2663. }
  2664. }
  2665. }
  2666. }
  2667. if(h->slice_type_nos != FF_B_TYPE) break;
  2668. }
  2669. h->use_weight= h->use_weight || h->use_weight_chroma;
  2670. return 0;
  2671. }
  2672. static void implicit_weight_table(H264Context *h){
  2673. MpegEncContext * const s = &h->s;
  2674. int ref0, ref1;
  2675. int cur_poc = s->current_picture_ptr->poc;
  2676. if( h->ref_count[0] == 1 && h->ref_count[1] == 1
  2677. && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
  2678. h->use_weight= 0;
  2679. h->use_weight_chroma= 0;
  2680. return;
  2681. }
  2682. h->use_weight= 2;
  2683. h->use_weight_chroma= 2;
  2684. h->luma_log2_weight_denom= 5;
  2685. h->chroma_log2_weight_denom= 5;
  2686. for(ref0=0; ref0 < h->ref_count[0]; ref0++){
  2687. int poc0 = h->ref_list[0][ref0].poc;
  2688. for(ref1=0; ref1 < h->ref_count[1]; ref1++){
  2689. int poc1 = h->ref_list[1][ref1].poc;
  2690. int td = av_clip(poc1 - poc0, -128, 127);
  2691. if(td){
  2692. int tb = av_clip(cur_poc - poc0, -128, 127);
  2693. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2694. int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
  2695. if(dist_scale_factor < -64 || dist_scale_factor > 128)
  2696. h->implicit_weight[ref0][ref1] = 32;
  2697. else
  2698. h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
  2699. }else
  2700. h->implicit_weight[ref0][ref1] = 32;
  2701. }
  2702. }
  2703. }
  2704. /**
  2705. * Mark a picture as no longer needed for reference. The refmask
  2706. * argument allows unreferencing of individual fields or the whole frame.
  2707. * If the picture becomes entirely unreferenced, but is being held for
  2708. * display purposes, it is marked as such.
  2709. * @param refmask mask of fields to unreference; the mask is bitwise
  2710. * anded with the reference marking of pic
  2711. * @return non-zero if pic becomes entirely unreferenced (except possibly
  2712. * for display purposes) zero if one of the fields remains in
  2713. * reference
  2714. */
  2715. static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
  2716. int i;
  2717. if (pic->reference &= refmask) {
  2718. return 0;
  2719. } else {
  2720. for(i = 0; h->delayed_pic[i]; i++)
  2721. if(pic == h->delayed_pic[i]){
  2722. pic->reference=DELAYED_PIC_REF;
  2723. break;
  2724. }
  2725. return 1;
  2726. }
  2727. }
  2728. /**
  2729. * instantaneous decoder refresh.
  2730. */
  2731. static void idr(H264Context *h){
  2732. int i;
  2733. for(i=0; i<16; i++){
  2734. remove_long(h, i, 0);
  2735. }
  2736. assert(h->long_ref_count==0);
  2737. for(i=0; i<h->short_ref_count; i++){
  2738. unreference_pic(h, h->short_ref[i], 0);
  2739. h->short_ref[i]= NULL;
  2740. }
  2741. h->short_ref_count=0;
  2742. h->prev_frame_num= 0;
  2743. h->prev_frame_num_offset= 0;
  2744. h->prev_poc_msb=
  2745. h->prev_poc_lsb= 0;
  2746. }
  2747. /* forget old pics after a seek */
  2748. static void flush_dpb(AVCodecContext *avctx){
  2749. H264Context *h= avctx->priv_data;
  2750. int i;
  2751. for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
  2752. if(h->delayed_pic[i])
  2753. h->delayed_pic[i]->reference= 0;
  2754. h->delayed_pic[i]= NULL;
  2755. }
  2756. h->outputed_poc= INT_MIN;
  2757. idr(h);
  2758. if(h->s.current_picture_ptr)
  2759. h->s.current_picture_ptr->reference= 0;
  2760. h->s.first_field= 0;
  2761. ff_mpeg_flush(avctx);
  2762. }
  2763. /**
  2764. * Find a Picture in the short term reference list by frame number.
  2765. * @param frame_num frame number to search for
  2766. * @param idx the index into h->short_ref where returned picture is found
  2767. * undefined if no picture found.
  2768. * @return pointer to the found picture, or NULL if no pic with the provided
  2769. * frame number is found
  2770. */
  2771. static Picture * find_short(H264Context *h, int frame_num, int *idx){
  2772. MpegEncContext * const s = &h->s;
  2773. int i;
  2774. for(i=0; i<h->short_ref_count; i++){
  2775. Picture *pic= h->short_ref[i];
  2776. if(s->avctx->debug&FF_DEBUG_MMCO)
  2777. av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
  2778. if(pic->frame_num == frame_num) {
  2779. *idx = i;
  2780. return pic;
  2781. }
  2782. }
  2783. return NULL;
  2784. }
  2785. /**
  2786. * Remove a picture from the short term reference list by its index in
  2787. * that list. This does no checking on the provided index; it is assumed
  2788. * to be valid. Other list entries are shifted down.
  2789. * @param i index into h->short_ref of picture to remove.
  2790. */
  2791. static void remove_short_at_index(H264Context *h, int i){
  2792. assert(i >= 0 && i < h->short_ref_count);
  2793. h->short_ref[i]= NULL;
  2794. if (--h->short_ref_count)
  2795. memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
  2796. }
  2797. /**
  2798. *
  2799. * @return the removed picture or NULL if an error occurs
  2800. */
  2801. static Picture * remove_short(H264Context *h, int frame_num, int ref_mask){
  2802. MpegEncContext * const s = &h->s;
  2803. Picture *pic;
  2804. int i;
  2805. if(s->avctx->debug&FF_DEBUG_MMCO)
  2806. av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
  2807. pic = find_short(h, frame_num, &i);
  2808. if (pic){
  2809. if(unreference_pic(h, pic, ref_mask))
  2810. remove_short_at_index(h, i);
  2811. }
  2812. return pic;
  2813. }
  2814. /**
  2815. * Remove a picture from the long term reference list by its index in
  2816. * that list.
  2817. * @return the removed picture or NULL if an error occurs
  2818. */
  2819. static Picture * remove_long(H264Context *h, int i, int ref_mask){
  2820. Picture *pic;
  2821. pic= h->long_ref[i];
  2822. if (pic){
  2823. if(unreference_pic(h, pic, ref_mask)){
  2824. assert(h->long_ref[i]->long_ref == 1);
  2825. h->long_ref[i]->long_ref= 0;
  2826. h->long_ref[i]= NULL;
  2827. h->long_ref_count--;
  2828. }
  2829. }
  2830. return pic;
  2831. }
  2832. /**
  2833. * print short term list
  2834. */
  2835. static void print_short_term(H264Context *h) {
  2836. uint32_t i;
  2837. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  2838. av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
  2839. for(i=0; i<h->short_ref_count; i++){
  2840. Picture *pic= h->short_ref[i];
  2841. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  2842. }
  2843. }
  2844. }
  2845. /**
  2846. * print long term list
  2847. */
  2848. static void print_long_term(H264Context *h) {
  2849. uint32_t i;
  2850. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  2851. av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
  2852. for(i = 0; i < 16; i++){
  2853. Picture *pic= h->long_ref[i];
  2854. if (pic) {
  2855. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  2856. }
  2857. }
  2858. }
  2859. }
  2860. /**
  2861. * Executes the reference picture marking (memory management control operations).
  2862. */
  2863. static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
  2864. MpegEncContext * const s = &h->s;
  2865. int i, j;
  2866. int current_ref_assigned=0;
  2867. Picture *pic;
  2868. if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
  2869. av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
  2870. for(i=0; i<mmco_count; i++){
  2871. int structure, frame_num;
  2872. if(s->avctx->debug&FF_DEBUG_MMCO)
  2873. 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);
  2874. if( mmco[i].opcode == MMCO_SHORT2UNUSED
  2875. || mmco[i].opcode == MMCO_SHORT2LONG){
  2876. frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
  2877. pic = find_short(h, frame_num, &j);
  2878. if(!pic){
  2879. if(mmco[i].opcode != MMCO_SHORT2LONG || !h->long_ref[mmco[i].long_arg]
  2880. || h->long_ref[mmco[i].long_arg]->frame_num != frame_num)
  2881. av_log(h->s.avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
  2882. continue;
  2883. }
  2884. }
  2885. switch(mmco[i].opcode){
  2886. case MMCO_SHORT2UNUSED:
  2887. if(s->avctx->debug&FF_DEBUG_MMCO)
  2888. 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);
  2889. remove_short(h, frame_num, structure ^ PICT_FRAME);
  2890. break;
  2891. case MMCO_SHORT2LONG:
  2892. if (h->long_ref[mmco[i].long_arg] != pic)
  2893. remove_long(h, mmco[i].long_arg, 0);
  2894. remove_short_at_index(h, j);
  2895. h->long_ref[ mmco[i].long_arg ]= pic;
  2896. if (h->long_ref[ mmco[i].long_arg ]){
  2897. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  2898. h->long_ref_count++;
  2899. }
  2900. break;
  2901. case MMCO_LONG2UNUSED:
  2902. j = pic_num_extract(h, mmco[i].long_arg, &structure);
  2903. pic = h->long_ref[j];
  2904. if (pic) {
  2905. remove_long(h, j, structure ^ PICT_FRAME);
  2906. } else if(s->avctx->debug&FF_DEBUG_MMCO)
  2907. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
  2908. break;
  2909. case MMCO_LONG:
  2910. // Comment below left from previous code as it is an interresting note.
  2911. /* First field in pair is in short term list or
  2912. * at a different long term index.
  2913. * This is not allowed; see 7.4.3.3, notes 2 and 3.
  2914. * Report the problem and keep the pair where it is,
  2915. * and mark this field valid.
  2916. */
  2917. if (h->long_ref[mmco[i].long_arg] != s->current_picture_ptr) {
  2918. remove_long(h, mmco[i].long_arg, 0);
  2919. h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
  2920. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  2921. h->long_ref_count++;
  2922. }
  2923. s->current_picture_ptr->reference |= s->picture_structure;
  2924. current_ref_assigned=1;
  2925. break;
  2926. case MMCO_SET_MAX_LONG:
  2927. assert(mmco[i].long_arg <= 16);
  2928. // just remove the long term which index is greater than new max
  2929. for(j = mmco[i].long_arg; j<16; j++){
  2930. remove_long(h, j, 0);
  2931. }
  2932. break;
  2933. case MMCO_RESET:
  2934. while(h->short_ref_count){
  2935. remove_short(h, h->short_ref[0]->frame_num, 0);
  2936. }
  2937. for(j = 0; j < 16; j++) {
  2938. remove_long(h, j, 0);
  2939. }
  2940. s->current_picture_ptr->poc=
  2941. s->current_picture_ptr->field_poc[0]=
  2942. s->current_picture_ptr->field_poc[1]=
  2943. h->poc_lsb=
  2944. h->poc_msb=
  2945. h->frame_num=
  2946. s->current_picture_ptr->frame_num= 0;
  2947. break;
  2948. default: assert(0);
  2949. }
  2950. }
  2951. if (!current_ref_assigned) {
  2952. /* Second field of complementary field pair; the first field of
  2953. * which is already referenced. If short referenced, it
  2954. * should be first entry in short_ref. If not, it must exist
  2955. * in long_ref; trying to put it on the short list here is an
  2956. * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
  2957. */
  2958. if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
  2959. /* Just mark the second field valid */
  2960. s->current_picture_ptr->reference = PICT_FRAME;
  2961. } else if (s->current_picture_ptr->long_ref) {
  2962. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
  2963. "assignment for second field "
  2964. "in complementary field pair "
  2965. "(first field is long term)\n");
  2966. } else {
  2967. pic= remove_short(h, s->current_picture_ptr->frame_num, 0);
  2968. if(pic){
  2969. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
  2970. }
  2971. if(h->short_ref_count)
  2972. memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
  2973. h->short_ref[0]= s->current_picture_ptr;
  2974. h->short_ref_count++;
  2975. s->current_picture_ptr->reference |= s->picture_structure;
  2976. }
  2977. }
  2978. if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
  2979. /* We have too many reference frames, probably due to corrupted
  2980. * stream. Need to discard one frame. Prevents overrun of the
  2981. * short_ref and long_ref buffers.
  2982. */
  2983. av_log(h->s.avctx, AV_LOG_ERROR,
  2984. "number of reference frames exceeds max (probably "
  2985. "corrupt input), discarding one\n");
  2986. if (h->long_ref_count && !h->short_ref_count) {
  2987. for (i = 0; i < 16; ++i)
  2988. if (h->long_ref[i])
  2989. break;
  2990. assert(i < 16);
  2991. remove_long(h, i, 0);
  2992. } else {
  2993. pic = h->short_ref[h->short_ref_count - 1];
  2994. remove_short(h, pic->frame_num, 0);
  2995. }
  2996. }
  2997. print_short_term(h);
  2998. print_long_term(h);
  2999. return 0;
  3000. }
  3001. static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
  3002. MpegEncContext * const s = &h->s;
  3003. int i;
  3004. h->mmco_index= 0;
  3005. if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
  3006. s->broken_link= get_bits1(gb) -1;
  3007. if(get_bits1(gb)){
  3008. h->mmco[0].opcode= MMCO_LONG;
  3009. h->mmco[0].long_arg= 0;
  3010. h->mmco_index= 1;
  3011. }
  3012. }else{
  3013. if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
  3014. for(i= 0; i<MAX_MMCO_COUNT; i++) {
  3015. MMCOOpcode opcode= get_ue_golomb(gb);
  3016. h->mmco[i].opcode= opcode;
  3017. if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
  3018. h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
  3019. /* if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
  3020. av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
  3021. return -1;
  3022. }*/
  3023. }
  3024. if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
  3025. unsigned int long_arg= get_ue_golomb(gb);
  3026. if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
  3027. av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
  3028. return -1;
  3029. }
  3030. h->mmco[i].long_arg= long_arg;
  3031. }
  3032. if(opcode > (unsigned)MMCO_LONG){
  3033. av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
  3034. return -1;
  3035. }
  3036. if(opcode == MMCO_END)
  3037. break;
  3038. }
  3039. h->mmco_index= i;
  3040. }else{
  3041. assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
  3042. if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
  3043. !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
  3044. h->mmco[0].opcode= MMCO_SHORT2UNUSED;
  3045. h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
  3046. h->mmco_index= 1;
  3047. if (FIELD_PICTURE) {
  3048. h->mmco[0].short_pic_num *= 2;
  3049. h->mmco[1].opcode= MMCO_SHORT2UNUSED;
  3050. h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
  3051. h->mmco_index= 2;
  3052. }
  3053. }
  3054. }
  3055. }
  3056. return 0;
  3057. }
  3058. static int init_poc(H264Context *h){
  3059. MpegEncContext * const s = &h->s;
  3060. const int max_frame_num= 1<<h->sps.log2_max_frame_num;
  3061. int field_poc[2];
  3062. Picture *cur = s->current_picture_ptr;
  3063. h->frame_num_offset= h->prev_frame_num_offset;
  3064. if(h->frame_num < h->prev_frame_num)
  3065. h->frame_num_offset += max_frame_num;
  3066. if(h->sps.poc_type==0){
  3067. const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
  3068. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
  3069. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  3070. else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
  3071. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  3072. else
  3073. h->poc_msb = h->prev_poc_msb;
  3074. //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
  3075. field_poc[0] =
  3076. field_poc[1] = h->poc_msb + h->poc_lsb;
  3077. if(s->picture_structure == PICT_FRAME)
  3078. field_poc[1] += h->delta_poc_bottom;
  3079. }else if(h->sps.poc_type==1){
  3080. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  3081. int i;
  3082. if(h->sps.poc_cycle_length != 0)
  3083. abs_frame_num = h->frame_num_offset + h->frame_num;
  3084. else
  3085. abs_frame_num = 0;
  3086. if(h->nal_ref_idc==0 && abs_frame_num > 0)
  3087. abs_frame_num--;
  3088. expected_delta_per_poc_cycle = 0;
  3089. for(i=0; i < h->sps.poc_cycle_length; i++)
  3090. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
  3091. if(abs_frame_num > 0){
  3092. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  3093. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  3094. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  3095. for(i = 0; i <= frame_num_in_poc_cycle; i++)
  3096. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
  3097. } else
  3098. expectedpoc = 0;
  3099. if(h->nal_ref_idc == 0)
  3100. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  3101. field_poc[0] = expectedpoc + h->delta_poc[0];
  3102. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  3103. if(s->picture_structure == PICT_FRAME)
  3104. field_poc[1] += h->delta_poc[1];
  3105. }else{
  3106. int poc= 2*(h->frame_num_offset + h->frame_num);
  3107. if(!h->nal_ref_idc)
  3108. poc--;
  3109. field_poc[0]= poc;
  3110. field_poc[1]= poc;
  3111. }
  3112. if(s->picture_structure != PICT_BOTTOM_FIELD)
  3113. s->current_picture_ptr->field_poc[0]= field_poc[0];
  3114. if(s->picture_structure != PICT_TOP_FIELD)
  3115. s->current_picture_ptr->field_poc[1]= field_poc[1];
  3116. cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
  3117. return 0;
  3118. }
  3119. /**
  3120. * initialize scan tables
  3121. */
  3122. static void init_scan_tables(H264Context *h){
  3123. MpegEncContext * const s = &h->s;
  3124. int i;
  3125. if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
  3126. memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
  3127. memcpy(h-> field_scan, field_scan, 16*sizeof(uint8_t));
  3128. }else{
  3129. for(i=0; i<16; i++){
  3130. #define T(x) (x>>2) | ((x<<2) & 0xF)
  3131. h->zigzag_scan[i] = T(zigzag_scan[i]);
  3132. h-> field_scan[i] = T( field_scan[i]);
  3133. #undef T
  3134. }
  3135. }
  3136. if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){
  3137. memcpy(h->zigzag_scan8x8, zigzag_scan8x8, 64*sizeof(uint8_t));
  3138. memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
  3139. memcpy(h->field_scan8x8, field_scan8x8, 64*sizeof(uint8_t));
  3140. memcpy(h->field_scan8x8_cavlc, field_scan8x8_cavlc, 64*sizeof(uint8_t));
  3141. }else{
  3142. for(i=0; i<64; i++){
  3143. #define T(x) (x>>3) | ((x&7)<<3)
  3144. h->zigzag_scan8x8[i] = T(zigzag_scan8x8[i]);
  3145. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  3146. h->field_scan8x8[i] = T(field_scan8x8[i]);
  3147. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  3148. #undef T
  3149. }
  3150. }
  3151. if(h->sps.transform_bypass){ //FIXME same ugly
  3152. h->zigzag_scan_q0 = zigzag_scan;
  3153. h->zigzag_scan8x8_q0 = zigzag_scan8x8;
  3154. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  3155. h->field_scan_q0 = field_scan;
  3156. h->field_scan8x8_q0 = field_scan8x8;
  3157. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  3158. }else{
  3159. h->zigzag_scan_q0 = h->zigzag_scan;
  3160. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  3161. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  3162. h->field_scan_q0 = h->field_scan;
  3163. h->field_scan8x8_q0 = h->field_scan8x8;
  3164. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  3165. }
  3166. }
  3167. /**
  3168. * Replicates H264 "master" context to thread contexts.
  3169. */
  3170. static void clone_slice(H264Context *dst, H264Context *src)
  3171. {
  3172. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  3173. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  3174. dst->s.current_picture = src->s.current_picture;
  3175. dst->s.linesize = src->s.linesize;
  3176. dst->s.uvlinesize = src->s.uvlinesize;
  3177. dst->s.first_field = src->s.first_field;
  3178. dst->prev_poc_msb = src->prev_poc_msb;
  3179. dst->prev_poc_lsb = src->prev_poc_lsb;
  3180. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  3181. dst->prev_frame_num = src->prev_frame_num;
  3182. dst->short_ref_count = src->short_ref_count;
  3183. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  3184. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  3185. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  3186. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  3187. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  3188. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  3189. }
  3190. /**
  3191. * decodes a slice header.
  3192. * This will also call MPV_common_init() and frame_start() as needed.
  3193. *
  3194. * @param h h264context
  3195. * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
  3196. *
  3197. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  3198. */
  3199. static int decode_slice_header(H264Context *h, H264Context *h0){
  3200. MpegEncContext * const s = &h->s;
  3201. MpegEncContext * const s0 = &h0->s;
  3202. unsigned int first_mb_in_slice;
  3203. unsigned int pps_id;
  3204. int num_ref_idx_active_override_flag;
  3205. static const uint8_t slice_type_map[5]= {FF_P_TYPE, FF_B_TYPE, FF_I_TYPE, FF_SP_TYPE, FF_SI_TYPE};
  3206. unsigned int slice_type, tmp, i, j;
  3207. int default_ref_list_done = 0;
  3208. int last_pic_structure;
  3209. s->dropable= h->nal_ref_idc == 0;
  3210. if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
  3211. s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
  3212. s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
  3213. }else{
  3214. s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
  3215. s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
  3216. }
  3217. first_mb_in_slice= get_ue_golomb(&s->gb);
  3218. if((s->flags2 & CODEC_FLAG2_CHUNKS) && first_mb_in_slice == 0){
  3219. h0->current_slice = 0;
  3220. if (!s0->first_field)
  3221. s->current_picture_ptr= NULL;
  3222. }
  3223. slice_type= get_ue_golomb(&s->gb);
  3224. if(slice_type > 9){
  3225. 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);
  3226. return -1;
  3227. }
  3228. if(slice_type > 4){
  3229. slice_type -= 5;
  3230. h->slice_type_fixed=1;
  3231. }else
  3232. h->slice_type_fixed=0;
  3233. slice_type= slice_type_map[ slice_type ];
  3234. if (slice_type == FF_I_TYPE
  3235. || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
  3236. default_ref_list_done = 1;
  3237. }
  3238. h->slice_type= slice_type;
  3239. h->slice_type_nos= slice_type & 3;
  3240. s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
  3241. if (s->pict_type == FF_B_TYPE && s0->last_picture_ptr == NULL) {
  3242. av_log(h->s.avctx, AV_LOG_ERROR,
  3243. "B picture before any references, skipping\n");
  3244. return -1;
  3245. }
  3246. pps_id= get_ue_golomb(&s->gb);
  3247. if(pps_id>=MAX_PPS_COUNT){
  3248. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  3249. return -1;
  3250. }
  3251. if(!h0->pps_buffers[pps_id]) {
  3252. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS referenced\n");
  3253. return -1;
  3254. }
  3255. h->pps= *h0->pps_buffers[pps_id];
  3256. if(!h0->sps_buffers[h->pps.sps_id]) {
  3257. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS referenced\n");
  3258. return -1;
  3259. }
  3260. h->sps = *h0->sps_buffers[h->pps.sps_id];
  3261. if(h == h0 && h->dequant_coeff_pps != pps_id){
  3262. h->dequant_coeff_pps = pps_id;
  3263. init_dequant_tables(h);
  3264. }
  3265. s->mb_width= h->sps.mb_width;
  3266. s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  3267. h->b_stride= s->mb_width*4;
  3268. h->b8_stride= s->mb_width*2;
  3269. s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
  3270. if(h->sps.frame_mbs_only_flag)
  3271. s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
  3272. else
  3273. s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 3);
  3274. if (s->context_initialized
  3275. && ( s->width != s->avctx->width || s->height != s->avctx->height)) {
  3276. if(h != h0)
  3277. return -1; // width / height changed during parallelized decoding
  3278. free_tables(h);
  3279. MPV_common_end(s);
  3280. }
  3281. if (!s->context_initialized) {
  3282. if(h != h0)
  3283. return -1; // we cant (re-)initialize context during parallel decoding
  3284. if (MPV_common_init(s) < 0)
  3285. return -1;
  3286. s->first_field = 0;
  3287. init_scan_tables(h);
  3288. alloc_tables(h);
  3289. for(i = 1; i < s->avctx->thread_count; i++) {
  3290. H264Context *c;
  3291. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  3292. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  3293. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  3294. c->sps = h->sps;
  3295. c->pps = h->pps;
  3296. init_scan_tables(c);
  3297. clone_tables(c, h);
  3298. }
  3299. for(i = 0; i < s->avctx->thread_count; i++)
  3300. if(context_init(h->thread_context[i]) < 0)
  3301. return -1;
  3302. s->avctx->width = s->width;
  3303. s->avctx->height = s->height;
  3304. s->avctx->sample_aspect_ratio= h->sps.sar;
  3305. if(!s->avctx->sample_aspect_ratio.den)
  3306. s->avctx->sample_aspect_ratio.den = 1;
  3307. if(h->sps.timing_info_present_flag){
  3308. s->avctx->time_base= (AVRational){h->sps.num_units_in_tick * 2, h->sps.time_scale};
  3309. if(h->x264_build > 0 && h->x264_build < 44)
  3310. s->avctx->time_base.den *= 2;
  3311. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  3312. s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);
  3313. }
  3314. }
  3315. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  3316. h->mb_mbaff = 0;
  3317. h->mb_aff_frame = 0;
  3318. last_pic_structure = s0->picture_structure;
  3319. if(h->sps.frame_mbs_only_flag){
  3320. s->picture_structure= PICT_FRAME;
  3321. }else{
  3322. if(get_bits1(&s->gb)) { //field_pic_flag
  3323. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  3324. } else {
  3325. s->picture_structure= PICT_FRAME;
  3326. h->mb_aff_frame = h->sps.mb_aff;
  3327. }
  3328. }
  3329. h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
  3330. if(h0->current_slice == 0){
  3331. while(h->frame_num != h->prev_frame_num &&
  3332. h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
  3333. av_log(NULL, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
  3334. frame_start(h);
  3335. h->prev_frame_num++;
  3336. h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
  3337. s->current_picture_ptr->frame_num= h->prev_frame_num;
  3338. execute_ref_pic_marking(h, NULL, 0);
  3339. }
  3340. /* See if we have a decoded first field looking for a pair... */
  3341. if (s0->first_field) {
  3342. assert(s0->current_picture_ptr);
  3343. assert(s0->current_picture_ptr->data[0]);
  3344. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  3345. /* figure out if we have a complementary field pair */
  3346. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  3347. /*
  3348. * Previous field is unmatched. Don't display it, but let it
  3349. * remain for reference if marked as such.
  3350. */
  3351. s0->current_picture_ptr = NULL;
  3352. s0->first_field = FIELD_PICTURE;
  3353. } else {
  3354. if (h->nal_ref_idc &&
  3355. s0->current_picture_ptr->reference &&
  3356. s0->current_picture_ptr->frame_num != h->frame_num) {
  3357. /*
  3358. * This and previous field were reference, but had
  3359. * different frame_nums. Consider this field first in
  3360. * pair. Throw away previous field except for reference
  3361. * purposes.
  3362. */
  3363. s0->first_field = 1;
  3364. s0->current_picture_ptr = NULL;
  3365. } else {
  3366. /* Second field in complementary pair */
  3367. s0->first_field = 0;
  3368. }
  3369. }
  3370. } else {
  3371. /* Frame or first field in a potentially complementary pair */
  3372. assert(!s0->current_picture_ptr);
  3373. s0->first_field = FIELD_PICTURE;
  3374. }
  3375. if((!FIELD_PICTURE || s0->first_field) && frame_start(h) < 0) {
  3376. s0->first_field = 0;
  3377. return -1;
  3378. }
  3379. }
  3380. if(h != h0)
  3381. clone_slice(h, h0);
  3382. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  3383. assert(s->mb_num == s->mb_width * s->mb_height);
  3384. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  3385. first_mb_in_slice >= s->mb_num){
  3386. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  3387. return -1;
  3388. }
  3389. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  3390. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  3391. if (s->picture_structure == PICT_BOTTOM_FIELD)
  3392. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  3393. assert(s->mb_y < s->mb_height);
  3394. if(s->picture_structure==PICT_FRAME){
  3395. h->curr_pic_num= h->frame_num;
  3396. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  3397. }else{
  3398. h->curr_pic_num= 2*h->frame_num + 1;
  3399. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  3400. }
  3401. if(h->nal_unit_type == NAL_IDR_SLICE){
  3402. get_ue_golomb(&s->gb); /* idr_pic_id */
  3403. }
  3404. if(h->sps.poc_type==0){
  3405. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  3406. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  3407. h->delta_poc_bottom= get_se_golomb(&s->gb);
  3408. }
  3409. }
  3410. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  3411. h->delta_poc[0]= get_se_golomb(&s->gb);
  3412. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  3413. h->delta_poc[1]= get_se_golomb(&s->gb);
  3414. }
  3415. init_poc(h);
  3416. if(h->pps.redundant_pic_cnt_present){
  3417. h->redundant_pic_count= get_ue_golomb(&s->gb);
  3418. }
  3419. //set defaults, might be overridden a few lines later
  3420. h->ref_count[0]= h->pps.ref_count[0];
  3421. h->ref_count[1]= h->pps.ref_count[1];
  3422. if(h->slice_type_nos != FF_I_TYPE){
  3423. if(h->slice_type_nos == FF_B_TYPE){
  3424. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  3425. }
  3426. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  3427. if(num_ref_idx_active_override_flag){
  3428. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  3429. if(h->slice_type_nos==FF_B_TYPE)
  3430. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  3431. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  3432. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  3433. h->ref_count[0]= h->ref_count[1]= 1;
  3434. return -1;
  3435. }
  3436. }
  3437. if(h->slice_type_nos == FF_B_TYPE)
  3438. h->list_count= 2;
  3439. else
  3440. h->list_count= 1;
  3441. }else
  3442. h->list_count= 0;
  3443. if(!default_ref_list_done){
  3444. fill_default_ref_list(h);
  3445. }
  3446. if(h->slice_type_nos!=FF_I_TYPE && decode_ref_pic_list_reordering(h) < 0)
  3447. return -1;
  3448. if( (h->pps.weighted_pred && h->slice_type_nos == FF_P_TYPE )
  3449. || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
  3450. pred_weight_table(h);
  3451. else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE)
  3452. implicit_weight_table(h);
  3453. else
  3454. h->use_weight = 0;
  3455. if(h->nal_ref_idc)
  3456. decode_ref_pic_marking(h0, &s->gb);
  3457. if(FRAME_MBAFF)
  3458. fill_mbaff_ref_list(h);
  3459. if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
  3460. tmp = get_ue_golomb(&s->gb);
  3461. if(tmp > 2){
  3462. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  3463. return -1;
  3464. }
  3465. h->cabac_init_idc= tmp;
  3466. }
  3467. h->last_qscale_diff = 0;
  3468. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  3469. if(tmp>51){
  3470. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3471. return -1;
  3472. }
  3473. s->qscale= tmp;
  3474. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3475. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3476. //FIXME qscale / qp ... stuff
  3477. if(h->slice_type == FF_SP_TYPE){
  3478. get_bits1(&s->gb); /* sp_for_switch_flag */
  3479. }
  3480. if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
  3481. get_se_golomb(&s->gb); /* slice_qs_delta */
  3482. }
  3483. h->deblocking_filter = 1;
  3484. h->slice_alpha_c0_offset = 0;
  3485. h->slice_beta_offset = 0;
  3486. if( h->pps.deblocking_filter_parameters_present ) {
  3487. tmp= get_ue_golomb(&s->gb);
  3488. if(tmp > 2){
  3489. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  3490. return -1;
  3491. }
  3492. h->deblocking_filter= tmp;
  3493. if(h->deblocking_filter < 2)
  3494. h->deblocking_filter^= 1; // 1<->0
  3495. if( h->deblocking_filter ) {
  3496. h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
  3497. h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
  3498. }
  3499. }
  3500. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  3501. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
  3502. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == FF_B_TYPE)
  3503. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  3504. h->deblocking_filter= 0;
  3505. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3506. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  3507. /* Cheat slightly for speed:
  3508. Do not bother to deblock across slices. */
  3509. h->deblocking_filter = 2;
  3510. } else {
  3511. h0->max_contexts = 1;
  3512. if(!h0->single_decode_warning) {
  3513. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3514. h0->single_decode_warning = 1;
  3515. }
  3516. if(h != h0)
  3517. return 1; // deblocking switched inside frame
  3518. }
  3519. }
  3520. #if 0 //FMO
  3521. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  3522. slice_group_change_cycle= get_bits(&s->gb, ?);
  3523. #endif
  3524. h0->last_slice_type = slice_type;
  3525. h->slice_num = ++h0->current_slice;
  3526. for(j=0; j<2; j++){
  3527. int *ref2frm= h->ref2frm[h->slice_num&15][j];
  3528. ref2frm[0]=
  3529. ref2frm[1]= -1;
  3530. for(i=0; i<16; i++)
  3531. ref2frm[i+2]= 4*h->ref_list[j][i].frame_num
  3532. +(h->ref_list[j][i].reference&3);
  3533. ref2frm[18+0]=
  3534. ref2frm[18+1]= -1;
  3535. for(i=16; i<48; i++)
  3536. ref2frm[i+4]= 4*h->ref_list[j][i].frame_num
  3537. +(h->ref_list[j][i].reference&3);
  3538. }
  3539. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
  3540. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  3541. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  3542. 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",
  3543. h->slice_num,
  3544. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  3545. first_mb_in_slice,
  3546. av_get_pict_type_char(h->slice_type),
  3547. pps_id, h->frame_num,
  3548. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  3549. h->ref_count[0], h->ref_count[1],
  3550. s->qscale,
  3551. h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,
  3552. h->use_weight,
  3553. h->use_weight==1 && h->use_weight_chroma ? "c" : "",
  3554. h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
  3555. );
  3556. }
  3557. return 0;
  3558. }
  3559. /**
  3560. *
  3561. */
  3562. static inline int get_level_prefix(GetBitContext *gb){
  3563. unsigned int buf;
  3564. int log;
  3565. OPEN_READER(re, gb);
  3566. UPDATE_CACHE(re, gb);
  3567. buf=GET_CACHE(re, gb);
  3568. log= 32 - av_log2(buf);
  3569. #ifdef TRACE
  3570. print_bin(buf>>(32-log), log);
  3571. 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__);
  3572. #endif
  3573. LAST_SKIP_BITS(re, gb, log);
  3574. CLOSE_READER(re, gb);
  3575. return log-1;
  3576. }
  3577. static inline int get_dct8x8_allowed(H264Context *h){
  3578. int i;
  3579. for(i=0; i<4; i++){
  3580. if(!IS_SUB_8X8(h->sub_mb_type[i])
  3581. || (!h->sps.direct_8x8_inference_flag && IS_DIRECT(h->sub_mb_type[i])))
  3582. return 0;
  3583. }
  3584. return 1;
  3585. }
  3586. /**
  3587. * decodes a residual block.
  3588. * @param n block index
  3589. * @param scantable scantable
  3590. * @param max_coeff number of coefficients in the block
  3591. * @return <0 if an error occurred
  3592. */
  3593. static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
  3594. MpegEncContext * const s = &h->s;
  3595. 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};
  3596. int level[16];
  3597. int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
  3598. //FIXME put trailing_onex into the context
  3599. if(n == CHROMA_DC_BLOCK_INDEX){
  3600. coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
  3601. total_coeff= coeff_token>>2;
  3602. }else{
  3603. if(n == LUMA_DC_BLOCK_INDEX){
  3604. total_coeff= pred_non_zero_count(h, 0);
  3605. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3606. total_coeff= coeff_token>>2;
  3607. }else{
  3608. total_coeff= pred_non_zero_count(h, n);
  3609. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3610. total_coeff= coeff_token>>2;
  3611. h->non_zero_count_cache[ scan8[n] ]= total_coeff;
  3612. }
  3613. }
  3614. //FIXME set last_non_zero?
  3615. if(total_coeff==0)
  3616. return 0;
  3617. if(total_coeff > (unsigned)max_coeff) {
  3618. av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);
  3619. return -1;
  3620. }
  3621. trailing_ones= coeff_token&3;
  3622. tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);
  3623. assert(total_coeff<=16);
  3624. for(i=0; i<trailing_ones; i++){
  3625. level[i]= 1 - 2*get_bits1(gb);
  3626. }
  3627. if(i<total_coeff) {
  3628. int level_code, mask;
  3629. int suffix_length = total_coeff > 10 && trailing_ones < 3;
  3630. int prefix= get_level_prefix(gb);
  3631. //first coefficient has suffix_length equal to 0 or 1
  3632. if(prefix<14){ //FIXME try to build a large unified VLC table for all this
  3633. if(suffix_length)
  3634. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3635. else
  3636. level_code= (prefix<<suffix_length); //part
  3637. }else if(prefix==14){
  3638. if(suffix_length)
  3639. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3640. else
  3641. level_code= prefix + get_bits(gb, 4); //part
  3642. }else{
  3643. level_code= (15<<suffix_length) + get_bits(gb, prefix-3); //part
  3644. if(suffix_length==0) level_code+=15; //FIXME doesn't make (much)sense
  3645. if(prefix>=16)
  3646. level_code += (1<<(prefix-3))-4096;
  3647. }
  3648. if(trailing_ones < 3) level_code += 2;
  3649. suffix_length = 1;
  3650. if(level_code > 5)
  3651. suffix_length++;
  3652. mask= -(level_code&1);
  3653. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3654. i++;
  3655. //remaining coefficients have suffix_length > 0
  3656. for(;i<total_coeff;i++) {
  3657. static const int suffix_limit[7] = {0,5,11,23,47,95,INT_MAX };
  3658. prefix = get_level_prefix(gb);
  3659. if(prefix<15){
  3660. level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);
  3661. }else{
  3662. level_code = (15<<suffix_length) + get_bits(gb, prefix-3);
  3663. if(prefix>=16)
  3664. level_code += (1<<(prefix-3))-4096;
  3665. }
  3666. mask= -(level_code&1);
  3667. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3668. if(level_code > suffix_limit[suffix_length])
  3669. suffix_length++;
  3670. }
  3671. }
  3672. if(total_coeff == max_coeff)
  3673. zeros_left=0;
  3674. else{
  3675. if(n == CHROMA_DC_BLOCK_INDEX)
  3676. zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
  3677. else
  3678. zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
  3679. }
  3680. coeff_num = zeros_left + total_coeff - 1;
  3681. j = scantable[coeff_num];
  3682. if(n > 24){
  3683. block[j] = level[0];
  3684. for(i=1;i<total_coeff;i++) {
  3685. if(zeros_left <= 0)
  3686. run_before = 0;
  3687. else if(zeros_left < 7){
  3688. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3689. }else{
  3690. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3691. }
  3692. zeros_left -= run_before;
  3693. coeff_num -= 1 + run_before;
  3694. j= scantable[ coeff_num ];
  3695. block[j]= level[i];
  3696. }
  3697. }else{
  3698. block[j] = (level[0] * qmul[j] + 32)>>6;
  3699. for(i=1;i<total_coeff;i++) {
  3700. if(zeros_left <= 0)
  3701. run_before = 0;
  3702. else if(zeros_left < 7){
  3703. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3704. }else{
  3705. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3706. }
  3707. zeros_left -= run_before;
  3708. coeff_num -= 1 + run_before;
  3709. j= scantable[ coeff_num ];
  3710. block[j]= (level[i] * qmul[j] + 32)>>6;
  3711. }
  3712. }
  3713. if(zeros_left<0){
  3714. av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
  3715. return -1;
  3716. }
  3717. return 0;
  3718. }
  3719. static void predict_field_decoding_flag(H264Context *h){
  3720. MpegEncContext * const s = &h->s;
  3721. const int mb_xy= h->mb_xy;
  3722. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  3723. ? s->current_picture.mb_type[mb_xy-1]
  3724. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  3725. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  3726. : 0;
  3727. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3728. }
  3729. /**
  3730. * decodes a P_SKIP or B_SKIP macroblock
  3731. */
  3732. static void decode_mb_skip(H264Context *h){
  3733. MpegEncContext * const s = &h->s;
  3734. const int mb_xy= h->mb_xy;
  3735. int mb_type=0;
  3736. memset(h->non_zero_count[mb_xy], 0, 16);
  3737. memset(h->non_zero_count_cache + 8, 0, 8*5); //FIXME ugly, remove pfui
  3738. if(MB_FIELD)
  3739. mb_type|= MB_TYPE_INTERLACED;
  3740. if( h->slice_type_nos == FF_B_TYPE )
  3741. {
  3742. // just for fill_caches. pred_direct_motion will set the real mb_type
  3743. mb_type|= MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
  3744. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3745. pred_direct_motion(h, &mb_type);
  3746. mb_type|= MB_TYPE_SKIP;
  3747. }
  3748. else
  3749. {
  3750. int mx, my;
  3751. mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
  3752. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3753. pred_pskip_motion(h, &mx, &my);
  3754. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
  3755. fill_rectangle( h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
  3756. }
  3757. write_back_motion(h, mb_type);
  3758. s->current_picture.mb_type[mb_xy]= mb_type;
  3759. s->current_picture.qscale_table[mb_xy]= s->qscale;
  3760. h->slice_table[ mb_xy ]= h->slice_num;
  3761. h->prev_mb_skipped= 1;
  3762. }
  3763. /**
  3764. * decodes a macroblock
  3765. * @returns 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  3766. */
  3767. static int decode_mb_cavlc(H264Context *h){
  3768. MpegEncContext * const s = &h->s;
  3769. int mb_xy;
  3770. int partition_count;
  3771. unsigned int mb_type, cbp;
  3772. int dct8x8_allowed= h->pps.transform_8x8_mode;
  3773. mb_xy = h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  3774. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?
  3775. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  3776. cbp = 0; /* avoid warning. FIXME: find a solution without slowing
  3777. down the code */
  3778. if(h->slice_type_nos != FF_I_TYPE){
  3779. if(s->mb_skip_run==-1)
  3780. s->mb_skip_run= get_ue_golomb(&s->gb);
  3781. if (s->mb_skip_run--) {
  3782. if(FRAME_MBAFF && (s->mb_y&1) == 0){
  3783. if(s->mb_skip_run==0)
  3784. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3785. else
  3786. predict_field_decoding_flag(h);
  3787. }
  3788. decode_mb_skip(h);
  3789. return 0;
  3790. }
  3791. }
  3792. if(FRAME_MBAFF){
  3793. if( (s->mb_y&1) == 0 )
  3794. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3795. }
  3796. h->prev_mb_skipped= 0;
  3797. mb_type= get_ue_golomb(&s->gb);
  3798. if(h->slice_type_nos == FF_B_TYPE){
  3799. if(mb_type < 23){
  3800. partition_count= b_mb_type_info[mb_type].partition_count;
  3801. mb_type= b_mb_type_info[mb_type].type;
  3802. }else{
  3803. mb_type -= 23;
  3804. goto decode_intra_mb;
  3805. }
  3806. }else if(h->slice_type_nos == FF_P_TYPE){
  3807. if(mb_type < 5){
  3808. partition_count= p_mb_type_info[mb_type].partition_count;
  3809. mb_type= p_mb_type_info[mb_type].type;
  3810. }else{
  3811. mb_type -= 5;
  3812. goto decode_intra_mb;
  3813. }
  3814. }else{
  3815. assert(h->slice_type_nos == FF_I_TYPE);
  3816. if(h->slice_type == FF_SI_TYPE && mb_type)
  3817. mb_type--;
  3818. decode_intra_mb:
  3819. if(mb_type > 25){
  3820. 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);
  3821. return -1;
  3822. }
  3823. partition_count=0;
  3824. cbp= i_mb_type_info[mb_type].cbp;
  3825. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  3826. mb_type= i_mb_type_info[mb_type].type;
  3827. }
  3828. if(MB_FIELD)
  3829. mb_type |= MB_TYPE_INTERLACED;
  3830. h->slice_table[ mb_xy ]= h->slice_num;
  3831. if(IS_INTRA_PCM(mb_type)){
  3832. unsigned int x;
  3833. // We assume these blocks are very rare so we do not optimize it.
  3834. align_get_bits(&s->gb);
  3835. // The pixels are stored in the same order as levels in h->mb array.
  3836. for(x=0; x < (CHROMA ? 384 : 256); x++){
  3837. ((uint8_t*)h->mb)[x]= get_bits(&s->gb, 8);
  3838. }
  3839. // In deblocking, the quantizer is 0
  3840. s->current_picture.qscale_table[mb_xy]= 0;
  3841. // All coeffs are present
  3842. memset(h->non_zero_count[mb_xy], 16, 16);
  3843. s->current_picture.mb_type[mb_xy]= mb_type;
  3844. return 0;
  3845. }
  3846. if(MB_MBAFF){
  3847. h->ref_count[0] <<= 1;
  3848. h->ref_count[1] <<= 1;
  3849. }
  3850. fill_caches(h, mb_type, 0);
  3851. //mb_pred
  3852. if(IS_INTRA(mb_type)){
  3853. int pred_mode;
  3854. // init_top_left_availability(h);
  3855. if(IS_INTRA4x4(mb_type)){
  3856. int i;
  3857. int di = 1;
  3858. if(dct8x8_allowed && get_bits1(&s->gb)){
  3859. mb_type |= MB_TYPE_8x8DCT;
  3860. di = 4;
  3861. }
  3862. // fill_intra4x4_pred_table(h);
  3863. for(i=0; i<16; i+=di){
  3864. int mode= pred_intra_mode(h, i);
  3865. if(!get_bits1(&s->gb)){
  3866. const int rem_mode= get_bits(&s->gb, 3);
  3867. mode = rem_mode + (rem_mode >= mode);
  3868. }
  3869. if(di==4)
  3870. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  3871. else
  3872. h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
  3873. }
  3874. write_back_intra_pred_mode(h);
  3875. if( check_intra4x4_pred_mode(h) < 0)
  3876. return -1;
  3877. }else{
  3878. h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
  3879. if(h->intra16x16_pred_mode < 0)
  3880. return -1;
  3881. }
  3882. if(CHROMA){
  3883. pred_mode= check_intra_pred_mode(h, get_ue_golomb(&s->gb));
  3884. if(pred_mode < 0)
  3885. return -1;
  3886. h->chroma_pred_mode= pred_mode;
  3887. }
  3888. }else if(partition_count==4){
  3889. int i, j, sub_partition_count[4], list, ref[2][4];
  3890. if(h->slice_type_nos == FF_B_TYPE){
  3891. for(i=0; i<4; i++){
  3892. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  3893. if(h->sub_mb_type[i] >=13){
  3894. 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);
  3895. return -1;
  3896. }
  3897. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  3898. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  3899. }
  3900. if( IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])
  3901. || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3])) {
  3902. pred_direct_motion(h, &mb_type);
  3903. h->ref_cache[0][scan8[4]] =
  3904. h->ref_cache[1][scan8[4]] =
  3905. h->ref_cache[0][scan8[12]] =
  3906. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  3907. }
  3908. }else{
  3909. assert(h->slice_type_nos == FF_P_TYPE); //FIXME SP correct ?
  3910. for(i=0; i<4; i++){
  3911. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  3912. if(h->sub_mb_type[i] >=4){
  3913. 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);
  3914. return -1;
  3915. }
  3916. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  3917. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  3918. }
  3919. }
  3920. for(list=0; list<h->list_count; list++){
  3921. int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
  3922. for(i=0; i<4; i++){
  3923. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  3924. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  3925. unsigned int tmp = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?
  3926. if(tmp>=ref_count){
  3927. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);
  3928. return -1;
  3929. }
  3930. ref[list][i]= tmp;
  3931. }else{
  3932. //FIXME
  3933. ref[list][i] = -1;
  3934. }
  3935. }
  3936. }
  3937. if(dct8x8_allowed)
  3938. dct8x8_allowed = get_dct8x8_allowed(h);
  3939. for(list=0; list<h->list_count; list++){
  3940. for(i=0; i<4; i++){
  3941. if(IS_DIRECT(h->sub_mb_type[i])) {
  3942. h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];
  3943. continue;
  3944. }
  3945. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ]=
  3946. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  3947. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  3948. const int sub_mb_type= h->sub_mb_type[i];
  3949. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  3950. for(j=0; j<sub_partition_count[i]; j++){
  3951. int mx, my;
  3952. const int index= 4*i + block_width*j;
  3953. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  3954. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
  3955. mx += get_se_golomb(&s->gb);
  3956. my += get_se_golomb(&s->gb);
  3957. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  3958. if(IS_SUB_8X8(sub_mb_type)){
  3959. mv_cache[ 1 ][0]=
  3960. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  3961. mv_cache[ 1 ][1]=
  3962. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  3963. }else if(IS_SUB_8X4(sub_mb_type)){
  3964. mv_cache[ 1 ][0]= mx;
  3965. mv_cache[ 1 ][1]= my;
  3966. }else if(IS_SUB_4X8(sub_mb_type)){
  3967. mv_cache[ 8 ][0]= mx;
  3968. mv_cache[ 8 ][1]= my;
  3969. }
  3970. mv_cache[ 0 ][0]= mx;
  3971. mv_cache[ 0 ][1]= my;
  3972. }
  3973. }else{
  3974. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  3975. p[0] = p[1]=
  3976. p[8] = p[9]= 0;
  3977. }
  3978. }
  3979. }
  3980. }else if(IS_DIRECT(mb_type)){
  3981. pred_direct_motion(h, &mb_type);
  3982. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  3983. }else{
  3984. int list, mx, my, i;
  3985. //FIXME we should set ref_idx_l? to 0 if we use that later ...
  3986. if(IS_16X16(mb_type)){
  3987. for(list=0; list<h->list_count; list++){
  3988. unsigned int val;
  3989. if(IS_DIR(mb_type, 0, list)){
  3990. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  3991. if(val >= h->ref_count[list]){
  3992. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  3993. return -1;
  3994. }
  3995. }else
  3996. val= LIST_NOT_USED&0xFF;
  3997. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
  3998. }
  3999. for(list=0; list<h->list_count; list++){
  4000. unsigned int val;
  4001. if(IS_DIR(mb_type, 0, list)){
  4002. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
  4003. mx += get_se_golomb(&s->gb);
  4004. my += get_se_golomb(&s->gb);
  4005. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4006. val= pack16to32(mx,my);
  4007. }else
  4008. val=0;
  4009. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, val, 4);
  4010. }
  4011. }
  4012. else if(IS_16X8(mb_type)){
  4013. for(list=0; list<h->list_count; list++){
  4014. for(i=0; i<2; i++){
  4015. unsigned int val;
  4016. if(IS_DIR(mb_type, i, list)){
  4017. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4018. if(val >= h->ref_count[list]){
  4019. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4020. return -1;
  4021. }
  4022. }else
  4023. val= LIST_NOT_USED&0xFF;
  4024. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
  4025. }
  4026. }
  4027. for(list=0; list<h->list_count; list++){
  4028. for(i=0; i<2; i++){
  4029. unsigned int val;
  4030. if(IS_DIR(mb_type, i, list)){
  4031. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
  4032. mx += get_se_golomb(&s->gb);
  4033. my += get_se_golomb(&s->gb);
  4034. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4035. val= pack16to32(mx,my);
  4036. }else
  4037. val=0;
  4038. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
  4039. }
  4040. }
  4041. }else{
  4042. assert(IS_8X16(mb_type));
  4043. for(list=0; list<h->list_count; list++){
  4044. for(i=0; i<2; i++){
  4045. unsigned int val;
  4046. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  4047. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4048. if(val >= h->ref_count[list]){
  4049. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4050. return -1;
  4051. }
  4052. }else
  4053. val= LIST_NOT_USED&0xFF;
  4054. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
  4055. }
  4056. }
  4057. for(list=0; list<h->list_count; list++){
  4058. for(i=0; i<2; i++){
  4059. unsigned int val;
  4060. if(IS_DIR(mb_type, i, list)){
  4061. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
  4062. mx += get_se_golomb(&s->gb);
  4063. my += get_se_golomb(&s->gb);
  4064. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4065. val= pack16to32(mx,my);
  4066. }else
  4067. val=0;
  4068. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
  4069. }
  4070. }
  4071. }
  4072. }
  4073. if(IS_INTER(mb_type))
  4074. write_back_motion(h, mb_type);
  4075. if(!IS_INTRA16x16(mb_type)){
  4076. cbp= get_ue_golomb(&s->gb);
  4077. if(cbp > 47){
  4078. av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, s->mb_x, s->mb_y);
  4079. return -1;
  4080. }
  4081. if(CHROMA){
  4082. if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp[cbp];
  4083. else cbp= golomb_to_inter_cbp [cbp];
  4084. }else{
  4085. if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp_gray[cbp];
  4086. else cbp= golomb_to_inter_cbp_gray[cbp];
  4087. }
  4088. }
  4089. h->cbp = cbp;
  4090. if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
  4091. if(get_bits1(&s->gb)){
  4092. mb_type |= MB_TYPE_8x8DCT;
  4093. h->cbp_table[mb_xy]= cbp;
  4094. }
  4095. }
  4096. s->current_picture.mb_type[mb_xy]= mb_type;
  4097. if(cbp || IS_INTRA16x16(mb_type)){
  4098. int i8x8, i4x4, chroma_idx;
  4099. int dquant;
  4100. GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
  4101. const uint8_t *scan, *scan8x8, *dc_scan;
  4102. // fill_non_zero_count_cache(h);
  4103. if(IS_INTERLACED(mb_type)){
  4104. scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
  4105. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  4106. dc_scan= luma_dc_field_scan;
  4107. }else{
  4108. scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
  4109. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  4110. dc_scan= luma_dc_zigzag_scan;
  4111. }
  4112. dquant= get_se_golomb(&s->gb);
  4113. if( dquant > 25 || dquant < -26 ){
  4114. av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);
  4115. return -1;
  4116. }
  4117. s->qscale += dquant;
  4118. if(((unsigned)s->qscale) > 51){
  4119. if(s->qscale<0) s->qscale+= 52;
  4120. else s->qscale-= 52;
  4121. }
  4122. h->chroma_qp[0]= get_chroma_qp(h, 0, s->qscale);
  4123. h->chroma_qp[1]= get_chroma_qp(h, 1, s->qscale);
  4124. if(IS_INTRA16x16(mb_type)){
  4125. if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
  4126. return -1; //FIXME continue if partitioned and other return -1 too
  4127. }
  4128. assert((cbp&15) == 0 || (cbp&15) == 15);
  4129. if(cbp&15){
  4130. for(i8x8=0; i8x8<4; i8x8++){
  4131. for(i4x4=0; i4x4<4; i4x4++){
  4132. const int index= i4x4 + 4*i8x8;
  4133. if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, h->dequant4_coeff[0][s->qscale], 15) < 0 ){
  4134. return -1;
  4135. }
  4136. }
  4137. }
  4138. }else{
  4139. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  4140. }
  4141. }else{
  4142. for(i8x8=0; i8x8<4; i8x8++){
  4143. if(cbp & (1<<i8x8)){
  4144. if(IS_8x8DCT(mb_type)){
  4145. DCTELEM *buf = &h->mb[64*i8x8];
  4146. uint8_t *nnz;
  4147. for(i4x4=0; i4x4<4; i4x4++){
  4148. if( decode_residual(h, gb, buf, i4x4+4*i8x8, scan8x8+16*i4x4,
  4149. h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 16) <0 )
  4150. return -1;
  4151. }
  4152. nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4153. nnz[0] += nnz[1] + nnz[8] + nnz[9];
  4154. }else{
  4155. for(i4x4=0; i4x4<4; i4x4++){
  4156. const int index= i4x4 + 4*i8x8;
  4157. if( decode_residual(h, gb, h->mb + 16*index, index, scan, h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale], 16) <0 ){
  4158. return -1;
  4159. }
  4160. }
  4161. }
  4162. }else{
  4163. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4164. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  4165. }
  4166. }
  4167. }
  4168. if(cbp&0x30){
  4169. for(chroma_idx=0; chroma_idx<2; chroma_idx++)
  4170. if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){
  4171. return -1;
  4172. }
  4173. }
  4174. if(cbp&0x20){
  4175. for(chroma_idx=0; chroma_idx<2; chroma_idx++){
  4176. const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[chroma_idx]];
  4177. for(i4x4=0; i4x4<4; i4x4++){
  4178. const int index= 16 + 4*chroma_idx + i4x4;
  4179. if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, qmul, 15) < 0){
  4180. return -1;
  4181. }
  4182. }
  4183. }
  4184. }else{
  4185. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4186. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4187. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4188. }
  4189. }else{
  4190. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4191. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  4192. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4193. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4194. }
  4195. s->current_picture.qscale_table[mb_xy]= s->qscale;
  4196. write_back_non_zero_count(h);
  4197. if(MB_MBAFF){
  4198. h->ref_count[0] >>= 1;
  4199. h->ref_count[1] >>= 1;
  4200. }
  4201. return 0;
  4202. }
  4203. static int decode_cabac_field_decoding_flag(H264Context *h) {
  4204. MpegEncContext * const s = &h->s;
  4205. const int mb_x = s->mb_x;
  4206. const int mb_y = s->mb_y & ~1;
  4207. const int mba_xy = mb_x - 1 + mb_y *s->mb_stride;
  4208. const int mbb_xy = mb_x + (mb_y-2)*s->mb_stride;
  4209. unsigned int ctx = 0;
  4210. if( h->slice_table[mba_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) ) {
  4211. ctx += 1;
  4212. }
  4213. if( h->slice_table[mbb_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) ) {
  4214. ctx += 1;
  4215. }
  4216. return get_cabac_noinline( &h->cabac, &h->cabac_state[70 + ctx] );
  4217. }
  4218. static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {
  4219. uint8_t *state= &h->cabac_state[ctx_base];
  4220. int mb_type;
  4221. if(intra_slice){
  4222. MpegEncContext * const s = &h->s;
  4223. const int mba_xy = h->left_mb_xy[0];
  4224. const int mbb_xy = h->top_mb_xy;
  4225. int ctx=0;
  4226. if( h->slice_table[mba_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mba_xy] ) )
  4227. ctx++;
  4228. if( h->slice_table[mbb_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mbb_xy] ) )
  4229. ctx++;
  4230. if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )
  4231. return 0; /* I4x4 */
  4232. state += 2;
  4233. }else{
  4234. if( get_cabac_noinline( &h->cabac, &state[0] ) == 0 )
  4235. return 0; /* I4x4 */
  4236. }
  4237. if( get_cabac_terminate( &h->cabac ) )
  4238. return 25; /* PCM */
  4239. mb_type = 1; /* I16x16 */
  4240. mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */
  4241. if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */
  4242. mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );
  4243. mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );
  4244. mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );
  4245. return mb_type;
  4246. }
  4247. static int decode_cabac_mb_type( H264Context *h ) {
  4248. MpegEncContext * const s = &h->s;
  4249. if( h->slice_type_nos == FF_I_TYPE ) {
  4250. return decode_cabac_intra_mb_type(h, 3, 1);
  4251. } else if( h->slice_type_nos == FF_P_TYPE ) {
  4252. if( get_cabac_noinline( &h->cabac, &h->cabac_state[14] ) == 0 ) {
  4253. /* P-type */
  4254. if( get_cabac_noinline( &h->cabac, &h->cabac_state[15] ) == 0 ) {
  4255. /* P_L0_D16x16, P_8x8 */
  4256. return 3 * get_cabac_noinline( &h->cabac, &h->cabac_state[16] );
  4257. } else {
  4258. /* P_L0_D8x16, P_L0_D16x8 */
  4259. return 2 - get_cabac_noinline( &h->cabac, &h->cabac_state[17] );
  4260. }
  4261. } else {
  4262. return decode_cabac_intra_mb_type(h, 17, 0) + 5;
  4263. }
  4264. } else if( h->slice_type_nos == FF_B_TYPE ) {
  4265. const int mba_xy = h->left_mb_xy[0];
  4266. const int mbb_xy = h->top_mb_xy;
  4267. int ctx = 0;
  4268. int bits;
  4269. if( h->slice_table[mba_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mba_xy] ) )
  4270. ctx++;
  4271. if( h->slice_table[mbb_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mbb_xy] ) )
  4272. ctx++;
  4273. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+ctx] ) )
  4274. return 0; /* B_Direct_16x16 */
  4275. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+3] ) ) {
  4276. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ); /* B_L[01]_16x16 */
  4277. }
  4278. bits = get_cabac_noinline( &h->cabac, &h->cabac_state[27+4] ) << 3;
  4279. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 2;
  4280. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 1;
  4281. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4282. if( bits < 8 )
  4283. return bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */
  4284. else if( bits == 13 ) {
  4285. return decode_cabac_intra_mb_type(h, 32, 0) + 23;
  4286. } else if( bits == 14 )
  4287. return 11; /* B_L1_L0_8x16 */
  4288. else if( bits == 15 )
  4289. return 22; /* B_8x8 */
  4290. bits= ( bits<<1 ) | get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4291. return bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */
  4292. } else {
  4293. /* TODO SI/SP frames? */
  4294. return -1;
  4295. }
  4296. }
  4297. static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {
  4298. MpegEncContext * const s = &h->s;
  4299. int mba_xy, mbb_xy;
  4300. int ctx = 0;
  4301. if(FRAME_MBAFF){ //FIXME merge with the stuff in fill_caches?
  4302. int mb_xy = mb_x + (mb_y&~1)*s->mb_stride;
  4303. mba_xy = mb_xy - 1;
  4304. if( (mb_y&1)
  4305. && h->slice_table[mba_xy] == h->slice_num
  4306. && MB_FIELD == !!IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) )
  4307. mba_xy += s->mb_stride;
  4308. if( MB_FIELD ){
  4309. mbb_xy = mb_xy - s->mb_stride;
  4310. if( !(mb_y&1)
  4311. && h->slice_table[mbb_xy] == h->slice_num
  4312. && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) )
  4313. mbb_xy -= s->mb_stride;
  4314. }else
  4315. mbb_xy = mb_x + (mb_y-1)*s->mb_stride;
  4316. }else{
  4317. int mb_xy = h->mb_xy;
  4318. mba_xy = mb_xy - 1;
  4319. mbb_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
  4320. }
  4321. if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mba_xy] ))
  4322. ctx++;
  4323. if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mbb_xy] ))
  4324. ctx++;
  4325. if( h->slice_type_nos == FF_B_TYPE )
  4326. ctx += 13;
  4327. return get_cabac_noinline( &h->cabac, &h->cabac_state[11+ctx] );
  4328. }
  4329. static int decode_cabac_mb_intra4x4_pred_mode( H264Context *h, int pred_mode ) {
  4330. int mode = 0;
  4331. if( get_cabac( &h->cabac, &h->cabac_state[68] ) )
  4332. return pred_mode;
  4333. mode += 1 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4334. mode += 2 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4335. mode += 4 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4336. if( mode >= pred_mode )
  4337. return mode + 1;
  4338. else
  4339. return mode;
  4340. }
  4341. static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {
  4342. const int mba_xy = h->left_mb_xy[0];
  4343. const int mbb_xy = h->top_mb_xy;
  4344. int ctx = 0;
  4345. /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */
  4346. if( h->slice_table[mba_xy] == h->slice_num && h->chroma_pred_mode_table[mba_xy] != 0 )
  4347. ctx++;
  4348. if( h->slice_table[mbb_xy] == h->slice_num && h->chroma_pred_mode_table[mbb_xy] != 0 )
  4349. ctx++;
  4350. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )
  4351. return 0;
  4352. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4353. return 1;
  4354. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4355. return 2;
  4356. else
  4357. return 3;
  4358. }
  4359. static int decode_cabac_mb_cbp_luma( H264Context *h) {
  4360. int cbp_b, cbp_a, ctx, cbp = 0;
  4361. cbp_a = h->slice_table[h->left_mb_xy[0]] == h->slice_num ? h->left_cbp : -1;
  4362. cbp_b = h->slice_table[h->top_mb_xy] == h->slice_num ? h->top_cbp : -1;
  4363. ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);
  4364. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);
  4365. ctx = !(cbp & 0x01) + 2 * !(cbp_b & 0x08);
  4366. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;
  4367. ctx = !(cbp_a & 0x08) + 2 * !(cbp & 0x01);
  4368. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;
  4369. ctx = !(cbp & 0x04) + 2 * !(cbp & 0x02);
  4370. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;
  4371. return cbp;
  4372. }
  4373. static int decode_cabac_mb_cbp_chroma( H264Context *h) {
  4374. int ctx;
  4375. int cbp_a, cbp_b;
  4376. cbp_a = (h->left_cbp>>4)&0x03;
  4377. cbp_b = (h-> top_cbp>>4)&0x03;
  4378. ctx = 0;
  4379. if( cbp_a > 0 ) ctx++;
  4380. if( cbp_b > 0 ) ctx += 2;
  4381. if( get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] ) == 0 )
  4382. return 0;
  4383. ctx = 4;
  4384. if( cbp_a == 2 ) ctx++;
  4385. if( cbp_b == 2 ) ctx += 2;
  4386. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] );
  4387. }
  4388. static int decode_cabac_mb_dqp( H264Context *h) {
  4389. int ctx = 0;
  4390. int val = 0;
  4391. if( h->last_qscale_diff != 0 )
  4392. ctx++;
  4393. while( get_cabac_noinline( &h->cabac, &h->cabac_state[60 + ctx] ) ) {
  4394. if( ctx < 2 )
  4395. ctx = 2;
  4396. else
  4397. ctx = 3;
  4398. val++;
  4399. if(val > 102) //prevent infinite loop
  4400. return INT_MIN;
  4401. }
  4402. if( val&0x01 )
  4403. return (val + 1)/2;
  4404. else
  4405. return -(val + 1)/2;
  4406. }
  4407. static int decode_cabac_p_mb_sub_type( H264Context *h ) {
  4408. if( get_cabac( &h->cabac, &h->cabac_state[21] ) )
  4409. return 0; /* 8x8 */
  4410. if( !get_cabac( &h->cabac, &h->cabac_state[22] ) )
  4411. return 1; /* 8x4 */
  4412. if( get_cabac( &h->cabac, &h->cabac_state[23] ) )
  4413. return 2; /* 4x8 */
  4414. return 3; /* 4x4 */
  4415. }
  4416. static int decode_cabac_b_mb_sub_type( H264Context *h ) {
  4417. int type;
  4418. if( !get_cabac( &h->cabac, &h->cabac_state[36] ) )
  4419. return 0; /* B_Direct_8x8 */
  4420. if( !get_cabac( &h->cabac, &h->cabac_state[37] ) )
  4421. return 1 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */
  4422. type = 3;
  4423. if( get_cabac( &h->cabac, &h->cabac_state[38] ) ) {
  4424. if( get_cabac( &h->cabac, &h->cabac_state[39] ) )
  4425. return 11 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */
  4426. type += 4;
  4427. }
  4428. type += 2*get_cabac( &h->cabac, &h->cabac_state[39] );
  4429. type += get_cabac( &h->cabac, &h->cabac_state[39] );
  4430. return type;
  4431. }
  4432. static inline int decode_cabac_mb_transform_size( H264Context *h ) {
  4433. return get_cabac_noinline( &h->cabac, &h->cabac_state[399 + h->neighbor_transform_size] );
  4434. }
  4435. static int decode_cabac_mb_ref( H264Context *h, int list, int n ) {
  4436. int refa = h->ref_cache[list][scan8[n] - 1];
  4437. int refb = h->ref_cache[list][scan8[n] - 8];
  4438. int ref = 0;
  4439. int ctx = 0;
  4440. if( h->slice_type_nos == FF_B_TYPE) {
  4441. if( refa > 0 && !h->direct_cache[scan8[n] - 1] )
  4442. ctx++;
  4443. if( refb > 0 && !h->direct_cache[scan8[n] - 8] )
  4444. ctx += 2;
  4445. } else {
  4446. if( refa > 0 )
  4447. ctx++;
  4448. if( refb > 0 )
  4449. ctx += 2;
  4450. }
  4451. while( get_cabac( &h->cabac, &h->cabac_state[54+ctx] ) ) {
  4452. ref++;
  4453. if( ctx < 4 )
  4454. ctx = 4;
  4455. else
  4456. ctx = 5;
  4457. if(ref >= 32 /*h->ref_list[list]*/){
  4458. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_ref\n");
  4459. return 0; //FIXME we should return -1 and check the return everywhere
  4460. }
  4461. }
  4462. return ref;
  4463. }
  4464. static int decode_cabac_mb_mvd( H264Context *h, int list, int n, int l ) {
  4465. int amvd = abs( h->mvd_cache[list][scan8[n] - 1][l] ) +
  4466. abs( h->mvd_cache[list][scan8[n] - 8][l] );
  4467. int ctxbase = (l == 0) ? 40 : 47;
  4468. int ctx, mvd;
  4469. if( amvd < 3 )
  4470. ctx = 0;
  4471. else if( amvd > 32 )
  4472. ctx = 2;
  4473. else
  4474. ctx = 1;
  4475. if(!get_cabac(&h->cabac, &h->cabac_state[ctxbase+ctx]))
  4476. return 0;
  4477. mvd= 1;
  4478. ctx= 3;
  4479. while( mvd < 9 && get_cabac( &h->cabac, &h->cabac_state[ctxbase+ctx] ) ) {
  4480. mvd++;
  4481. if( ctx < 6 )
  4482. ctx++;
  4483. }
  4484. if( mvd >= 9 ) {
  4485. int k = 3;
  4486. while( get_cabac_bypass( &h->cabac ) ) {
  4487. mvd += 1 << k;
  4488. k++;
  4489. if(k>24){
  4490. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n");
  4491. return INT_MIN;
  4492. }
  4493. }
  4494. while( k-- ) {
  4495. if( get_cabac_bypass( &h->cabac ) )
  4496. mvd += 1 << k;
  4497. }
  4498. }
  4499. return get_cabac_bypass_sign( &h->cabac, -mvd );
  4500. }
  4501. static av_always_inline int get_cabac_cbf_ctx( H264Context *h, int cat, int idx, int is_dc ) {
  4502. int nza, nzb;
  4503. int ctx = 0;
  4504. if( is_dc ) {
  4505. if( cat == 0 ) {
  4506. nza = h->left_cbp&0x100;
  4507. nzb = h-> top_cbp&0x100;
  4508. } else {
  4509. nza = (h->left_cbp>>(6+idx))&0x01;
  4510. nzb = (h-> top_cbp>>(6+idx))&0x01;
  4511. }
  4512. } else {
  4513. if( cat == 4 ) {
  4514. nza = h->non_zero_count_cache[scan8[16+idx] - 1];
  4515. nzb = h->non_zero_count_cache[scan8[16+idx] - 8];
  4516. } else {
  4517. assert(cat == 1 || cat == 2);
  4518. nza = h->non_zero_count_cache[scan8[idx] - 1];
  4519. nzb = h->non_zero_count_cache[scan8[idx] - 8];
  4520. }
  4521. }
  4522. if( nza > 0 )
  4523. ctx++;
  4524. if( nzb > 0 )
  4525. ctx += 2;
  4526. return ctx + 4 * cat;
  4527. }
  4528. DECLARE_ASM_CONST(1, uint8_t, last_coeff_flag_offset_8x8[63]) = {
  4529. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  4530. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  4531. 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  4532. 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8
  4533. };
  4534. 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 ) {
  4535. static const int significant_coeff_flag_offset[2][6] = {
  4536. { 105+0, 105+15, 105+29, 105+44, 105+47, 402 },
  4537. { 277+0, 277+15, 277+29, 277+44, 277+47, 436 }
  4538. };
  4539. static const int last_coeff_flag_offset[2][6] = {
  4540. { 166+0, 166+15, 166+29, 166+44, 166+47, 417 },
  4541. { 338+0, 338+15, 338+29, 338+44, 338+47, 451 }
  4542. };
  4543. static const int coeff_abs_level_m1_offset[6] = {
  4544. 227+0, 227+10, 227+20, 227+30, 227+39, 426
  4545. };
  4546. static const uint8_t significant_coeff_flag_offset_8x8[2][63] = {
  4547. { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5,
  4548. 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9,10, 9, 8, 7,
  4549. 7, 6,11,12,13,11, 6, 7, 8, 9,14,10, 9, 8, 6,11,
  4550. 12,13,11, 6, 9,14,10, 9,11,12,13,11,14,10,12 },
  4551. { 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5,
  4552. 6, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11,
  4553. 9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,13,13, 9,
  4554. 9,10,10, 8,13,13, 9, 9,10,10,14,14,14,14,14 }
  4555. };
  4556. /* node ctx: 0..3: abslevel1 (with abslevelgt1 == 0).
  4557. * 4..7: abslevelgt1 + 3 (and abslevel1 doesn't matter).
  4558. * map node ctx => cabac ctx for level=1 */
  4559. static const uint8_t coeff_abs_level1_ctx[8] = { 1, 2, 3, 4, 0, 0, 0, 0 };
  4560. /* map node ctx => cabac ctx for level>1 */
  4561. static const uint8_t coeff_abs_levelgt1_ctx[8] = { 5, 5, 5, 5, 6, 7, 8, 9 };
  4562. static const uint8_t coeff_abs_level_transition[2][8] = {
  4563. /* update node ctx after decoding a level=1 */
  4564. { 1, 2, 3, 3, 4, 5, 6, 7 },
  4565. /* update node ctx after decoding a level>1 */
  4566. { 4, 4, 4, 4, 5, 6, 7, 7 }
  4567. };
  4568. int index[64];
  4569. int av_unused last;
  4570. int coeff_count = 0;
  4571. int node_ctx = 0;
  4572. uint8_t *significant_coeff_ctx_base;
  4573. uint8_t *last_coeff_ctx_base;
  4574. uint8_t *abs_level_m1_ctx_base;
  4575. #ifndef ARCH_X86
  4576. #define CABAC_ON_STACK
  4577. #endif
  4578. #ifdef CABAC_ON_STACK
  4579. #define CC &cc
  4580. CABACContext cc;
  4581. cc.range = h->cabac.range;
  4582. cc.low = h->cabac.low;
  4583. cc.bytestream= h->cabac.bytestream;
  4584. #else
  4585. #define CC &h->cabac
  4586. #endif
  4587. /* cat: 0-> DC 16x16 n = 0
  4588. * 1-> AC 16x16 n = luma4x4idx
  4589. * 2-> Luma4x4 n = luma4x4idx
  4590. * 3-> DC Chroma n = iCbCr
  4591. * 4-> AC Chroma n = 4 * iCbCr + chroma4x4idx
  4592. * 5-> Luma8x8 n = 4 * luma8x8idx
  4593. */
  4594. /* read coded block flag */
  4595. if( is_dc || cat != 5 ) {
  4596. if( get_cabac( CC, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n, is_dc ) ] ) == 0 ) {
  4597. if( !is_dc ) {
  4598. if( cat == 4 )
  4599. h->non_zero_count_cache[scan8[16+n]] = 0;
  4600. else
  4601. h->non_zero_count_cache[scan8[n]] = 0;
  4602. }
  4603. #ifdef CABAC_ON_STACK
  4604. h->cabac.range = cc.range ;
  4605. h->cabac.low = cc.low ;
  4606. h->cabac.bytestream= cc.bytestream;
  4607. #endif
  4608. return;
  4609. }
  4610. }
  4611. significant_coeff_ctx_base = h->cabac_state
  4612. + significant_coeff_flag_offset[MB_FIELD][cat];
  4613. last_coeff_ctx_base = h->cabac_state
  4614. + last_coeff_flag_offset[MB_FIELD][cat];
  4615. abs_level_m1_ctx_base = h->cabac_state
  4616. + coeff_abs_level_m1_offset[cat];
  4617. if( !is_dc && cat == 5 ) {
  4618. #define DECODE_SIGNIFICANCE( coefs, sig_off, last_off ) \
  4619. for(last= 0; last < coefs; last++) { \
  4620. uint8_t *sig_ctx = significant_coeff_ctx_base + sig_off; \
  4621. if( get_cabac( CC, sig_ctx )) { \
  4622. uint8_t *last_ctx = last_coeff_ctx_base + last_off; \
  4623. index[coeff_count++] = last; \
  4624. if( get_cabac( CC, last_ctx ) ) { \
  4625. last= max_coeff; \
  4626. break; \
  4627. } \
  4628. } \
  4629. }\
  4630. if( last == max_coeff -1 ) {\
  4631. index[coeff_count++] = last;\
  4632. }
  4633. const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD];
  4634. #if defined(ARCH_X86) && defined(HAVE_7REGS) && defined(HAVE_EBX_AVAILABLE) && !defined(BROKEN_RELOCATIONS)
  4635. coeff_count= decode_significance_8x8_x86(CC, significant_coeff_ctx_base, index, sig_off);
  4636. } else {
  4637. coeff_count= decode_significance_x86(CC, max_coeff, significant_coeff_ctx_base, index);
  4638. #else
  4639. DECODE_SIGNIFICANCE( 63, sig_off[last], last_coeff_flag_offset_8x8[last] );
  4640. } else {
  4641. DECODE_SIGNIFICANCE( max_coeff - 1, last, last );
  4642. #endif
  4643. }
  4644. assert(coeff_count > 0);
  4645. if( is_dc ) {
  4646. if( cat == 0 )
  4647. h->cbp_table[h->mb_xy] |= 0x100;
  4648. else
  4649. h->cbp_table[h->mb_xy] |= 0x40 << n;
  4650. } else {
  4651. if( cat == 5 )
  4652. fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
  4653. else if( cat == 4 )
  4654. h->non_zero_count_cache[scan8[16+n]] = coeff_count;
  4655. else {
  4656. assert( cat == 1 || cat == 2 );
  4657. h->non_zero_count_cache[scan8[n]] = coeff_count;
  4658. }
  4659. }
  4660. do {
  4661. uint8_t *ctx = coeff_abs_level1_ctx[node_ctx] + abs_level_m1_ctx_base;
  4662. int j= scantable[index[--coeff_count]];
  4663. if( get_cabac( CC, ctx ) == 0 ) {
  4664. node_ctx = coeff_abs_level_transition[0][node_ctx];
  4665. if( is_dc ) {
  4666. block[j] = get_cabac_bypass_sign( CC, -1);
  4667. }else{
  4668. block[j] = (get_cabac_bypass_sign( CC, -qmul[j]) + 32) >> 6;
  4669. }
  4670. } else {
  4671. int coeff_abs = 2;
  4672. ctx = coeff_abs_levelgt1_ctx[node_ctx] + abs_level_m1_ctx_base;
  4673. node_ctx = coeff_abs_level_transition[1][node_ctx];
  4674. while( coeff_abs < 15 && get_cabac( CC, ctx ) ) {
  4675. coeff_abs++;
  4676. }
  4677. if( coeff_abs >= 15 ) {
  4678. int j = 0;
  4679. while( get_cabac_bypass( CC ) ) {
  4680. j++;
  4681. }
  4682. coeff_abs=1;
  4683. while( j-- ) {
  4684. coeff_abs += coeff_abs + get_cabac_bypass( CC );
  4685. }
  4686. coeff_abs+= 14;
  4687. }
  4688. if( is_dc ) {
  4689. block[j] = get_cabac_bypass_sign( CC, -coeff_abs );
  4690. }else{
  4691. block[j] = (get_cabac_bypass_sign( CC, -coeff_abs ) * qmul[j] + 32) >> 6;
  4692. }
  4693. }
  4694. } while( coeff_count );
  4695. #ifdef CABAC_ON_STACK
  4696. h->cabac.range = cc.range ;
  4697. h->cabac.low = cc.low ;
  4698. h->cabac.bytestream= cc.bytestream;
  4699. #endif
  4700. }
  4701. #ifndef CONFIG_SMALL
  4702. 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 ) {
  4703. decode_cabac_residual_internal(h, block, cat, n, scantable, qmul, max_coeff, 1);
  4704. }
  4705. 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 ) {
  4706. decode_cabac_residual_internal(h, block, cat, n, scantable, qmul, max_coeff, 0);
  4707. }
  4708. #endif
  4709. static void decode_cabac_residual( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff ) {
  4710. #ifdef CONFIG_SMALL
  4711. decode_cabac_residual_internal(h, block, cat, n, scantable, qmul, max_coeff, cat == 0 || cat == 3);
  4712. #else
  4713. if( cat == 0 || cat == 3 ) decode_cabac_residual_dc(h, block, cat, n, scantable, qmul, max_coeff);
  4714. else decode_cabac_residual_nondc(h, block, cat, n, scantable, qmul, max_coeff);
  4715. #endif
  4716. }
  4717. static inline void compute_mb_neighbors(H264Context *h)
  4718. {
  4719. MpegEncContext * const s = &h->s;
  4720. const int mb_xy = h->mb_xy;
  4721. h->top_mb_xy = mb_xy - s->mb_stride;
  4722. h->left_mb_xy[0] = mb_xy - 1;
  4723. if(FRAME_MBAFF){
  4724. const int pair_xy = s->mb_x + (s->mb_y & ~1)*s->mb_stride;
  4725. const int top_pair_xy = pair_xy - s->mb_stride;
  4726. const int top_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
  4727. const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
  4728. const int curr_mb_frame_flag = !MB_FIELD;
  4729. const int bottom = (s->mb_y & 1);
  4730. if (bottom
  4731. ? !curr_mb_frame_flag // bottom macroblock
  4732. : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
  4733. ) {
  4734. h->top_mb_xy -= s->mb_stride;
  4735. }
  4736. if (left_mb_frame_flag != curr_mb_frame_flag) {
  4737. h->left_mb_xy[0] = pair_xy - 1;
  4738. }
  4739. } else if (FIELD_PICTURE) {
  4740. h->top_mb_xy -= s->mb_stride;
  4741. }
  4742. return;
  4743. }
  4744. /**
  4745. * decodes a macroblock
  4746. * @returns 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  4747. */
  4748. static int decode_mb_cabac(H264Context *h) {
  4749. MpegEncContext * const s = &h->s;
  4750. int mb_xy;
  4751. int mb_type, partition_count, cbp = 0;
  4752. int dct8x8_allowed= h->pps.transform_8x8_mode;
  4753. mb_xy = h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  4754. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?)
  4755. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  4756. if( h->slice_type_nos != FF_I_TYPE ) {
  4757. int skip;
  4758. /* a skipped mb needs the aff flag from the following mb */
  4759. if( FRAME_MBAFF && s->mb_x==0 && (s->mb_y&1)==0 )
  4760. predict_field_decoding_flag(h);
  4761. if( FRAME_MBAFF && (s->mb_y&1)==1 && h->prev_mb_skipped )
  4762. skip = h->next_mb_skipped;
  4763. else
  4764. skip = decode_cabac_mb_skip( h, s->mb_x, s->mb_y );
  4765. /* read skip flags */
  4766. if( skip ) {
  4767. if( FRAME_MBAFF && (s->mb_y&1)==0 ){
  4768. s->current_picture.mb_type[mb_xy] = MB_TYPE_SKIP;
  4769. h->next_mb_skipped = decode_cabac_mb_skip( h, s->mb_x, s->mb_y+1 );
  4770. if(h->next_mb_skipped)
  4771. predict_field_decoding_flag(h);
  4772. else
  4773. h->mb_mbaff = h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4774. }
  4775. decode_mb_skip(h);
  4776. h->cbp_table[mb_xy] = 0;
  4777. h->chroma_pred_mode_table[mb_xy] = 0;
  4778. h->last_qscale_diff = 0;
  4779. return 0;
  4780. }
  4781. }
  4782. if(FRAME_MBAFF){
  4783. if( (s->mb_y&1) == 0 )
  4784. h->mb_mbaff =
  4785. h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4786. }
  4787. h->prev_mb_skipped = 0;
  4788. compute_mb_neighbors(h);
  4789. if( ( mb_type = decode_cabac_mb_type( h ) ) < 0 ) {
  4790. av_log( h->s.avctx, AV_LOG_ERROR, "decode_cabac_mb_type failed\n" );
  4791. return -1;
  4792. }
  4793. if( h->slice_type_nos == FF_B_TYPE ) {
  4794. if( mb_type < 23 ){
  4795. partition_count= b_mb_type_info[mb_type].partition_count;
  4796. mb_type= b_mb_type_info[mb_type].type;
  4797. }else{
  4798. mb_type -= 23;
  4799. goto decode_intra_mb;
  4800. }
  4801. } else if( h->slice_type_nos == FF_P_TYPE ) {
  4802. if( mb_type < 5) {
  4803. partition_count= p_mb_type_info[mb_type].partition_count;
  4804. mb_type= p_mb_type_info[mb_type].type;
  4805. } else {
  4806. mb_type -= 5;
  4807. goto decode_intra_mb;
  4808. }
  4809. } else {
  4810. if(h->slice_type == FF_SI_TYPE && mb_type)
  4811. mb_type--;
  4812. assert(h->slice_type_nos == FF_I_TYPE);
  4813. decode_intra_mb:
  4814. partition_count = 0;
  4815. cbp= i_mb_type_info[mb_type].cbp;
  4816. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  4817. mb_type= i_mb_type_info[mb_type].type;
  4818. }
  4819. if(MB_FIELD)
  4820. mb_type |= MB_TYPE_INTERLACED;
  4821. h->slice_table[ mb_xy ]= h->slice_num;
  4822. if(IS_INTRA_PCM(mb_type)) {
  4823. const uint8_t *ptr;
  4824. // We assume these blocks are very rare so we do not optimize it.
  4825. // FIXME The two following lines get the bitstream position in the cabac
  4826. // decode, I think it should be done by a function in cabac.h (or cabac.c).
  4827. ptr= h->cabac.bytestream;
  4828. if(h->cabac.low&0x1) ptr--;
  4829. if(CABAC_BITS==16){
  4830. if(h->cabac.low&0x1FF) ptr--;
  4831. }
  4832. // The pixels are stored in the same order as levels in h->mb array.
  4833. memcpy(h->mb, ptr, 256); ptr+=256;
  4834. if(CHROMA){
  4835. memcpy(h->mb+128, ptr, 128); ptr+=128;
  4836. }
  4837. ff_init_cabac_decoder(&h->cabac, ptr, h->cabac.bytestream_end - ptr);
  4838. // All blocks are present
  4839. h->cbp_table[mb_xy] = 0x1ef;
  4840. h->chroma_pred_mode_table[mb_xy] = 0;
  4841. // In deblocking, the quantizer is 0
  4842. s->current_picture.qscale_table[mb_xy]= 0;
  4843. // All coeffs are present
  4844. memset(h->non_zero_count[mb_xy], 16, 16);
  4845. s->current_picture.mb_type[mb_xy]= mb_type;
  4846. h->last_qscale_diff = 0;
  4847. return 0;
  4848. }
  4849. if(MB_MBAFF){
  4850. h->ref_count[0] <<= 1;
  4851. h->ref_count[1] <<= 1;
  4852. }
  4853. fill_caches(h, mb_type, 0);
  4854. if( IS_INTRA( mb_type ) ) {
  4855. int i, pred_mode;
  4856. if( IS_INTRA4x4( mb_type ) ) {
  4857. if( dct8x8_allowed && decode_cabac_mb_transform_size( h ) ) {
  4858. mb_type |= MB_TYPE_8x8DCT;
  4859. for( i = 0; i < 16; i+=4 ) {
  4860. int pred = pred_intra_mode( h, i );
  4861. int mode = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  4862. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  4863. }
  4864. } else {
  4865. for( i = 0; i < 16; i++ ) {
  4866. int pred = pred_intra_mode( h, i );
  4867. h->intra4x4_pred_mode_cache[ scan8[i] ] = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  4868. //av_log( s->avctx, AV_LOG_ERROR, "i4x4 pred=%d mode=%d\n", pred, h->intra4x4_pred_mode_cache[ scan8[i] ] );
  4869. }
  4870. }
  4871. write_back_intra_pred_mode(h);
  4872. if( check_intra4x4_pred_mode(h) < 0 ) return -1;
  4873. } else {
  4874. h->intra16x16_pred_mode= check_intra_pred_mode( h, h->intra16x16_pred_mode );
  4875. if( h->intra16x16_pred_mode < 0 ) return -1;
  4876. }
  4877. if(CHROMA){
  4878. h->chroma_pred_mode_table[mb_xy] =
  4879. pred_mode = decode_cabac_mb_chroma_pre_mode( h );
  4880. pred_mode= check_intra_pred_mode( h, pred_mode );
  4881. if( pred_mode < 0 ) return -1;
  4882. h->chroma_pred_mode= pred_mode;
  4883. }
  4884. } else if( partition_count == 4 ) {
  4885. int i, j, sub_partition_count[4], list, ref[2][4];
  4886. if( h->slice_type_nos == FF_B_TYPE ) {
  4887. for( i = 0; i < 4; i++ ) {
  4888. h->sub_mb_type[i] = decode_cabac_b_mb_sub_type( h );
  4889. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4890. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4891. }
  4892. if( IS_DIRECT(h->sub_mb_type[0] | h->sub_mb_type[1] |
  4893. h->sub_mb_type[2] | h->sub_mb_type[3]) ) {
  4894. pred_direct_motion(h, &mb_type);
  4895. h->ref_cache[0][scan8[4]] =
  4896. h->ref_cache[1][scan8[4]] =
  4897. h->ref_cache[0][scan8[12]] =
  4898. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  4899. if( h->ref_count[0] > 1 || h->ref_count[1] > 1 ) {
  4900. for( i = 0; i < 4; i++ )
  4901. if( IS_DIRECT(h->sub_mb_type[i]) )
  4902. fill_rectangle( &h->direct_cache[scan8[4*i]], 2, 2, 8, 1, 1 );
  4903. }
  4904. }
  4905. } else {
  4906. for( i = 0; i < 4; i++ ) {
  4907. h->sub_mb_type[i] = decode_cabac_p_mb_sub_type( h );
  4908. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4909. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4910. }
  4911. }
  4912. for( list = 0; list < h->list_count; list++ ) {
  4913. for( i = 0; i < 4; i++ ) {
  4914. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  4915. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4916. if( h->ref_count[list] > 1 )
  4917. ref[list][i] = decode_cabac_mb_ref( h, list, 4*i );
  4918. else
  4919. ref[list][i] = 0;
  4920. } else {
  4921. ref[list][i] = -1;
  4922. }
  4923. h->ref_cache[list][ scan8[4*i]+1 ]=
  4924. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  4925. }
  4926. }
  4927. if(dct8x8_allowed)
  4928. dct8x8_allowed = get_dct8x8_allowed(h);
  4929. for(list=0; list<h->list_count; list++){
  4930. for(i=0; i<4; i++){
  4931. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ];
  4932. if(IS_DIRECT(h->sub_mb_type[i])){
  4933. fill_rectangle(h->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 4);
  4934. continue;
  4935. }
  4936. if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
  4937. const int sub_mb_type= h->sub_mb_type[i];
  4938. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  4939. for(j=0; j<sub_partition_count[i]; j++){
  4940. int mpx, mpy;
  4941. int mx, my;
  4942. const int index= 4*i + block_width*j;
  4943. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  4944. int16_t (* mvd_cache)[2]= &h->mvd_cache[list][ scan8[index] ];
  4945. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mpx, &mpy);
  4946. mx = mpx + decode_cabac_mb_mvd( h, list, index, 0 );
  4947. my = mpy + decode_cabac_mb_mvd( h, list, index, 1 );
  4948. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4949. if(IS_SUB_8X8(sub_mb_type)){
  4950. mv_cache[ 1 ][0]=
  4951. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  4952. mv_cache[ 1 ][1]=
  4953. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  4954. mvd_cache[ 1 ][0]=
  4955. mvd_cache[ 8 ][0]= mvd_cache[ 9 ][0]= mx - mpx;
  4956. mvd_cache[ 1 ][1]=
  4957. mvd_cache[ 8 ][1]= mvd_cache[ 9 ][1]= my - mpy;
  4958. }else if(IS_SUB_8X4(sub_mb_type)){
  4959. mv_cache[ 1 ][0]= mx;
  4960. mv_cache[ 1 ][1]= my;
  4961. mvd_cache[ 1 ][0]= mx - mpx;
  4962. mvd_cache[ 1 ][1]= my - mpy;
  4963. }else if(IS_SUB_4X8(sub_mb_type)){
  4964. mv_cache[ 8 ][0]= mx;
  4965. mv_cache[ 8 ][1]= my;
  4966. mvd_cache[ 8 ][0]= mx - mpx;
  4967. mvd_cache[ 8 ][1]= my - mpy;
  4968. }
  4969. mv_cache[ 0 ][0]= mx;
  4970. mv_cache[ 0 ][1]= my;
  4971. mvd_cache[ 0 ][0]= mx - mpx;
  4972. mvd_cache[ 0 ][1]= my - mpy;
  4973. }
  4974. }else{
  4975. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  4976. uint32_t *pd= (uint32_t *)&h->mvd_cache[list][ scan8[4*i] ][0];
  4977. p[0] = p[1] = p[8] = p[9] = 0;
  4978. pd[0]= pd[1]= pd[8]= pd[9]= 0;
  4979. }
  4980. }
  4981. }
  4982. } else if( IS_DIRECT(mb_type) ) {
  4983. pred_direct_motion(h, &mb_type);
  4984. fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 4);
  4985. fill_rectangle(h->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 4);
  4986. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  4987. } else {
  4988. int list, mx, my, i, mpx, mpy;
  4989. if(IS_16X16(mb_type)){
  4990. for(list=0; list<h->list_count; list++){
  4991. if(IS_DIR(mb_type, 0, list)){
  4992. const int ref = h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 0 ) : 0;
  4993. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);
  4994. }else
  4995. 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
  4996. }
  4997. for(list=0; list<h->list_count; list++){
  4998. if(IS_DIR(mb_type, 0, list)){
  4999. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mpx, &mpy);
  5000. mx = mpx + decode_cabac_mb_mvd( h, list, 0, 0 );
  5001. my = mpy + decode_cabac_mb_mvd( h, list, 0, 1 );
  5002. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5003. fill_rectangle(h->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5004. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
  5005. }else
  5006. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, 0, 4);
  5007. }
  5008. }
  5009. else if(IS_16X8(mb_type)){
  5010. for(list=0; list<h->list_count; list++){
  5011. for(i=0; i<2; i++){
  5012. if(IS_DIR(mb_type, i, list)){
  5013. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 8*i ) : 0;
  5014. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);
  5015. }else
  5016. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);
  5017. }
  5018. }
  5019. for(list=0; list<h->list_count; list++){
  5020. for(i=0; i<2; i++){
  5021. if(IS_DIR(mb_type, i, list)){
  5022. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mpx, &mpy);
  5023. mx = mpx + decode_cabac_mb_mvd( h, list, 8*i, 0 );
  5024. my = mpy + decode_cabac_mb_mvd( h, list, 8*i, 1 );
  5025. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5026. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx-mpx,my-mpy), 4);
  5027. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
  5028. }else{
  5029. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5030. fill_rectangle(h-> mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5031. }
  5032. }
  5033. }
  5034. }else{
  5035. assert(IS_8X16(mb_type));
  5036. for(list=0; list<h->list_count; list++){
  5037. for(i=0; i<2; i++){
  5038. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  5039. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 4*i ) : 0;
  5040. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);
  5041. }else
  5042. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);
  5043. }
  5044. }
  5045. for(list=0; list<h->list_count; list++){
  5046. for(i=0; i<2; i++){
  5047. if(IS_DIR(mb_type, i, list)){
  5048. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mpx, &mpy);
  5049. mx = mpx + decode_cabac_mb_mvd( h, list, 4*i, 0 );
  5050. my = mpy + decode_cabac_mb_mvd( h, list, 4*i, 1 );
  5051. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5052. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5053. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
  5054. }else{
  5055. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5056. fill_rectangle(h-> mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5057. }
  5058. }
  5059. }
  5060. }
  5061. }
  5062. if( IS_INTER( mb_type ) ) {
  5063. h->chroma_pred_mode_table[mb_xy] = 0;
  5064. write_back_motion( h, mb_type );
  5065. }
  5066. if( !IS_INTRA16x16( mb_type ) ) {
  5067. cbp = decode_cabac_mb_cbp_luma( h );
  5068. if(CHROMA)
  5069. cbp |= decode_cabac_mb_cbp_chroma( h ) << 4;
  5070. }
  5071. h->cbp_table[mb_xy] = h->cbp = cbp;
  5072. if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) {
  5073. if( decode_cabac_mb_transform_size( h ) )
  5074. mb_type |= MB_TYPE_8x8DCT;
  5075. }
  5076. s->current_picture.mb_type[mb_xy]= mb_type;
  5077. if( cbp || IS_INTRA16x16( mb_type ) ) {
  5078. const uint8_t *scan, *scan8x8, *dc_scan;
  5079. const uint32_t *qmul;
  5080. int dqp;
  5081. if(IS_INTERLACED(mb_type)){
  5082. scan8x8= s->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
  5083. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  5084. dc_scan= luma_dc_field_scan;
  5085. }else{
  5086. scan8x8= s->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
  5087. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  5088. dc_scan= luma_dc_zigzag_scan;
  5089. }
  5090. h->last_qscale_diff = dqp = decode_cabac_mb_dqp( h );
  5091. if( dqp == INT_MIN ){
  5092. av_log(h->s.avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", s->mb_x, s->mb_y);
  5093. return -1;
  5094. }
  5095. s->qscale += dqp;
  5096. if(((unsigned)s->qscale) > 51){
  5097. if(s->qscale<0) s->qscale+= 52;
  5098. else s->qscale-= 52;
  5099. }
  5100. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  5101. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  5102. if( IS_INTRA16x16( mb_type ) ) {
  5103. int i;
  5104. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 DC\n" );
  5105. decode_cabac_residual( h, h->mb, 0, 0, dc_scan, NULL, 16);
  5106. if( cbp&15 ) {
  5107. qmul = h->dequant4_coeff[0][s->qscale];
  5108. for( i = 0; i < 16; i++ ) {
  5109. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 AC:%d\n", i );
  5110. decode_cabac_residual(h, h->mb + 16*i, 1, i, scan + 1, qmul, 15);
  5111. }
  5112. } else {
  5113. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  5114. }
  5115. } else {
  5116. int i8x8, i4x4;
  5117. for( i8x8 = 0; i8x8 < 4; i8x8++ ) {
  5118. if( cbp & (1<<i8x8) ) {
  5119. if( IS_8x8DCT(mb_type) ) {
  5120. decode_cabac_residual(h, h->mb + 64*i8x8, 5, 4*i8x8,
  5121. scan8x8, h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 64);
  5122. } else {
  5123. qmul = h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale];
  5124. for( i4x4 = 0; i4x4 < 4; i4x4++ ) {
  5125. const int index = 4*i8x8 + i4x4;
  5126. //av_log( s->avctx, AV_LOG_ERROR, "Luma4x4: %d\n", index );
  5127. //START_TIMER
  5128. decode_cabac_residual(h, h->mb + 16*index, 2, index, scan, qmul, 16);
  5129. //STOP_TIMER("decode_residual")
  5130. }
  5131. }
  5132. } else {
  5133. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  5134. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  5135. }
  5136. }
  5137. }
  5138. if( cbp&0x30 ){
  5139. int c;
  5140. for( c = 0; c < 2; c++ ) {
  5141. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-DC\n",c );
  5142. decode_cabac_residual(h, h->mb + 256 + 16*4*c, 3, c, chroma_dc_scan, NULL, 4);
  5143. }
  5144. }
  5145. if( cbp&0x20 ) {
  5146. int c, i;
  5147. for( c = 0; c < 2; c++ ) {
  5148. qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[c]];
  5149. for( i = 0; i < 4; i++ ) {
  5150. const int index = 16 + 4 * c + i;
  5151. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-AC %d\n",c, index - 16 );
  5152. decode_cabac_residual(h, h->mb + 16*index, 4, index - 16, scan + 1, qmul, 15);
  5153. }
  5154. }
  5155. } else {
  5156. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5157. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5158. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5159. }
  5160. } else {
  5161. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5162. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  5163. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5164. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5165. h->last_qscale_diff = 0;
  5166. }
  5167. s->current_picture.qscale_table[mb_xy]= s->qscale;
  5168. write_back_non_zero_count(h);
  5169. if(MB_MBAFF){
  5170. h->ref_count[0] >>= 1;
  5171. h->ref_count[1] >>= 1;
  5172. }
  5173. return 0;
  5174. }
  5175. static void filter_mb_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5176. int i, d;
  5177. const int index_a = qp + h->slice_alpha_c0_offset;
  5178. const int alpha = (alpha_table+52)[index_a];
  5179. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5180. if( bS[0] < 4 ) {
  5181. int8_t tc[4];
  5182. for(i=0; i<4; i++)
  5183. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5184. h->s.dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);
  5185. } else {
  5186. /* 16px edge length, because bS=4 is triggered by being at
  5187. * the edge of an intra MB, so all 4 bS are the same */
  5188. for( d = 0; d < 16; d++ ) {
  5189. const int p0 = pix[-1];
  5190. const int p1 = pix[-2];
  5191. const int p2 = pix[-3];
  5192. const int q0 = pix[0];
  5193. const int q1 = pix[1];
  5194. const int q2 = pix[2];
  5195. if( FFABS( p0 - q0 ) < alpha &&
  5196. FFABS( p1 - p0 ) < beta &&
  5197. FFABS( q1 - q0 ) < beta ) {
  5198. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5199. if( FFABS( p2 - p0 ) < beta)
  5200. {
  5201. const int p3 = pix[-4];
  5202. /* p0', p1', p2' */
  5203. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5204. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5205. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5206. } else {
  5207. /* p0' */
  5208. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5209. }
  5210. if( FFABS( q2 - q0 ) < beta)
  5211. {
  5212. const int q3 = pix[3];
  5213. /* q0', q1', q2' */
  5214. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5215. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5216. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5217. } else {
  5218. /* q0' */
  5219. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5220. }
  5221. }else{
  5222. /* p0', q0' */
  5223. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5224. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5225. }
  5226. 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]);
  5227. }
  5228. pix += stride;
  5229. }
  5230. }
  5231. }
  5232. static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5233. int i;
  5234. const int index_a = qp + h->slice_alpha_c0_offset;
  5235. const int alpha = (alpha_table+52)[index_a];
  5236. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5237. if( bS[0] < 4 ) {
  5238. int8_t tc[4];
  5239. for(i=0; i<4; i++)
  5240. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5241. h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5242. } else {
  5243. h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5244. }
  5245. }
  5246. static void filter_mb_mbaff_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5247. int i;
  5248. for( i = 0; i < 16; i++, pix += stride) {
  5249. int index_a;
  5250. int alpha;
  5251. int beta;
  5252. int qp_index;
  5253. int bS_index = (i >> 1);
  5254. if (!MB_FIELD) {
  5255. bS_index &= ~1;
  5256. bS_index |= (i & 1);
  5257. }
  5258. if( bS[bS_index] == 0 ) {
  5259. continue;
  5260. }
  5261. qp_index = MB_FIELD ? (i >> 3) : (i & 1);
  5262. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5263. alpha = (alpha_table+52)[index_a];
  5264. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5265. if( bS[bS_index] < 4 ) {
  5266. const int tc0 = (tc0_table+52)[index_a][bS[bS_index] - 1];
  5267. const int p0 = pix[-1];
  5268. const int p1 = pix[-2];
  5269. const int p2 = pix[-3];
  5270. const int q0 = pix[0];
  5271. const int q1 = pix[1];
  5272. const int q2 = pix[2];
  5273. if( FFABS( p0 - q0 ) < alpha &&
  5274. FFABS( p1 - p0 ) < beta &&
  5275. FFABS( q1 - q0 ) < beta ) {
  5276. int tc = tc0;
  5277. int i_delta;
  5278. if( FFABS( p2 - p0 ) < beta ) {
  5279. pix[-2] = p1 + av_clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );
  5280. tc++;
  5281. }
  5282. if( FFABS( q2 - q0 ) < beta ) {
  5283. pix[1] = q1 + av_clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );
  5284. tc++;
  5285. }
  5286. i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5287. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5288. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5289. 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);
  5290. }
  5291. }else{
  5292. const int p0 = pix[-1];
  5293. const int p1 = pix[-2];
  5294. const int p2 = pix[-3];
  5295. const int q0 = pix[0];
  5296. const int q1 = pix[1];
  5297. const int q2 = pix[2];
  5298. if( FFABS( p0 - q0 ) < alpha &&
  5299. FFABS( p1 - p0 ) < beta &&
  5300. FFABS( q1 - q0 ) < beta ) {
  5301. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5302. if( FFABS( p2 - p0 ) < beta)
  5303. {
  5304. const int p3 = pix[-4];
  5305. /* p0', p1', p2' */
  5306. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5307. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5308. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5309. } else {
  5310. /* p0' */
  5311. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5312. }
  5313. if( FFABS( q2 - q0 ) < beta)
  5314. {
  5315. const int q3 = pix[3];
  5316. /* q0', q1', q2' */
  5317. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5318. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5319. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5320. } else {
  5321. /* q0' */
  5322. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5323. }
  5324. }else{
  5325. /* p0', q0' */
  5326. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5327. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5328. }
  5329. 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]);
  5330. }
  5331. }
  5332. }
  5333. }
  5334. static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5335. int i;
  5336. for( i = 0; i < 8; i++, pix += stride) {
  5337. int index_a;
  5338. int alpha;
  5339. int beta;
  5340. int qp_index;
  5341. int bS_index = i;
  5342. if( bS[bS_index] == 0 ) {
  5343. continue;
  5344. }
  5345. qp_index = MB_FIELD ? (i >> 2) : (i & 1);
  5346. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5347. alpha = (alpha_table+52)[index_a];
  5348. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5349. if( bS[bS_index] < 4 ) {
  5350. const int tc = (tc0_table+52)[index_a][bS[bS_index] - 1] + 1;
  5351. const int p0 = pix[-1];
  5352. const int p1 = pix[-2];
  5353. const int q0 = pix[0];
  5354. const int q1 = pix[1];
  5355. if( FFABS( p0 - q0 ) < alpha &&
  5356. FFABS( p1 - p0 ) < beta &&
  5357. FFABS( q1 - q0 ) < beta ) {
  5358. const int i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5359. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5360. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5361. 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);
  5362. }
  5363. }else{
  5364. const int p0 = pix[-1];
  5365. const int p1 = pix[-2];
  5366. const int q0 = pix[0];
  5367. const int q1 = pix[1];
  5368. if( FFABS( p0 - q0 ) < alpha &&
  5369. FFABS( p1 - p0 ) < beta &&
  5370. FFABS( q1 - q0 ) < beta ) {
  5371. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2; /* p0' */
  5372. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2; /* q0' */
  5373. 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]);
  5374. }
  5375. }
  5376. }
  5377. }
  5378. static void filter_mb_edgeh( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5379. int i, d;
  5380. const int index_a = qp + h->slice_alpha_c0_offset;
  5381. const int alpha = (alpha_table+52)[index_a];
  5382. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5383. const int pix_next = stride;
  5384. if( bS[0] < 4 ) {
  5385. int8_t tc[4];
  5386. for(i=0; i<4; i++)
  5387. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5388. h->s.dsp.h264_v_loop_filter_luma(pix, stride, alpha, beta, tc);
  5389. } else {
  5390. /* 16px edge length, see filter_mb_edgev */
  5391. for( d = 0; d < 16; d++ ) {
  5392. const int p0 = pix[-1*pix_next];
  5393. const int p1 = pix[-2*pix_next];
  5394. const int p2 = pix[-3*pix_next];
  5395. const int q0 = pix[0];
  5396. const int q1 = pix[1*pix_next];
  5397. const int q2 = pix[2*pix_next];
  5398. if( FFABS( p0 - q0 ) < alpha &&
  5399. FFABS( p1 - p0 ) < beta &&
  5400. FFABS( q1 - q0 ) < beta ) {
  5401. const int p3 = pix[-4*pix_next];
  5402. const int q3 = pix[ 3*pix_next];
  5403. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5404. if( FFABS( p2 - p0 ) < beta) {
  5405. /* p0', p1', p2' */
  5406. pix[-1*pix_next] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5407. pix[-2*pix_next] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5408. pix[-3*pix_next] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5409. } else {
  5410. /* p0' */
  5411. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5412. }
  5413. if( FFABS( q2 - q0 ) < beta) {
  5414. /* q0', q1', q2' */
  5415. pix[0*pix_next] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5416. pix[1*pix_next] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5417. pix[2*pix_next] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5418. } else {
  5419. /* q0' */
  5420. pix[0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5421. }
  5422. }else{
  5423. /* p0', q0' */
  5424. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5425. pix[ 0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5426. }
  5427. 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]);
  5428. }
  5429. pix++;
  5430. }
  5431. }
  5432. }
  5433. static void filter_mb_edgech( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5434. int i;
  5435. const int index_a = qp + h->slice_alpha_c0_offset;
  5436. const int alpha = (alpha_table+52)[index_a];
  5437. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5438. if( bS[0] < 4 ) {
  5439. int8_t tc[4];
  5440. for(i=0; i<4; i++)
  5441. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5442. h->s.dsp.h264_v_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5443. } else {
  5444. h->s.dsp.h264_v_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5445. }
  5446. }
  5447. 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) {
  5448. MpegEncContext * const s = &h->s;
  5449. int mb_y_firstrow = s->picture_structure == PICT_BOTTOM_FIELD;
  5450. int mb_xy, mb_type;
  5451. int qp, qp0, qp1, qpc, qpc0, qpc1, qp_thresh;
  5452. mb_xy = h->mb_xy;
  5453. if(mb_x==0 || mb_y==mb_y_firstrow || !s->dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff ||
  5454. 1 ||
  5455. (h->deblocking_filter == 2 && (h->slice_table[mb_xy] != h->slice_table[h->top_mb_xy] ||
  5456. h->slice_table[mb_xy] != h->slice_table[mb_xy - 1]))) {
  5457. filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
  5458. return;
  5459. }
  5460. assert(!FRAME_MBAFF);
  5461. mb_type = s->current_picture.mb_type[mb_xy];
  5462. qp = s->current_picture.qscale_table[mb_xy];
  5463. qp0 = s->current_picture.qscale_table[mb_xy-1];
  5464. qp1 = s->current_picture.qscale_table[h->top_mb_xy];
  5465. qpc = get_chroma_qp( h, 0, qp );
  5466. qpc0 = get_chroma_qp( h, 0, qp0 );
  5467. qpc1 = get_chroma_qp( h, 0, qp1 );
  5468. qp0 = (qp + qp0 + 1) >> 1;
  5469. qp1 = (qp + qp1 + 1) >> 1;
  5470. qpc0 = (qpc + qpc0 + 1) >> 1;
  5471. qpc1 = (qpc + qpc1 + 1) >> 1;
  5472. qp_thresh = 15 - h->slice_alpha_c0_offset;
  5473. if(qp <= qp_thresh && qp0 <= qp_thresh && qp1 <= qp_thresh &&
  5474. qpc <= qp_thresh && qpc0 <= qp_thresh && qpc1 <= qp_thresh)
  5475. return;
  5476. if( IS_INTRA(mb_type) ) {
  5477. int16_t bS4[4] = {4,4,4,4};
  5478. int16_t bS3[4] = {3,3,3,3};
  5479. int16_t *bSH = FIELD_PICTURE ? bS3 : bS4;
  5480. if( IS_8x8DCT(mb_type) ) {
  5481. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5482. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5483. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5484. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5485. } else {
  5486. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5487. filter_mb_edgev( h, &img_y[4*1], linesize, bS3, qp );
  5488. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5489. filter_mb_edgev( h, &img_y[4*3], linesize, bS3, qp );
  5490. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5491. filter_mb_edgeh( h, &img_y[4*1*linesize], linesize, bS3, qp );
  5492. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5493. filter_mb_edgeh( h, &img_y[4*3*linesize], linesize, bS3, qp );
  5494. }
  5495. filter_mb_edgecv( h, &img_cb[2*0], uvlinesize, bS4, qpc0 );
  5496. filter_mb_edgecv( h, &img_cb[2*2], uvlinesize, bS3, qpc );
  5497. filter_mb_edgecv( h, &img_cr[2*0], uvlinesize, bS4, qpc0 );
  5498. filter_mb_edgecv( h, &img_cr[2*2], uvlinesize, bS3, qpc );
  5499. filter_mb_edgech( h, &img_cb[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5500. filter_mb_edgech( h, &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5501. filter_mb_edgech( h, &img_cr[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5502. filter_mb_edgech( h, &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5503. return;
  5504. } else {
  5505. DECLARE_ALIGNED_8(int16_t, bS[2][4][4]);
  5506. uint64_t (*bSv)[4] = (uint64_t(*)[4])bS;
  5507. int edges;
  5508. if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 ) {
  5509. edges = 4;
  5510. bSv[0][0] = bSv[0][2] = bSv[1][0] = bSv[1][2] = 0x0002000200020002ULL;
  5511. } else {
  5512. int mask_edge1 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 :
  5513. (mb_type & MB_TYPE_16x8) ? 1 : 0;
  5514. int mask_edge0 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5515. && (s->current_picture.mb_type[mb_xy-1] & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5516. ? 3 : 0;
  5517. int step = IS_8x8DCT(mb_type) ? 2 : 1;
  5518. edges = (mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
  5519. s->dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,
  5520. (h->slice_type_nos == FF_B_TYPE), edges, step, mask_edge0, mask_edge1, FIELD_PICTURE);
  5521. }
  5522. if( IS_INTRA(s->current_picture.mb_type[mb_xy-1]) )
  5523. bSv[0][0] = 0x0004000400040004ULL;
  5524. if( IS_INTRA(s->current_picture.mb_type[h->top_mb_xy]) )
  5525. bSv[1][0] = FIELD_PICTURE ? 0x0003000300030003ULL : 0x0004000400040004ULL;
  5526. #define FILTER(hv,dir,edge)\
  5527. if(bSv[dir][edge]) {\
  5528. filter_mb_edge##hv( h, &img_y[4*edge*(dir?linesize:1)], linesize, bS[dir][edge], edge ? qp : qp##dir );\
  5529. if(!(edge&1)) {\
  5530. filter_mb_edgec##hv( h, &img_cb[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5531. filter_mb_edgec##hv( h, &img_cr[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5532. }\
  5533. }
  5534. if( edges == 1 ) {
  5535. FILTER(v,0,0);
  5536. FILTER(h,1,0);
  5537. } else if( IS_8x8DCT(mb_type) ) {
  5538. FILTER(v,0,0);
  5539. FILTER(v,0,2);
  5540. FILTER(h,1,0);
  5541. FILTER(h,1,2);
  5542. } else {
  5543. FILTER(v,0,0);
  5544. FILTER(v,0,1);
  5545. FILTER(v,0,2);
  5546. FILTER(v,0,3);
  5547. FILTER(h,1,0);
  5548. FILTER(h,1,1);
  5549. FILTER(h,1,2);
  5550. FILTER(h,1,3);
  5551. }
  5552. #undef FILTER
  5553. }
  5554. }
  5555. 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) {
  5556. MpegEncContext * const s = &h->s;
  5557. const int mb_xy= mb_x + mb_y*s->mb_stride;
  5558. const int mb_type = s->current_picture.mb_type[mb_xy];
  5559. const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;
  5560. int first_vertical_edge_done = 0;
  5561. int dir;
  5562. //for sufficiently low qp, filtering wouldn't do anything
  5563. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  5564. if(!FRAME_MBAFF){
  5565. 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]);
  5566. int qp = s->current_picture.qscale_table[mb_xy];
  5567. if(qp <= qp_thresh
  5568. && (mb_x == 0 || ((qp + s->current_picture.qscale_table[mb_xy-1] + 1)>>1) <= qp_thresh)
  5569. && (mb_y == 0 || ((qp + s->current_picture.qscale_table[h->top_mb_xy] + 1)>>1) <= qp_thresh)){
  5570. return;
  5571. }
  5572. }
  5573. // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
  5574. if(!h->pps.cabac && h->pps.transform_8x8_mode){
  5575. int top_type, left_type[2];
  5576. top_type = s->current_picture.mb_type[h->top_mb_xy] ;
  5577. left_type[0] = s->current_picture.mb_type[h->left_mb_xy[0]];
  5578. left_type[1] = s->current_picture.mb_type[h->left_mb_xy[1]];
  5579. if(IS_8x8DCT(top_type)){
  5580. h->non_zero_count_cache[4+8*0]=
  5581. h->non_zero_count_cache[5+8*0]= h->cbp_table[h->top_mb_xy] & 4;
  5582. h->non_zero_count_cache[6+8*0]=
  5583. h->non_zero_count_cache[7+8*0]= h->cbp_table[h->top_mb_xy] & 8;
  5584. }
  5585. if(IS_8x8DCT(left_type[0])){
  5586. h->non_zero_count_cache[3+8*1]=
  5587. h->non_zero_count_cache[3+8*2]= h->cbp_table[h->left_mb_xy[0]]&2; //FIXME check MBAFF
  5588. }
  5589. if(IS_8x8DCT(left_type[1])){
  5590. h->non_zero_count_cache[3+8*3]=
  5591. h->non_zero_count_cache[3+8*4]= h->cbp_table[h->left_mb_xy[1]]&8; //FIXME check MBAFF
  5592. }
  5593. if(IS_8x8DCT(mb_type)){
  5594. h->non_zero_count_cache[scan8[0 ]]= h->non_zero_count_cache[scan8[1 ]]=
  5595. h->non_zero_count_cache[scan8[2 ]]= h->non_zero_count_cache[scan8[3 ]]= h->cbp_table[mb_xy] & 1;
  5596. h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
  5597. h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp_table[mb_xy] & 2;
  5598. h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
  5599. h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp_table[mb_xy] & 4;
  5600. h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
  5601. h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp_table[mb_xy] & 8;
  5602. }
  5603. }
  5604. if (FRAME_MBAFF
  5605. // left mb is in picture
  5606. && h->slice_table[mb_xy-1] != 255
  5607. // and current and left pair do not have the same interlaced type
  5608. && (IS_INTERLACED(mb_type) != IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]))
  5609. // and left mb is in the same slice if deblocking_filter == 2
  5610. && (h->deblocking_filter!=2 || h->slice_table[mb_xy-1] == h->slice_table[mb_xy])) {
  5611. /* First vertical edge is different in MBAFF frames
  5612. * There are 8 different bS to compute and 2 different Qp
  5613. */
  5614. const int pair_xy = mb_x + (mb_y&~1)*s->mb_stride;
  5615. const int left_mb_xy[2] = { pair_xy-1, pair_xy-1+s->mb_stride };
  5616. int16_t bS[8];
  5617. int qp[2];
  5618. int bqp[2];
  5619. int rqp[2];
  5620. int mb_qp, mbn0_qp, mbn1_qp;
  5621. int i;
  5622. first_vertical_edge_done = 1;
  5623. if( IS_INTRA(mb_type) )
  5624. bS[0] = bS[1] = bS[2] = bS[3] = bS[4] = bS[5] = bS[6] = bS[7] = 4;
  5625. else {
  5626. for( i = 0; i < 8; i++ ) {
  5627. int mbn_xy = MB_FIELD ? left_mb_xy[i>>2] : left_mb_xy[i&1];
  5628. if( IS_INTRA( s->current_picture.mb_type[mbn_xy] ) )
  5629. bS[i] = 4;
  5630. else if( h->non_zero_count_cache[12+8*(i>>1)] != 0 ||
  5631. /* FIXME: with 8x8dct + cavlc, should check cbp instead of nnz */
  5632. h->non_zero_count[mbn_xy][MB_FIELD ? i&3 : (i>>2)+(mb_y&1)*2] )
  5633. bS[i] = 2;
  5634. else
  5635. bS[i] = 1;
  5636. }
  5637. }
  5638. mb_qp = s->current_picture.qscale_table[mb_xy];
  5639. mbn0_qp = s->current_picture.qscale_table[left_mb_xy[0]];
  5640. mbn1_qp = s->current_picture.qscale_table[left_mb_xy[1]];
  5641. qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;
  5642. bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +
  5643. get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;
  5644. rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +
  5645. get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;
  5646. qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;
  5647. bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +
  5648. get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;
  5649. rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +
  5650. get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;
  5651. /* Filter edge */
  5652. 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);
  5653. { int i; for (i = 0; i < 8; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5654. filter_mb_mbaff_edgev ( h, &img_y [0], linesize, bS, qp );
  5655. filter_mb_mbaff_edgecv( h, &img_cb[0], uvlinesize, bS, bqp );
  5656. filter_mb_mbaff_edgecv( h, &img_cr[0], uvlinesize, bS, rqp );
  5657. }
  5658. /* dir : 0 -> vertical edge, 1 -> horizontal edge */
  5659. for( dir = 0; dir < 2; dir++ )
  5660. {
  5661. int edge;
  5662. const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
  5663. const int mbm_type = s->current_picture.mb_type[mbm_xy];
  5664. int (*ref2frm) [64] = h->ref2frm[ h->slice_num &15 ][0] + (MB_MBAFF ? 20 : 2);
  5665. int (*ref2frmm)[64] = h->ref2frm[ h->slice_table[mbm_xy]&15 ][0] + (MB_MBAFF ? 20 : 2);
  5666. int start = h->slice_table[mbm_xy] == 255 ? 1 : 0;
  5667. const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))
  5668. == (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;
  5669. // how often to recheck mv-based bS when iterating between edges
  5670. const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :
  5671. (mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;
  5672. // how often to recheck mv-based bS when iterating along each edge
  5673. const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
  5674. if (first_vertical_edge_done) {
  5675. start = 1;
  5676. first_vertical_edge_done = 0;
  5677. }
  5678. if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])
  5679. start = 1;
  5680. if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0
  5681. && !IS_INTERLACED(mb_type)
  5682. && IS_INTERLACED(mbm_type)
  5683. ) {
  5684. // This is a special case in the norm where the filtering must
  5685. // be done twice (one each of the field) even if we are in a
  5686. // frame macroblock.
  5687. //
  5688. static const int nnz_idx[4] = {4,5,6,3};
  5689. unsigned int tmp_linesize = 2 * linesize;
  5690. unsigned int tmp_uvlinesize = 2 * uvlinesize;
  5691. int mbn_xy = mb_xy - 2 * s->mb_stride;
  5692. int qp;
  5693. int i, j;
  5694. int16_t bS[4];
  5695. for(j=0; j<2; j++, mbn_xy += s->mb_stride){
  5696. if( IS_INTRA(mb_type) ||
  5697. IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {
  5698. bS[0] = bS[1] = bS[2] = bS[3] = 3;
  5699. } else {
  5700. const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];
  5701. for( i = 0; i < 4; i++ ) {
  5702. if( h->non_zero_count_cache[scan8[0]+i] != 0 ||
  5703. mbn_nnz[nnz_idx[i]] != 0 )
  5704. bS[i] = 2;
  5705. else
  5706. bS[i] = 1;
  5707. }
  5708. }
  5709. // Do not use s->qscale as luma quantizer because it has not the same
  5710. // value in IPCM macroblocks.
  5711. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5712. 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);
  5713. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5714. filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );
  5715. filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,
  5716. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5717. filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,
  5718. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5719. }
  5720. start = 1;
  5721. }
  5722. /* Calculate bS */
  5723. for( edge = start; edge < edges; edge++ ) {
  5724. /* mbn_xy: neighbor macroblock */
  5725. const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;
  5726. const int mbn_type = s->current_picture.mb_type[mbn_xy];
  5727. int (*ref2frmn)[64] = edge > 0 ? ref2frm : ref2frmm;
  5728. int16_t bS[4];
  5729. int qp;
  5730. if( (edge&1) && IS_8x8DCT(mb_type) )
  5731. continue;
  5732. if( IS_INTRA(mb_type) ||
  5733. IS_INTRA(mbn_type) ) {
  5734. int value;
  5735. if (edge == 0) {
  5736. if ( (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))
  5737. || ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))
  5738. ) {
  5739. value = 4;
  5740. } else {
  5741. value = 3;
  5742. }
  5743. } else {
  5744. value = 3;
  5745. }
  5746. bS[0] = bS[1] = bS[2] = bS[3] = value;
  5747. } else {
  5748. int i, l;
  5749. int mv_done;
  5750. if( edge & mask_edge ) {
  5751. bS[0] = bS[1] = bS[2] = bS[3] = 0;
  5752. mv_done = 1;
  5753. }
  5754. else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {
  5755. bS[0] = bS[1] = bS[2] = bS[3] = 1;
  5756. mv_done = 1;
  5757. }
  5758. else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {
  5759. int b_idx= 8 + 4 + edge * (dir ? 8:1);
  5760. int bn_idx= b_idx - (dir ? 8:1);
  5761. int v = 0;
  5762. for( l = 0; !v && l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {
  5763. v |= ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[l][h->ref_cache[l][bn_idx]] ||
  5764. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5765. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit;
  5766. }
  5767. if(h->slice_type_nos == FF_B_TYPE && v){
  5768. v=0;
  5769. for( l = 0; !v && l < 2; l++ ) {
  5770. int ln= 1-l;
  5771. v |= ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[ln][h->ref_cache[ln][bn_idx]] ||
  5772. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||
  5773. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit;
  5774. }
  5775. }
  5776. bS[0] = bS[1] = bS[2] = bS[3] = v;
  5777. mv_done = 1;
  5778. }
  5779. else
  5780. mv_done = 0;
  5781. for( i = 0; i < 4; i++ ) {
  5782. int x = dir == 0 ? edge : i;
  5783. int y = dir == 0 ? i : edge;
  5784. int b_idx= 8 + 4 + x + 8*y;
  5785. int bn_idx= b_idx - (dir ? 8:1);
  5786. if( h->non_zero_count_cache[b_idx] != 0 ||
  5787. h->non_zero_count_cache[bn_idx] != 0 ) {
  5788. bS[i] = 2;
  5789. }
  5790. else if(!mv_done)
  5791. {
  5792. bS[i] = 0;
  5793. for( l = 0; l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {
  5794. if( ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[l][h->ref_cache[l][bn_idx]] ||
  5795. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5796. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit ) {
  5797. bS[i] = 1;
  5798. break;
  5799. }
  5800. }
  5801. if(h->slice_type_nos == FF_B_TYPE && bS[i]){
  5802. bS[i] = 0;
  5803. for( l = 0; l < 2; l++ ) {
  5804. int ln= 1-l;
  5805. if( ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[ln][h->ref_cache[ln][bn_idx]] ||
  5806. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||
  5807. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit ) {
  5808. bS[i] = 1;
  5809. break;
  5810. }
  5811. }
  5812. }
  5813. }
  5814. }
  5815. if(bS[0]+bS[1]+bS[2]+bS[3] == 0)
  5816. continue;
  5817. }
  5818. /* Filter edge */
  5819. // Do not use s->qscale as luma quantizer because it has not the same
  5820. // value in IPCM macroblocks.
  5821. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5822. //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]);
  5823. 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);
  5824. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5825. if( dir == 0 ) {
  5826. filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );
  5827. if( (edge&1) == 0 ) {
  5828. filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,
  5829. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5830. filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,
  5831. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5832. }
  5833. } else {
  5834. filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );
  5835. if( (edge&1) == 0 ) {
  5836. filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,
  5837. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5838. filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,
  5839. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5840. }
  5841. }
  5842. }
  5843. }
  5844. }
  5845. static int decode_slice(struct AVCodecContext *avctx, H264Context *h){
  5846. MpegEncContext * const s = &h->s;
  5847. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  5848. s->mb_skip_run= -1;
  5849. if( h->pps.cabac ) {
  5850. int i;
  5851. /* realign */
  5852. align_get_bits( &s->gb );
  5853. /* init cabac */
  5854. ff_init_cabac_states( &h->cabac);
  5855. ff_init_cabac_decoder( &h->cabac,
  5856. s->gb.buffer + get_bits_count(&s->gb)/8,
  5857. ( s->gb.size_in_bits - get_bits_count(&s->gb) + 7)/8);
  5858. /* calculate pre-state */
  5859. for( i= 0; i < 460; i++ ) {
  5860. int pre;
  5861. if( h->slice_type_nos == FF_I_TYPE )
  5862. pre = av_clip( ((cabac_context_init_I[i][0] * s->qscale) >>4 ) + cabac_context_init_I[i][1], 1, 126 );
  5863. else
  5864. pre = av_clip( ((cabac_context_init_PB[h->cabac_init_idc][i][0] * s->qscale) >>4 ) + cabac_context_init_PB[h->cabac_init_idc][i][1], 1, 126 );
  5865. if( pre <= 63 )
  5866. h->cabac_state[i] = 2 * ( 63 - pre ) + 0;
  5867. else
  5868. h->cabac_state[i] = 2 * ( pre - 64 ) + 1;
  5869. }
  5870. for(;;){
  5871. //START_TIMER
  5872. int ret = decode_mb_cabac(h);
  5873. int eos;
  5874. //STOP_TIMER("decode_mb_cabac")
  5875. if(ret>=0) hl_decode_mb(h);
  5876. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  5877. s->mb_y++;
  5878. if(ret>=0) ret = decode_mb_cabac(h);
  5879. if(ret>=0) hl_decode_mb(h);
  5880. s->mb_y--;
  5881. }
  5882. eos = get_cabac_terminate( &h->cabac );
  5883. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  5884. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream (%td)\n", s->mb_x, s->mb_y, h->cabac.bytestream_end - h->cabac.bytestream);
  5885. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  5886. return -1;
  5887. }
  5888. if( ++s->mb_x >= s->mb_width ) {
  5889. s->mb_x = 0;
  5890. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  5891. ++s->mb_y;
  5892. if(FIELD_OR_MBAFF_PICTURE) {
  5893. ++s->mb_y;
  5894. }
  5895. }
  5896. if( eos || s->mb_y >= s->mb_height ) {
  5897. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  5898. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5899. return 0;
  5900. }
  5901. }
  5902. } else {
  5903. for(;;){
  5904. int ret = decode_mb_cavlc(h);
  5905. if(ret>=0) hl_decode_mb(h);
  5906. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  5907. s->mb_y++;
  5908. ret = decode_mb_cavlc(h);
  5909. if(ret>=0) hl_decode_mb(h);
  5910. s->mb_y--;
  5911. }
  5912. if(ret<0){
  5913. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  5914. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  5915. return -1;
  5916. }
  5917. if(++s->mb_x >= s->mb_width){
  5918. s->mb_x=0;
  5919. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  5920. ++s->mb_y;
  5921. if(FIELD_OR_MBAFF_PICTURE) {
  5922. ++s->mb_y;
  5923. }
  5924. if(s->mb_y >= s->mb_height){
  5925. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  5926. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  5927. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5928. return 0;
  5929. }else{
  5930. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5931. return -1;
  5932. }
  5933. }
  5934. }
  5935. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  5936. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  5937. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  5938. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5939. return 0;
  5940. }else{
  5941. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  5942. return -1;
  5943. }
  5944. }
  5945. }
  5946. }
  5947. #if 0
  5948. for(;s->mb_y < s->mb_height; s->mb_y++){
  5949. for(;s->mb_x < s->mb_width; s->mb_x++){
  5950. int ret= decode_mb(h);
  5951. hl_decode_mb(h);
  5952. if(ret<0){
  5953. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  5954. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  5955. return -1;
  5956. }
  5957. if(++s->mb_x >= s->mb_width){
  5958. s->mb_x=0;
  5959. if(++s->mb_y >= s->mb_height){
  5960. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  5961. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5962. return 0;
  5963. }else{
  5964. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5965. return -1;
  5966. }
  5967. }
  5968. }
  5969. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  5970. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  5971. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5972. return 0;
  5973. }else{
  5974. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  5975. return -1;
  5976. }
  5977. }
  5978. }
  5979. s->mb_x=0;
  5980. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  5981. }
  5982. #endif
  5983. return -1; //not reached
  5984. }
  5985. static int decode_unregistered_user_data(H264Context *h, int size){
  5986. MpegEncContext * const s = &h->s;
  5987. uint8_t user_data[16+256];
  5988. int e, build, i;
  5989. if(size<16)
  5990. return -1;
  5991. for(i=0; i<sizeof(user_data)-1 && i<size; i++){
  5992. user_data[i]= get_bits(&s->gb, 8);
  5993. }
  5994. user_data[i]= 0;
  5995. e= sscanf(user_data+16, "x264 - core %d"/*%s - H.264/MPEG-4 AVC codec - Copyleft 2005 - http://www.videolan.org/x264.html*/, &build);
  5996. if(e==1 && build>=0)
  5997. h->x264_build= build;
  5998. if(s->avctx->debug & FF_DEBUG_BUGS)
  5999. av_log(s->avctx, AV_LOG_DEBUG, "user data:\"%s\"\n", user_data+16);
  6000. for(; i<size; i++)
  6001. skip_bits(&s->gb, 8);
  6002. return 0;
  6003. }
  6004. static int decode_sei(H264Context *h){
  6005. MpegEncContext * const s = &h->s;
  6006. while(get_bits_count(&s->gb) + 16 < s->gb.size_in_bits){
  6007. int size, type;
  6008. type=0;
  6009. do{
  6010. type+= show_bits(&s->gb, 8);
  6011. }while(get_bits(&s->gb, 8) == 255);
  6012. size=0;
  6013. do{
  6014. size+= show_bits(&s->gb, 8);
  6015. }while(get_bits(&s->gb, 8) == 255);
  6016. switch(type){
  6017. case 5:
  6018. if(decode_unregistered_user_data(h, size) < 0)
  6019. return -1;
  6020. break;
  6021. default:
  6022. skip_bits(&s->gb, 8*size);
  6023. }
  6024. //FIXME check bits here
  6025. align_get_bits(&s->gb);
  6026. }
  6027. return 0;
  6028. }
  6029. static inline void decode_hrd_parameters(H264Context *h, SPS *sps){
  6030. MpegEncContext * const s = &h->s;
  6031. int cpb_count, i;
  6032. cpb_count = get_ue_golomb(&s->gb) + 1;
  6033. get_bits(&s->gb, 4); /* bit_rate_scale */
  6034. get_bits(&s->gb, 4); /* cpb_size_scale */
  6035. for(i=0; i<cpb_count; i++){
  6036. get_ue_golomb(&s->gb); /* bit_rate_value_minus1 */
  6037. get_ue_golomb(&s->gb); /* cpb_size_value_minus1 */
  6038. get_bits1(&s->gb); /* cbr_flag */
  6039. }
  6040. get_bits(&s->gb, 5); /* initial_cpb_removal_delay_length_minus1 */
  6041. get_bits(&s->gb, 5); /* cpb_removal_delay_length_minus1 */
  6042. get_bits(&s->gb, 5); /* dpb_output_delay_length_minus1 */
  6043. get_bits(&s->gb, 5); /* time_offset_length */
  6044. }
  6045. static inline int decode_vui_parameters(H264Context *h, SPS *sps){
  6046. MpegEncContext * const s = &h->s;
  6047. int aspect_ratio_info_present_flag;
  6048. unsigned int aspect_ratio_idc;
  6049. int nal_hrd_parameters_present_flag, vcl_hrd_parameters_present_flag;
  6050. aspect_ratio_info_present_flag= get_bits1(&s->gb);
  6051. if( aspect_ratio_info_present_flag ) {
  6052. aspect_ratio_idc= get_bits(&s->gb, 8);
  6053. if( aspect_ratio_idc == EXTENDED_SAR ) {
  6054. sps->sar.num= get_bits(&s->gb, 16);
  6055. sps->sar.den= get_bits(&s->gb, 16);
  6056. }else if(aspect_ratio_idc < sizeof(pixel_aspect)/sizeof(*pixel_aspect)){
  6057. sps->sar= pixel_aspect[aspect_ratio_idc];
  6058. }else{
  6059. av_log(h->s.avctx, AV_LOG_ERROR, "illegal aspect ratio\n");
  6060. return -1;
  6061. }
  6062. }else{
  6063. sps->sar.num=
  6064. sps->sar.den= 0;
  6065. }
  6066. // s->avctx->aspect_ratio= sar_width*s->width / (float)(s->height*sar_height);
  6067. if(get_bits1(&s->gb)){ /* overscan_info_present_flag */
  6068. get_bits1(&s->gb); /* overscan_appropriate_flag */
  6069. }
  6070. if(get_bits1(&s->gb)){ /* video_signal_type_present_flag */
  6071. get_bits(&s->gb, 3); /* video_format */
  6072. get_bits1(&s->gb); /* video_full_range_flag */
  6073. if(get_bits1(&s->gb)){ /* colour_description_present_flag */
  6074. get_bits(&s->gb, 8); /* colour_primaries */
  6075. get_bits(&s->gb, 8); /* transfer_characteristics */
  6076. get_bits(&s->gb, 8); /* matrix_coefficients */
  6077. }
  6078. }
  6079. if(get_bits1(&s->gb)){ /* chroma_location_info_present_flag */
  6080. get_ue_golomb(&s->gb); /* chroma_sample_location_type_top_field */
  6081. get_ue_golomb(&s->gb); /* chroma_sample_location_type_bottom_field */
  6082. }
  6083. sps->timing_info_present_flag = get_bits1(&s->gb);
  6084. if(sps->timing_info_present_flag){
  6085. sps->num_units_in_tick = get_bits_long(&s->gb, 32);
  6086. sps->time_scale = get_bits_long(&s->gb, 32);
  6087. sps->fixed_frame_rate_flag = get_bits1(&s->gb);
  6088. }
  6089. nal_hrd_parameters_present_flag = get_bits1(&s->gb);
  6090. if(nal_hrd_parameters_present_flag)
  6091. decode_hrd_parameters(h, sps);
  6092. vcl_hrd_parameters_present_flag = get_bits1(&s->gb);
  6093. if(vcl_hrd_parameters_present_flag)
  6094. decode_hrd_parameters(h, sps);
  6095. if(nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag)
  6096. get_bits1(&s->gb); /* low_delay_hrd_flag */
  6097. get_bits1(&s->gb); /* pic_struct_present_flag */
  6098. sps->bitstream_restriction_flag = get_bits1(&s->gb);
  6099. if(sps->bitstream_restriction_flag){
  6100. unsigned int num_reorder_frames;
  6101. get_bits1(&s->gb); /* motion_vectors_over_pic_boundaries_flag */
  6102. get_ue_golomb(&s->gb); /* max_bytes_per_pic_denom */
  6103. get_ue_golomb(&s->gb); /* max_bits_per_mb_denom */
  6104. get_ue_golomb(&s->gb); /* log2_max_mv_length_horizontal */
  6105. get_ue_golomb(&s->gb); /* log2_max_mv_length_vertical */
  6106. num_reorder_frames= get_ue_golomb(&s->gb);
  6107. get_ue_golomb(&s->gb); /*max_dec_frame_buffering*/
  6108. if(num_reorder_frames > 16 /*max_dec_frame_buffering || max_dec_frame_buffering > 16*/){
  6109. av_log(h->s.avctx, AV_LOG_ERROR, "illegal num_reorder_frames %d\n", num_reorder_frames);
  6110. return -1;
  6111. }
  6112. sps->num_reorder_frames= num_reorder_frames;
  6113. }
  6114. return 0;
  6115. }
  6116. static void decode_scaling_list(H264Context *h, uint8_t *factors, int size,
  6117. const uint8_t *jvt_list, const uint8_t *fallback_list){
  6118. MpegEncContext * const s = &h->s;
  6119. int i, last = 8, next = 8;
  6120. const uint8_t *scan = size == 16 ? zigzag_scan : zigzag_scan8x8;
  6121. if(!get_bits1(&s->gb)) /* matrix not written, we use the predicted one */
  6122. memcpy(factors, fallback_list, size*sizeof(uint8_t));
  6123. else
  6124. for(i=0;i<size;i++){
  6125. if(next)
  6126. next = (last + get_se_golomb(&s->gb)) & 0xff;
  6127. if(!i && !next){ /* matrix not written, we use the preset one */
  6128. memcpy(factors, jvt_list, size*sizeof(uint8_t));
  6129. break;
  6130. }
  6131. last = factors[scan[i]] = next ? next : last;
  6132. }
  6133. }
  6134. static void decode_scaling_matrices(H264Context *h, SPS *sps, PPS *pps, int is_sps,
  6135. uint8_t (*scaling_matrix4)[16], uint8_t (*scaling_matrix8)[64]){
  6136. MpegEncContext * const s = &h->s;
  6137. int fallback_sps = !is_sps && sps->scaling_matrix_present;
  6138. const uint8_t *fallback[4] = {
  6139. fallback_sps ? sps->scaling_matrix4[0] : default_scaling4[0],
  6140. fallback_sps ? sps->scaling_matrix4[3] : default_scaling4[1],
  6141. fallback_sps ? sps->scaling_matrix8[0] : default_scaling8[0],
  6142. fallback_sps ? sps->scaling_matrix8[1] : default_scaling8[1]
  6143. };
  6144. if(get_bits1(&s->gb)){
  6145. sps->scaling_matrix_present |= is_sps;
  6146. decode_scaling_list(h,scaling_matrix4[0],16,default_scaling4[0],fallback[0]); // Intra, Y
  6147. decode_scaling_list(h,scaling_matrix4[1],16,default_scaling4[0],scaling_matrix4[0]); // Intra, Cr
  6148. decode_scaling_list(h,scaling_matrix4[2],16,default_scaling4[0],scaling_matrix4[1]); // Intra, Cb
  6149. decode_scaling_list(h,scaling_matrix4[3],16,default_scaling4[1],fallback[1]); // Inter, Y
  6150. decode_scaling_list(h,scaling_matrix4[4],16,default_scaling4[1],scaling_matrix4[3]); // Inter, Cr
  6151. decode_scaling_list(h,scaling_matrix4[5],16,default_scaling4[1],scaling_matrix4[4]); // Inter, Cb
  6152. if(is_sps || pps->transform_8x8_mode){
  6153. decode_scaling_list(h,scaling_matrix8[0],64,default_scaling8[0],fallback[2]); // Intra, Y
  6154. decode_scaling_list(h,scaling_matrix8[1],64,default_scaling8[1],fallback[3]); // Inter, Y
  6155. }
  6156. } else if(fallback_sps) {
  6157. memcpy(scaling_matrix4, sps->scaling_matrix4, 6*16*sizeof(uint8_t));
  6158. memcpy(scaling_matrix8, sps->scaling_matrix8, 2*64*sizeof(uint8_t));
  6159. }
  6160. }
  6161. /**
  6162. * Returns and optionally allocates SPS / PPS structures in the supplied array 'vec'
  6163. */
  6164. static void *
  6165. alloc_parameter_set(H264Context *h, void **vec, const unsigned int id, const unsigned int max,
  6166. const size_t size, const char *name)
  6167. {
  6168. if(id>=max) {
  6169. av_log(h->s.avctx, AV_LOG_ERROR, "%s_id (%d) out of range\n", name, id);
  6170. return NULL;
  6171. }
  6172. if(!vec[id]) {
  6173. vec[id] = av_mallocz(size);
  6174. if(vec[id] == NULL)
  6175. av_log(h->s.avctx, AV_LOG_ERROR, "cannot allocate memory for %s\n", name);
  6176. }
  6177. return vec[id];
  6178. }
  6179. static inline int decode_seq_parameter_set(H264Context *h){
  6180. MpegEncContext * const s = &h->s;
  6181. int profile_idc, level_idc;
  6182. unsigned int sps_id, tmp, mb_width, mb_height;
  6183. int i;
  6184. SPS *sps;
  6185. profile_idc= get_bits(&s->gb, 8);
  6186. get_bits1(&s->gb); //constraint_set0_flag
  6187. get_bits1(&s->gb); //constraint_set1_flag
  6188. get_bits1(&s->gb); //constraint_set2_flag
  6189. get_bits1(&s->gb); //constraint_set3_flag
  6190. get_bits(&s->gb, 4); // reserved
  6191. level_idc= get_bits(&s->gb, 8);
  6192. sps_id= get_ue_golomb(&s->gb);
  6193. sps = alloc_parameter_set(h, (void **)h->sps_buffers, sps_id, MAX_SPS_COUNT, sizeof(SPS), "sps");
  6194. if(sps == NULL)
  6195. return -1;
  6196. sps->profile_idc= profile_idc;
  6197. sps->level_idc= level_idc;
  6198. if(sps->profile_idc >= 100){ //high profile
  6199. sps->chroma_format_idc= get_ue_golomb(&s->gb);
  6200. if(sps->chroma_format_idc == 3)
  6201. get_bits1(&s->gb); //residual_color_transform_flag
  6202. get_ue_golomb(&s->gb); //bit_depth_luma_minus8
  6203. get_ue_golomb(&s->gb); //bit_depth_chroma_minus8
  6204. sps->transform_bypass = get_bits1(&s->gb);
  6205. decode_scaling_matrices(h, sps, NULL, 1, sps->scaling_matrix4, sps->scaling_matrix8);
  6206. }else{
  6207. sps->scaling_matrix_present = 0;
  6208. sps->chroma_format_idc= 1;
  6209. }
  6210. sps->log2_max_frame_num= get_ue_golomb(&s->gb) + 4;
  6211. sps->poc_type= get_ue_golomb(&s->gb);
  6212. if(sps->poc_type == 0){ //FIXME #define
  6213. sps->log2_max_poc_lsb= get_ue_golomb(&s->gb) + 4;
  6214. } else if(sps->poc_type == 1){//FIXME #define
  6215. sps->delta_pic_order_always_zero_flag= get_bits1(&s->gb);
  6216. sps->offset_for_non_ref_pic= get_se_golomb(&s->gb);
  6217. sps->offset_for_top_to_bottom_field= get_se_golomb(&s->gb);
  6218. tmp= get_ue_golomb(&s->gb);
  6219. if(tmp >= sizeof(sps->offset_for_ref_frame) / sizeof(sps->offset_for_ref_frame[0])){
  6220. av_log(h->s.avctx, AV_LOG_ERROR, "poc_cycle_length overflow %u\n", tmp);
  6221. return -1;
  6222. }
  6223. sps->poc_cycle_length= tmp;
  6224. for(i=0; i<sps->poc_cycle_length; i++)
  6225. sps->offset_for_ref_frame[i]= get_se_golomb(&s->gb);
  6226. }else if(sps->poc_type != 2){
  6227. av_log(h->s.avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);
  6228. return -1;
  6229. }
  6230. tmp= get_ue_golomb(&s->gb);
  6231. if(tmp > MAX_PICTURE_COUNT-2 || tmp >= 32){
  6232. av_log(h->s.avctx, AV_LOG_ERROR, "too many reference frames\n");
  6233. return -1;
  6234. }
  6235. sps->ref_frame_count= tmp;
  6236. sps->gaps_in_frame_num_allowed_flag= get_bits1(&s->gb);
  6237. mb_width= get_ue_golomb(&s->gb) + 1;
  6238. mb_height= get_ue_golomb(&s->gb) + 1;
  6239. if(mb_width >= INT_MAX/16 || mb_height >= INT_MAX/16 ||
  6240. avcodec_check_dimensions(NULL, 16*mb_width, 16*mb_height)){
  6241. av_log(h->s.avctx, AV_LOG_ERROR, "mb_width/height overflow\n");
  6242. return -1;
  6243. }
  6244. sps->mb_width = mb_width;
  6245. sps->mb_height= mb_height;
  6246. sps->frame_mbs_only_flag= get_bits1(&s->gb);
  6247. if(!sps->frame_mbs_only_flag)
  6248. sps->mb_aff= get_bits1(&s->gb);
  6249. else
  6250. sps->mb_aff= 0;
  6251. sps->direct_8x8_inference_flag= get_bits1(&s->gb);
  6252. #ifndef ALLOW_INTERLACE
  6253. if(sps->mb_aff)
  6254. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF support not included; enable it at compile-time.\n");
  6255. #endif
  6256. if(!sps->direct_8x8_inference_flag && sps->mb_aff)
  6257. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF + !direct_8x8_inference is not implemented\n");
  6258. sps->crop= get_bits1(&s->gb);
  6259. if(sps->crop){
  6260. sps->crop_left = get_ue_golomb(&s->gb);
  6261. sps->crop_right = get_ue_golomb(&s->gb);
  6262. sps->crop_top = get_ue_golomb(&s->gb);
  6263. sps->crop_bottom= get_ue_golomb(&s->gb);
  6264. if(sps->crop_left || sps->crop_top){
  6265. av_log(h->s.avctx, AV_LOG_ERROR, "insane cropping not completely supported, this could look slightly wrong ...\n");
  6266. }
  6267. if(sps->crop_right >= 8 || sps->crop_bottom >= (8>> !h->sps.frame_mbs_only_flag)){
  6268. av_log(h->s.avctx, AV_LOG_ERROR, "brainfart cropping not supported, this could look slightly wrong ...\n");
  6269. }
  6270. }else{
  6271. sps->crop_left =
  6272. sps->crop_right =
  6273. sps->crop_top =
  6274. sps->crop_bottom= 0;
  6275. }
  6276. sps->vui_parameters_present_flag= get_bits1(&s->gb);
  6277. if( sps->vui_parameters_present_flag )
  6278. decode_vui_parameters(h, sps);
  6279. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6280. 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",
  6281. sps_id, sps->profile_idc, sps->level_idc,
  6282. sps->poc_type,
  6283. sps->ref_frame_count,
  6284. sps->mb_width, sps->mb_height,
  6285. sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),
  6286. sps->direct_8x8_inference_flag ? "8B8" : "",
  6287. sps->crop_left, sps->crop_right,
  6288. sps->crop_top, sps->crop_bottom,
  6289. sps->vui_parameters_present_flag ? "VUI" : "",
  6290. ((const char*[]){"Gray","420","422","444"})[sps->chroma_format_idc]
  6291. );
  6292. }
  6293. return 0;
  6294. }
  6295. static void
  6296. build_qp_table(PPS *pps, int t, int index)
  6297. {
  6298. int i;
  6299. for(i = 0; i < 52; i++)
  6300. pps->chroma_qp_table[t][i] = chroma_qp[av_clip(i + index, 0, 51)];
  6301. }
  6302. static inline int decode_picture_parameter_set(H264Context *h, int bit_length){
  6303. MpegEncContext * const s = &h->s;
  6304. unsigned int tmp, pps_id= get_ue_golomb(&s->gb);
  6305. PPS *pps;
  6306. pps = alloc_parameter_set(h, (void **)h->pps_buffers, pps_id, MAX_PPS_COUNT, sizeof(PPS), "pps");
  6307. if(pps == NULL)
  6308. return -1;
  6309. tmp= get_ue_golomb(&s->gb);
  6310. if(tmp>=MAX_SPS_COUNT || h->sps_buffers[tmp] == NULL){
  6311. av_log(h->s.avctx, AV_LOG_ERROR, "sps_id out of range\n");
  6312. return -1;
  6313. }
  6314. pps->sps_id= tmp;
  6315. pps->cabac= get_bits1(&s->gb);
  6316. pps->pic_order_present= get_bits1(&s->gb);
  6317. pps->slice_group_count= get_ue_golomb(&s->gb) + 1;
  6318. if(pps->slice_group_count > 1 ){
  6319. pps->mb_slice_group_map_type= get_ue_golomb(&s->gb);
  6320. av_log(h->s.avctx, AV_LOG_ERROR, "FMO not supported\n");
  6321. switch(pps->mb_slice_group_map_type){
  6322. case 0:
  6323. #if 0
  6324. | for( i = 0; i <= num_slice_groups_minus1; i++ ) | | |
  6325. | run_length[ i ] |1 |ue(v) |
  6326. #endif
  6327. break;
  6328. case 2:
  6329. #if 0
  6330. | for( i = 0; i < num_slice_groups_minus1; i++ ) | | |
  6331. |{ | | |
  6332. | top_left_mb[ i ] |1 |ue(v) |
  6333. | bottom_right_mb[ i ] |1 |ue(v) |
  6334. | } | | |
  6335. #endif
  6336. break;
  6337. case 3:
  6338. case 4:
  6339. case 5:
  6340. #if 0
  6341. | slice_group_change_direction_flag |1 |u(1) |
  6342. | slice_group_change_rate_minus1 |1 |ue(v) |
  6343. #endif
  6344. break;
  6345. case 6:
  6346. #if 0
  6347. | slice_group_id_cnt_minus1 |1 |ue(v) |
  6348. | for( i = 0; i <= slice_group_id_cnt_minus1; i++ | | |
  6349. |) | | |
  6350. | slice_group_id[ i ] |1 |u(v) |
  6351. #endif
  6352. break;
  6353. }
  6354. }
  6355. pps->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  6356. pps->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  6357. if(pps->ref_count[0]-1 > 32-1 || pps->ref_count[1]-1 > 32-1){
  6358. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow (pps)\n");
  6359. pps->ref_count[0]= pps->ref_count[1]= 1;
  6360. return -1;
  6361. }
  6362. pps->weighted_pred= get_bits1(&s->gb);
  6363. pps->weighted_bipred_idc= get_bits(&s->gb, 2);
  6364. pps->init_qp= get_se_golomb(&s->gb) + 26;
  6365. pps->init_qs= get_se_golomb(&s->gb) + 26;
  6366. pps->chroma_qp_index_offset[0]= get_se_golomb(&s->gb);
  6367. pps->deblocking_filter_parameters_present= get_bits1(&s->gb);
  6368. pps->constrained_intra_pred= get_bits1(&s->gb);
  6369. pps->redundant_pic_cnt_present = get_bits1(&s->gb);
  6370. pps->transform_8x8_mode= 0;
  6371. h->dequant_coeff_pps= -1; //contents of sps/pps can change even if id doesn't, so reinit
  6372. memset(pps->scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  6373. memset(pps->scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  6374. if(get_bits_count(&s->gb) < bit_length){
  6375. pps->transform_8x8_mode= get_bits1(&s->gb);
  6376. decode_scaling_matrices(h, h->sps_buffers[pps->sps_id], pps, 0, pps->scaling_matrix4, pps->scaling_matrix8);
  6377. pps->chroma_qp_index_offset[1]= get_se_golomb(&s->gb); //second_chroma_qp_index_offset
  6378. } else {
  6379. pps->chroma_qp_index_offset[1]= pps->chroma_qp_index_offset[0];
  6380. }
  6381. build_qp_table(pps, 0, pps->chroma_qp_index_offset[0]);
  6382. build_qp_table(pps, 1, pps->chroma_qp_index_offset[1]);
  6383. if(pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1])
  6384. h->pps.chroma_qp_diff= 1;
  6385. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6386. 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",
  6387. pps_id, pps->sps_id,
  6388. pps->cabac ? "CABAC" : "CAVLC",
  6389. pps->slice_group_count,
  6390. pps->ref_count[0], pps->ref_count[1],
  6391. pps->weighted_pred ? "weighted" : "",
  6392. pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1],
  6393. pps->deblocking_filter_parameters_present ? "LPAR" : "",
  6394. pps->constrained_intra_pred ? "CONSTR" : "",
  6395. pps->redundant_pic_cnt_present ? "REDU" : "",
  6396. pps->transform_8x8_mode ? "8x8DCT" : ""
  6397. );
  6398. }
  6399. return 0;
  6400. }
  6401. /**
  6402. * Call decode_slice() for each context.
  6403. *
  6404. * @param h h264 master context
  6405. * @param context_count number of contexts to execute
  6406. */
  6407. static void execute_decode_slices(H264Context *h, int context_count){
  6408. MpegEncContext * const s = &h->s;
  6409. AVCodecContext * const avctx= s->avctx;
  6410. H264Context *hx;
  6411. int i;
  6412. if(context_count == 1) {
  6413. decode_slice(avctx, h);
  6414. } else {
  6415. for(i = 1; i < context_count; i++) {
  6416. hx = h->thread_context[i];
  6417. hx->s.error_resilience = avctx->error_resilience;
  6418. hx->s.error_count = 0;
  6419. }
  6420. avctx->execute(avctx, (void *)decode_slice,
  6421. (void **)h->thread_context, NULL, context_count);
  6422. /* pull back stuff from slices to master context */
  6423. hx = h->thread_context[context_count - 1];
  6424. s->mb_x = hx->s.mb_x;
  6425. s->mb_y = hx->s.mb_y;
  6426. s->dropable = hx->s.dropable;
  6427. s->picture_structure = hx->s.picture_structure;
  6428. for(i = 1; i < context_count; i++)
  6429. h->s.error_count += h->thread_context[i]->s.error_count;
  6430. }
  6431. }
  6432. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
  6433. MpegEncContext * const s = &h->s;
  6434. AVCodecContext * const avctx= s->avctx;
  6435. int buf_index=0;
  6436. H264Context *hx; ///< thread context
  6437. int context_count = 0;
  6438. h->max_contexts = avctx->thread_count;
  6439. #if 0
  6440. int i;
  6441. for(i=0; i<50; i++){
  6442. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  6443. }
  6444. #endif
  6445. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  6446. h->current_slice = 0;
  6447. if (!s->first_field)
  6448. s->current_picture_ptr= NULL;
  6449. }
  6450. for(;;){
  6451. int consumed;
  6452. int dst_length;
  6453. int bit_length;
  6454. const uint8_t *ptr;
  6455. int i, nalsize = 0;
  6456. int err;
  6457. if(h->is_avc) {
  6458. if(buf_index >= buf_size) break;
  6459. nalsize = 0;
  6460. for(i = 0; i < h->nal_length_size; i++)
  6461. nalsize = (nalsize << 8) | buf[buf_index++];
  6462. if(nalsize <= 1 || (nalsize+buf_index > buf_size)){
  6463. if(nalsize == 1){
  6464. buf_index++;
  6465. continue;
  6466. }else{
  6467. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  6468. break;
  6469. }
  6470. }
  6471. } else {
  6472. // start code prefix search
  6473. for(; buf_index + 3 < buf_size; buf_index++){
  6474. // This should always succeed in the first iteration.
  6475. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  6476. break;
  6477. }
  6478. if(buf_index+3 >= buf_size) break;
  6479. buf_index+=3;
  6480. }
  6481. hx = h->thread_context[context_count];
  6482. ptr= decode_nal(hx, buf + buf_index, &dst_length, &consumed, h->is_avc ? nalsize : buf_size - buf_index);
  6483. if (ptr==NULL || dst_length < 0){
  6484. return -1;
  6485. }
  6486. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  6487. dst_length--;
  6488. bit_length= !dst_length ? 0 : (8*dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1));
  6489. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  6490. 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);
  6491. }
  6492. if (h->is_avc && (nalsize != consumed)){
  6493. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  6494. consumed= nalsize;
  6495. }
  6496. buf_index += consumed;
  6497. if( (s->hurry_up == 1 && h->nal_ref_idc == 0) //FIXME do not discard SEI id
  6498. ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  6499. continue;
  6500. again:
  6501. err = 0;
  6502. switch(hx->nal_unit_type){
  6503. case NAL_IDR_SLICE:
  6504. if (h->nal_unit_type != NAL_IDR_SLICE) {
  6505. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  6506. return -1;
  6507. }
  6508. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  6509. case NAL_SLICE:
  6510. init_get_bits(&hx->s.gb, ptr, bit_length);
  6511. hx->intra_gb_ptr=
  6512. hx->inter_gb_ptr= &hx->s.gb;
  6513. hx->s.data_partitioning = 0;
  6514. if((err = decode_slice_header(hx, h)))
  6515. break;
  6516. s->current_picture_ptr->key_frame|= (hx->nal_unit_type == NAL_IDR_SLICE);
  6517. if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
  6518. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6519. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  6520. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  6521. && avctx->skip_frame < AVDISCARD_ALL)
  6522. context_count++;
  6523. break;
  6524. case NAL_DPA:
  6525. init_get_bits(&hx->s.gb, ptr, bit_length);
  6526. hx->intra_gb_ptr=
  6527. hx->inter_gb_ptr= NULL;
  6528. hx->s.data_partitioning = 1;
  6529. err = decode_slice_header(hx, h);
  6530. break;
  6531. case NAL_DPB:
  6532. init_get_bits(&hx->intra_gb, ptr, bit_length);
  6533. hx->intra_gb_ptr= &hx->intra_gb;
  6534. break;
  6535. case NAL_DPC:
  6536. init_get_bits(&hx->inter_gb, ptr, bit_length);
  6537. hx->inter_gb_ptr= &hx->inter_gb;
  6538. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  6539. && s->context_initialized
  6540. && s->hurry_up < 5
  6541. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6542. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  6543. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  6544. && avctx->skip_frame < AVDISCARD_ALL)
  6545. context_count++;
  6546. break;
  6547. case NAL_SEI:
  6548. init_get_bits(&s->gb, ptr, bit_length);
  6549. decode_sei(h);
  6550. break;
  6551. case NAL_SPS:
  6552. init_get_bits(&s->gb, ptr, bit_length);
  6553. decode_seq_parameter_set(h);
  6554. if(s->flags& CODEC_FLAG_LOW_DELAY)
  6555. s->low_delay=1;
  6556. if(avctx->has_b_frames < 2)
  6557. avctx->has_b_frames= !s->low_delay;
  6558. break;
  6559. case NAL_PPS:
  6560. init_get_bits(&s->gb, ptr, bit_length);
  6561. decode_picture_parameter_set(h, bit_length);
  6562. break;
  6563. case NAL_AUD:
  6564. case NAL_END_SEQUENCE:
  6565. case NAL_END_STREAM:
  6566. case NAL_FILLER_DATA:
  6567. case NAL_SPS_EXT:
  6568. case NAL_AUXILIARY_SLICE:
  6569. break;
  6570. default:
  6571. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", h->nal_unit_type, bit_length);
  6572. }
  6573. if(context_count == h->max_contexts) {
  6574. execute_decode_slices(h, context_count);
  6575. context_count = 0;
  6576. }
  6577. if (err < 0)
  6578. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  6579. else if(err == 1) {
  6580. /* Slice could not be decoded in parallel mode, copy down
  6581. * NAL unit stuff to context 0 and restart. Note that
  6582. * rbsp_buffer is not transferred, but since we no longer
  6583. * run in parallel mode this should not be an issue. */
  6584. h->nal_unit_type = hx->nal_unit_type;
  6585. h->nal_ref_idc = hx->nal_ref_idc;
  6586. hx = h;
  6587. goto again;
  6588. }
  6589. }
  6590. if(context_count)
  6591. execute_decode_slices(h, context_count);
  6592. return buf_index;
  6593. }
  6594. /**
  6595. * returns the number of bytes consumed for building the current frame
  6596. */
  6597. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  6598. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  6599. if(pos+10>buf_size) pos=buf_size; // oops ;)
  6600. return pos;
  6601. }
  6602. static int decode_frame(AVCodecContext *avctx,
  6603. void *data, int *data_size,
  6604. const uint8_t *buf, int buf_size)
  6605. {
  6606. H264Context *h = avctx->priv_data;
  6607. MpegEncContext *s = &h->s;
  6608. AVFrame *pict = data;
  6609. int buf_index;
  6610. s->flags= avctx->flags;
  6611. s->flags2= avctx->flags2;
  6612. /* end of stream, output what is still in the buffers */
  6613. if (buf_size == 0) {
  6614. Picture *out;
  6615. int i, out_idx;
  6616. //FIXME factorize this with the output code below
  6617. out = h->delayed_pic[0];
  6618. out_idx = 0;
  6619. for(i=1; h->delayed_pic[i] && h->delayed_pic[i]->poc; i++)
  6620. if(h->delayed_pic[i]->poc < out->poc){
  6621. out = h->delayed_pic[i];
  6622. out_idx = i;
  6623. }
  6624. for(i=out_idx; h->delayed_pic[i]; i++)
  6625. h->delayed_pic[i] = h->delayed_pic[i+1];
  6626. if(out){
  6627. *data_size = sizeof(AVFrame);
  6628. *pict= *(AVFrame*)out;
  6629. }
  6630. return 0;
  6631. }
  6632. if(h->is_avc && !h->got_avcC) {
  6633. int i, cnt, nalsize;
  6634. unsigned char *p = avctx->extradata;
  6635. if(avctx->extradata_size < 7) {
  6636. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  6637. return -1;
  6638. }
  6639. if(*p != 1) {
  6640. av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);
  6641. return -1;
  6642. }
  6643. /* sps and pps in the avcC always have length coded with 2 bytes,
  6644. so put a fake nal_length_size = 2 while parsing them */
  6645. h->nal_length_size = 2;
  6646. // Decode sps from avcC
  6647. cnt = *(p+5) & 0x1f; // Number of sps
  6648. p += 6;
  6649. for (i = 0; i < cnt; i++) {
  6650. nalsize = AV_RB16(p) + 2;
  6651. if(decode_nal_units(h, p, nalsize) < 0) {
  6652. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  6653. return -1;
  6654. }
  6655. p += nalsize;
  6656. }
  6657. // Decode pps from avcC
  6658. cnt = *(p++); // Number of pps
  6659. for (i = 0; i < cnt; i++) {
  6660. nalsize = AV_RB16(p) + 2;
  6661. if(decode_nal_units(h, p, nalsize) != nalsize) {
  6662. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  6663. return -1;
  6664. }
  6665. p += nalsize;
  6666. }
  6667. // Now store right nal length size, that will be use to parse all other nals
  6668. h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
  6669. // Do not reparse avcC
  6670. h->got_avcC = 1;
  6671. }
  6672. if(avctx->frame_number==0 && !h->is_avc && s->avctx->extradata_size){
  6673. if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)
  6674. return -1;
  6675. }
  6676. buf_index=decode_nal_units(h, buf, buf_size);
  6677. if(buf_index < 0)
  6678. return -1;
  6679. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  6680. if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
  6681. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  6682. return -1;
  6683. }
  6684. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  6685. Picture *out = s->current_picture_ptr;
  6686. Picture *cur = s->current_picture_ptr;
  6687. int i, pics, cross_idr, out_of_order, out_idx;
  6688. s->mb_y= 0;
  6689. s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
  6690. s->current_picture_ptr->pict_type= s->pict_type;
  6691. if(!s->dropable) {
  6692. execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  6693. h->prev_poc_msb= h->poc_msb;
  6694. h->prev_poc_lsb= h->poc_lsb;
  6695. }
  6696. h->prev_frame_num_offset= h->frame_num_offset;
  6697. h->prev_frame_num= h->frame_num;
  6698. /*
  6699. * FIXME: Error handling code does not seem to support interlaced
  6700. * when slices span multiple rows
  6701. * The ff_er_add_slice calls don't work right for bottom
  6702. * fields; they cause massive erroneous error concealing
  6703. * Error marking covers both fields (top and bottom).
  6704. * This causes a mismatched s->error_count
  6705. * and a bad error table. Further, the error count goes to
  6706. * INT_MAX when called for bottom field, because mb_y is
  6707. * past end by one (callers fault) and resync_mb_y != 0
  6708. * causes problems for the first MB line, too.
  6709. */
  6710. if (!FIELD_PICTURE)
  6711. ff_er_frame_end(s);
  6712. MPV_frame_end(s);
  6713. if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
  6714. /* Wait for second field. */
  6715. *data_size = 0;
  6716. } else {
  6717. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  6718. /* Derive top_field_first from field pocs. */
  6719. cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  6720. //FIXME do something with unavailable reference frames
  6721. /* Sort B-frames into display order */
  6722. if(h->sps.bitstream_restriction_flag
  6723. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  6724. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  6725. s->low_delay = 0;
  6726. }
  6727. if( s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
  6728. && !h->sps.bitstream_restriction_flag){
  6729. s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
  6730. s->low_delay= 0;
  6731. }
  6732. pics = 0;
  6733. while(h->delayed_pic[pics]) pics++;
  6734. assert(pics <= MAX_DELAYED_PIC_COUNT);
  6735. h->delayed_pic[pics++] = cur;
  6736. if(cur->reference == 0)
  6737. cur->reference = DELAYED_PIC_REF;
  6738. out = h->delayed_pic[0];
  6739. out_idx = 0;
  6740. for(i=1; h->delayed_pic[i] && h->delayed_pic[i]->poc; i++)
  6741. if(h->delayed_pic[i]->poc < out->poc){
  6742. out = h->delayed_pic[i];
  6743. out_idx = i;
  6744. }
  6745. cross_idr = !h->delayed_pic[0]->poc || !!h->delayed_pic[i];
  6746. out_of_order = !cross_idr && out->poc < h->outputed_poc;
  6747. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  6748. { }
  6749. else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
  6750. || (s->low_delay &&
  6751. ((!cross_idr && out->poc > h->outputed_poc + 2)
  6752. || cur->pict_type == FF_B_TYPE)))
  6753. {
  6754. s->low_delay = 0;
  6755. s->avctx->has_b_frames++;
  6756. }
  6757. if(out_of_order || pics > s->avctx->has_b_frames){
  6758. out->reference &= ~DELAYED_PIC_REF;
  6759. for(i=out_idx; h->delayed_pic[i]; i++)
  6760. h->delayed_pic[i] = h->delayed_pic[i+1];
  6761. }
  6762. if(!out_of_order && pics > s->avctx->has_b_frames){
  6763. *data_size = sizeof(AVFrame);
  6764. h->outputed_poc = out->poc;
  6765. *pict= *(AVFrame*)out;
  6766. }else{
  6767. av_log(avctx, AV_LOG_DEBUG, "no picture\n");
  6768. }
  6769. }
  6770. }
  6771. assert(pict->data[0] || !*data_size);
  6772. ff_print_debug_info(s, pict);
  6773. //printf("out %d\n", (int)pict->data[0]);
  6774. #if 0 //?
  6775. /* Return the Picture timestamp as the frame number */
  6776. /* we subtract 1 because it is added on utils.c */
  6777. avctx->frame_number = s->picture_number - 1;
  6778. #endif
  6779. return get_consumed_bytes(s, buf_index, buf_size);
  6780. }
  6781. #if 0
  6782. static inline void fill_mb_avail(H264Context *h){
  6783. MpegEncContext * const s = &h->s;
  6784. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  6785. if(s->mb_y){
  6786. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  6787. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  6788. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  6789. }else{
  6790. h->mb_avail[0]=
  6791. h->mb_avail[1]=
  6792. h->mb_avail[2]= 0;
  6793. }
  6794. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  6795. h->mb_avail[4]= 1; //FIXME move out
  6796. h->mb_avail[5]= 0; //FIXME move out
  6797. }
  6798. #endif
  6799. #ifdef TEST
  6800. #undef printf
  6801. #undef random
  6802. #define COUNT 8000
  6803. #define SIZE (COUNT*40)
  6804. int main(void){
  6805. int i;
  6806. uint8_t temp[SIZE];
  6807. PutBitContext pb;
  6808. GetBitContext gb;
  6809. // int int_temp[10000];
  6810. DSPContext dsp;
  6811. AVCodecContext avctx;
  6812. dsputil_init(&dsp, &avctx);
  6813. init_put_bits(&pb, temp, SIZE);
  6814. printf("testing unsigned exp golomb\n");
  6815. for(i=0; i<COUNT; i++){
  6816. START_TIMER
  6817. set_ue_golomb(&pb, i);
  6818. STOP_TIMER("set_ue_golomb");
  6819. }
  6820. flush_put_bits(&pb);
  6821. init_get_bits(&gb, temp, 8*SIZE);
  6822. for(i=0; i<COUNT; i++){
  6823. int j, s;
  6824. s= show_bits(&gb, 24);
  6825. START_TIMER
  6826. j= get_ue_golomb(&gb);
  6827. if(j != i){
  6828. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6829. // return -1;
  6830. }
  6831. STOP_TIMER("get_ue_golomb");
  6832. }
  6833. init_put_bits(&pb, temp, SIZE);
  6834. printf("testing signed exp golomb\n");
  6835. for(i=0; i<COUNT; i++){
  6836. START_TIMER
  6837. set_se_golomb(&pb, i - COUNT/2);
  6838. STOP_TIMER("set_se_golomb");
  6839. }
  6840. flush_put_bits(&pb);
  6841. init_get_bits(&gb, temp, 8*SIZE);
  6842. for(i=0; i<COUNT; i++){
  6843. int j, s;
  6844. s= show_bits(&gb, 24);
  6845. START_TIMER
  6846. j= get_se_golomb(&gb);
  6847. if(j != i - COUNT/2){
  6848. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6849. // return -1;
  6850. }
  6851. STOP_TIMER("get_se_golomb");
  6852. }
  6853. #if 0
  6854. printf("testing 4x4 (I)DCT\n");
  6855. DCTELEM block[16];
  6856. uint8_t src[16], ref[16];
  6857. uint64_t error= 0, max_error=0;
  6858. for(i=0; i<COUNT; i++){
  6859. int j;
  6860. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  6861. for(j=0; j<16; j++){
  6862. ref[j]= random()%255;
  6863. src[j]= random()%255;
  6864. }
  6865. h264_diff_dct_c(block, src, ref, 4);
  6866. //normalize
  6867. for(j=0; j<16; j++){
  6868. // printf("%d ", block[j]);
  6869. block[j]= block[j]*4;
  6870. if(j&1) block[j]= (block[j]*4 + 2)/5;
  6871. if(j&4) block[j]= (block[j]*4 + 2)/5;
  6872. }
  6873. // printf("\n");
  6874. s->dsp.h264_idct_add(ref, block, 4);
  6875. /* for(j=0; j<16; j++){
  6876. printf("%d ", ref[j]);
  6877. }
  6878. printf("\n");*/
  6879. for(j=0; j<16; j++){
  6880. int diff= FFABS(src[j] - ref[j]);
  6881. error+= diff*diff;
  6882. max_error= FFMAX(max_error, diff);
  6883. }
  6884. }
  6885. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  6886. printf("testing quantizer\n");
  6887. for(qp=0; qp<52; qp++){
  6888. for(i=0; i<16; i++)
  6889. src1_block[i]= src2_block[i]= random()%255;
  6890. }
  6891. printf("Testing NAL layer\n");
  6892. uint8_t bitstream[COUNT];
  6893. uint8_t nal[COUNT*2];
  6894. H264Context h;
  6895. memset(&h, 0, sizeof(H264Context));
  6896. for(i=0; i<COUNT; i++){
  6897. int zeros= i;
  6898. int nal_length;
  6899. int consumed;
  6900. int out_length;
  6901. uint8_t *out;
  6902. int j;
  6903. for(j=0; j<COUNT; j++){
  6904. bitstream[j]= (random() % 255) + 1;
  6905. }
  6906. for(j=0; j<zeros; j++){
  6907. int pos= random() % COUNT;
  6908. while(bitstream[pos] == 0){
  6909. pos++;
  6910. pos %= COUNT;
  6911. }
  6912. bitstream[pos]=0;
  6913. }
  6914. START_TIMER
  6915. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  6916. if(nal_length<0){
  6917. printf("encoding failed\n");
  6918. return -1;
  6919. }
  6920. out= decode_nal(&h, nal, &out_length, &consumed, nal_length);
  6921. STOP_TIMER("NAL")
  6922. if(out_length != COUNT){
  6923. printf("incorrect length %d %d\n", out_length, COUNT);
  6924. return -1;
  6925. }
  6926. if(consumed != nal_length){
  6927. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  6928. return -1;
  6929. }
  6930. if(memcmp(bitstream, out, COUNT)){
  6931. printf("mismatch\n");
  6932. return -1;
  6933. }
  6934. }
  6935. #endif
  6936. printf("Testing RBSP\n");
  6937. return 0;
  6938. }
  6939. #endif /* TEST */
  6940. static av_cold int decode_end(AVCodecContext *avctx)
  6941. {
  6942. H264Context *h = avctx->priv_data;
  6943. MpegEncContext *s = &h->s;
  6944. av_freep(&h->rbsp_buffer[0]);
  6945. av_freep(&h->rbsp_buffer[1]);
  6946. free_tables(h); //FIXME cleanup init stuff perhaps
  6947. MPV_common_end(s);
  6948. // memset(h, 0, sizeof(H264Context));
  6949. return 0;
  6950. }
  6951. AVCodec h264_decoder = {
  6952. "h264",
  6953. CODEC_TYPE_VIDEO,
  6954. CODEC_ID_H264,
  6955. sizeof(H264Context),
  6956. decode_init,
  6957. NULL,
  6958. decode_end,
  6959. decode_frame,
  6960. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY,
  6961. .flush= flush_dpb,
  6962. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  6963. };
  6964. #include "svq3.c"