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.

7996 lines
309KB

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