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.

7930 lines
306KB

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